Skip to main content

foundry_cli/opts/build/
core.rs

1use super::ProjectPathOpts;
2use crate::{opts::CompilerOpts, utils::LoadConfig};
3use clap::{Parser, ValueHint};
4use eyre::Result;
5use foundry_compilers::{
6    Project,
7    artifacts::{RevertStrings, remappings::Remapping},
8    compilers::multi::MultiCompiler,
9    utils::canonicalized,
10};
11use foundry_config::{
12    Config, DenyLevel, Remappings,
13    figment::{
14        self, Figment, Metadata, Profile, Provider,
15        error::Kind::InvalidType,
16        value::{Dict, Map, Value},
17    },
18    filter::SkipBuildFilter,
19    providers::relative_remapping_preserving_context_boundary,
20};
21use serde::Serialize;
22use std::path::PathBuf;
23
24#[derive(Clone, Debug, Default, Serialize, Parser)]
25#[command(next_help_heading = "Build options")]
26pub struct BuildOpts {
27    /// Clear the cache and artifacts folder and recompile.
28    #[arg(long, help_heading = "Cache options")]
29    #[serde(skip)]
30    pub force: bool,
31
32    /// Disable the cache.
33    #[arg(long)]
34    #[serde(skip)]
35    pub no_cache: bool,
36
37    /// Disable dynamic test linking.
38    #[arg(long, conflicts_with = "no_cache")]
39    #[serde(skip)]
40    pub no_dynamic_test_linking: bool,
41
42    /// Reject contracts that depend on externally linked Solidity libraries.
43    ///
44    /// Internal libraries and dynamic test linking remain available. Overrides
45    /// `allow_linked_libraries` in configuration and environment variables.
46    #[arg(long, help_heading = "Linker options")]
47    #[serde(skip)]
48    pub disallow_linked_libraries: bool,
49
50    /// Set pre-linked libraries.
51    #[arg(long, help_heading = "Linker options", env = "DAPP_LIBRARIES")]
52    #[serde(skip_serializing_if = "Vec::is_empty")]
53    pub libraries: Vec<String>,
54
55    /// Ignore solc warnings by error code.
56    #[arg(long, help_heading = "Compiler options", value_name = "ERROR_CODES")]
57    #[serde(skip_serializing_if = "Vec::is_empty")]
58    pub ignored_error_codes: Vec<u64>,
59
60    /// A compiler error will be triggered at the specified diagnostic level.
61    ///
62    /// Replaces the deprecated `--deny-warnings` flag.
63    ///
64    /// Possible values:
65    ///  - `never`: Do not treat any diagnostics as errors.
66    ///  - `warnings`: Treat warnings as errors.
67    ///  - `notes`: Treat both, warnings and notes, as errors.
68    #[arg(
69        long,
70        short = 'D',
71        help_heading = "Compiler options",
72        value_name = "LEVEL",
73        conflicts_with = "deny_warnings"
74    )]
75    #[serde(skip)]
76    pub deny: Option<DenyLevel>,
77
78    /// Deprecated: use `--deny=warnings` instead.
79    #[arg(long = "deny-warnings", hide = true)]
80    pub deny_warnings: bool,
81
82    /// Do not auto-detect the `solc` version.
83    #[arg(long, help_heading = "Compiler options")]
84    #[serde(skip)]
85    pub no_auto_detect: bool,
86
87    /// Specify the solc version, Solar version, path, or executable name on `PATH` to build with.
88    ///
89    /// Valid values are in the format `x.y.z`, `solc:x.y.z`, `solar:x.y.z`, `path/to/solc`, or
90    /// `solc`.
91    #[arg(
92        long = "use",
93        alias = "compiler-version",
94        help_heading = "Compiler options",
95        value_name = "SOLC_VERSION"
96    )]
97    #[serde(skip)]
98    pub use_solc: Option<String>,
99
100    /// Do not access the network.
101    ///
102    /// Missing solc versions and Solar releases will not be installed.
103    #[arg(help_heading = "Compiler options", long)]
104    #[serde(skip)]
105    pub offline: bool,
106
107    /// Changes compilation to only use literal content and not URLs.
108    #[arg(long, help_heading = "Compiler options")]
109    #[serde(skip)]
110    pub use_literal_content: bool,
111
112    /// Do not append any metadata to the bytecode.
113    ///
114    /// This is equivalent to setting `bytecode_hash` to `none` and `cbor_metadata` to `false`.
115    #[arg(long, help_heading = "Compiler options")]
116    #[serde(skip)]
117    pub no_metadata: bool,
118
119    /// The path to the contract artifacts folder.
120    #[arg(
121        long = "out",
122        short,
123        help_heading = "Project options",
124        value_hint = ValueHint::DirPath,
125        value_name = "PATH",
126    )]
127    #[serde(rename = "out", skip_serializing_if = "Option::is_none")]
128    pub out_path: Option<PathBuf>,
129
130    /// Revert string configuration.
131    ///
132    /// Possible values are "default", "strip" (remove),
133    /// "debug" (Solidity-generated revert strings) and "verboseDebug"
134    #[arg(long, help_heading = "Project options", value_name = "REVERT")]
135    #[serde(skip)]
136    pub revert_strings: Option<RevertStrings>,
137
138    /// Generate build info files.
139    #[arg(long, help_heading = "Project options")]
140    #[serde(skip)]
141    pub build_info: bool,
142
143    /// Output path to directory that build info files will be written to.
144    #[arg(
145        long,
146        help_heading = "Project options",
147        value_hint = ValueHint::DirPath,
148        value_name = "PATH",
149        requires = "build_info",
150    )]
151    #[serde(skip_serializing_if = "Option::is_none")]
152    pub build_info_path: Option<PathBuf>,
153
154    /// Skip building files whose names contain the given filter.
155    ///
156    /// `test` and `script` are aliases for `.t.sol` and `.s.sol`.
157    #[arg(long, num_args(1..))]
158    #[serde(skip)]
159    pub skip: Option<Vec<SkipBuildFilter>>,
160
161    #[command(flatten)]
162    #[serde(flatten)]
163    pub compiler: CompilerOpts,
164
165    #[command(flatten)]
166    #[serde(flatten)]
167    pub project_paths: ProjectPathOpts,
168}
169
170impl BuildOpts {
171    /// Returns the `Project` for the current workspace
172    ///
173    /// This loads the `foundry_config::Config` for the current workspace (see
174    /// `find_project_root` and merges the cli `BuildArgs` into it before returning
175    /// [`foundry_config::Config::project()`]).
176    pub fn project(&self) -> Result<Project<MultiCompiler>> {
177        let config = self.load_config()?;
178        Ok(config.project()?)
179    }
180
181    /// Returns the remappings to add to the config
182    #[deprecated(note = "Use ProjectPathsArgs::get_remappings() instead")]
183    pub fn get_remappings(&self) -> Vec<Remapping> {
184        self.project_paths.get_remappings()
185    }
186}
187
188// Loads project's figment and merges the build cli arguments into it
189impl<'a> From<&'a BuildOpts> for Figment {
190    fn from(args: &'a BuildOpts) -> Self {
191        let root = args.project_paths.project_root();
192        let mut figment = Config::figment_with_root(&root);
193
194        // remappings should stack
195        let remappings_root = canonicalized(&root);
196        let cli_remappings = args
197            .project_paths
198            .get_remappings()
199            .into_iter()
200            .map(|remapping| {
201                let remapping = relative_remapping_preserving_context_boundary(remapping, &root)
202                    .to_relative_remapping();
203                relative_remapping_preserving_context_boundary(remapping, &remappings_root)
204                    .to_relative_remapping()
205            })
206            .collect();
207        let mut remappings = Remappings::new_with_remappings(cli_remappings).with_figment(&figment);
208        let generated_remappings = Remappings::generated_from_figment(&figment);
209        let warnings = remappings.warnings_from_figment(&figment);
210        remappings.extend_with_config_remappings(
211            figment.extract_inner::<Vec<Remapping>>("remappings").unwrap_or_default(),
212            &generated_remappings,
213        );
214        let remappings = remappings
215            .into_inner()
216            .into_iter()
217            .map(|remapping| relative_remapping_preserving_context_boundary(remapping, &root))
218            .collect::<Vec<_>>();
219        figment =
220            figment.merge(("remappings", remappings)).merge(("__warnings", warnings)).merge(args);
221
222        if let Some(skip) = &args.skip {
223            let mut skip = skip.iter().map(|s| s.file_pattern().to_string()).collect::<Vec<_>>();
224            skip.extend(figment.extract_inner::<Vec<String>>("skip").unwrap_or_default());
225            figment = figment.merge(("skip", skip));
226        };
227
228        figment
229    }
230}
231
232impl Provider for BuildOpts {
233    fn metadata(&self) -> Metadata {
234        Metadata::named("Core Build Args Provider")
235    }
236
237    fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
238        let value = Value::serialize(self)?;
239        let error = InvalidType(value.to_actual(), "map".into());
240        let mut dict = value.into_dict().ok_or(error)?;
241
242        if self.no_auto_detect {
243            dict.insert("auto_detect_solc".to_string(), false.into());
244        }
245
246        if let Some(ref solc) = self.use_solc {
247            dict.insert("solc".to_string(), solc.trim_start_matches("solc:").into());
248        }
249
250        if self.offline {
251            dict.insert("offline".to_string(), true.into());
252        }
253
254        if self.deny_warnings {
255            dict.insert("deny".to_string(), figment::value::Value::serialize(DenyLevel::Warnings)?);
256            _ = sh_warn!("`--deny-warnings` is being deprecated in favor of `--deny warnings`.");
257        } else if let Some(deny) = self.deny {
258            dict.insert("deny".to_string(), figment::value::Value::serialize(deny)?);
259        }
260
261        if self.use_literal_content {
262            dict.insert("use_literal_content".to_string(), true.into());
263        }
264
265        if self.no_metadata {
266            dict.insert("bytecode_hash".to_string(), "none".into());
267            dict.insert("cbor_metadata".to_string(), false.into());
268        }
269
270        if self.force {
271            dict.insert("force".to_string(), self.force.into());
272        }
273
274        // we need to ensure no_cache set accordingly
275        if self.no_cache {
276            dict.insert("cache".to_string(), false.into());
277        }
278
279        if self.no_dynamic_test_linking {
280            dict.insert("dynamic_test_linking".to_string(), false.into());
281        }
282
283        if self.build_info {
284            dict.insert("build_info".to_string(), self.build_info.into());
285        }
286
287        if self.compiler.ast {
288            dict.insert("ast".to_string(), true.into());
289        }
290
291        if let Some(optimize) = self.compiler.optimize {
292            dict.insert("optimizer".to_string(), optimize.into());
293        }
294
295        if self.compiler.via_ir {
296            dict.insert("via_ir".to_string(), true.into());
297        }
298
299        if self.compiler.via_ssa_cfg {
300            dict.insert("via_ssa_cfg".to_string(), true.into());
301        }
302
303        if self.compiler.experimental {
304            dict.insert("experimental".to_string(), true.into());
305        }
306
307        if !self.compiler.extra_output.is_empty() {
308            let selection: Vec<_> =
309                self.compiler.extra_output.iter().map(|s| s.to_string()).collect();
310            dict.insert("extra_output".to_string(), selection.into());
311        }
312
313        if !self.compiler.extra_output_files.is_empty() {
314            let selection: Vec<_> =
315                self.compiler.extra_output_files.iter().map(|s| s.to_string()).collect();
316            dict.insert("extra_output_files".to_string(), selection.into());
317        }
318
319        if let Some(ref revert) = self.revert_strings {
320            dict.insert("revert_strings".to_string(), revert.to_string().into());
321        }
322
323        let mut data = Map::from([(Config::selected_profile(), dict)]);
324        if self.disallow_linked_libraries {
325            // Environment variables use the global profile, which wins over named profiles.
326            data.entry(Profile::Global)
327                .or_default()
328                .insert("allow_linked_libraries".to_string(), false.into());
329        }
330        Ok(data)
331    }
332}