Skip to main content

forge/cmd/
build.rs

1use super::watch::WatchArgs;
2use crate::Lockfile;
3use clap::Parser;
4use eyre::Result;
5use forge_lint::{
6    linter::Linter,
7    sol::{DeniedLintDiagnostics, SolidityLinter},
8};
9use foundry_cli::{
10    opts::{BuildOpts, configure_pcx_from_solc, get_solar_sources_from_compile_output},
11    utils::{Git, LoadConfig, cache_local_signatures},
12};
13use foundry_common::{
14    compile::{ContractSizeLimits, ProjectCompiler},
15    shell,
16};
17use foundry_compilers::{
18    CompilationError, FileFilter, Project, ProjectCompileOutput,
19    compilers::{Language, multi::MultiCompilerLanguage},
20    solc::SolcLanguage,
21    utils::source_files_iter,
22};
23use foundry_config::{
24    Config, SkipBuildFilters,
25    figment::{
26        self, Metadata, Profile, Provider,
27        error::Kind::InvalidType,
28        value::{Dict, Map, Value},
29    },
30    filter::{expand_globs, is_ignored_path},
31};
32use serde::Serialize;
33use solar::{
34    interface::{Session, config::CompileOpts},
35    sema::Compiler,
36};
37use soldeer_core::install::DependencyStatus;
38use std::{fmt::Write, path::PathBuf};
39
40foundry_config::merge_impl_figment_convert!(BuildArgs, build);
41
42/// CLI arguments for `forge build`.
43///
44/// CLI arguments take the highest precedence in the Config/Figment hierarchy.
45/// In order to override them in the foundry `Config` they need to be merged into an existing
46/// `figment::Provider`, like `foundry_config::Config` is.
47///
48/// `BuildArgs` implements `figment::Provider` in which all config related fields are serialized and
49/// then merged into an existing `Config`, effectively overwriting them.
50///
51/// Some arguments are marked as `#[serde(skip)]` and require manual processing in
52/// `figment::Provider` implementation
53#[derive(Clone, Debug, Default, Serialize, Parser)]
54#[command(next_help_heading = "Build options", about = None, long_about = None)] // override doc
55pub struct BuildArgs {
56    /// Build source files from specified paths.
57    #[serde(skip)]
58    pub paths: Option<Vec<PathBuf>>,
59
60    /// Print compiled contract names.
61    #[arg(long)]
62    #[serde(skip)]
63    pub names: bool,
64
65    /// Print compiled contract sizes.
66    /// Constructor argument length is not included in the calculation of initcode size.
67    #[arg(long)]
68    #[serde(skip)]
69    pub sizes: bool,
70
71    /// Ignore initcode contract bytecode size limit introduced by EIP-3860.
72    #[arg(long, alias = "ignore-initcode-size")]
73    #[serde(skip)]
74    pub ignore_eip_3860: bool,
75
76    /// Skip the post-build lint step for this invocation.
77    ///
78    /// Equivalent to setting `lint_on_build = false` under `[lint]` in foundry.toml,
79    /// but only for the current command.
80    #[arg(long, visible_alias = "skip-lint")]
81    #[serde(skip)]
82    pub no_lint: bool,
83
84    #[command(flatten)]
85    #[serde(flatten)]
86    pub build: BuildOpts,
87
88    #[command(flatten)]
89    #[serde(skip)]
90    pub watch: WatchArgs,
91}
92
93impl BuildArgs {
94    pub async fn run(self, locked: bool) -> Result<ProjectCompileOutput> {
95        let mut config = self.load_config()?;
96
97        if locked {
98            self.check_foundry_lock_consistency(&config)?;
99        }
100
101        self.install_missing_dependencies(&mut config)?;
102
103        self.check_soldeer_lock_consistency(&config).await;
104
105        let project = config.project()?;
106
107        // Collect sources to compile if build subdirectories specified.
108        let mut files = vec![];
109        let mut selected_paths = vec![];
110        if let Some(paths) = &self.paths {
111            for path in paths {
112                let joined = project.root().join(path);
113                let path = if joined.exists() { &joined } else { path };
114                selected_paths.push(path.clone());
115                files.extend(source_files_iter(path, MultiCompilerLanguage::FILE_EXTENSIONS));
116            }
117            if files.is_empty() && config.external_compilers.is_empty() {
118                eyre::bail!("No source files found in specified build paths.");
119            }
120        }
121
122        let format_json = shell::is_json();
123
124        let mut output = ProjectCompiler::new()
125            .allow_linked_libraries(config.allow_linked_libraries)
126            .external_compilers(&config)
127            .files(files)
128            .selected_paths(selected_paths)
129            .dynamic_test_linking(config.dynamic_test_linking)
130            .print_compiler_settings(shell::verbosity() >= 2)
131            .print_names(self.names)
132            .print_sizes(self.sizes)
133            .ignore_eip_3860(self.ignore_eip_3860)
134            .size_limits(contract_size_limits(&config))
135            .bail(!format_json)
136            .compile(&project)?;
137
138        // Cache project selectors.
139        cache_local_signatures(&output)?;
140
141        if format_json && (!self.names && !self.sizes || output.has_compiler_errors()) {
142            sh_println!("{}", serde_json::to_string_pretty(&output.output())?)?;
143        }
144        if format_json && output.has_compiler_errors() {
145            std::process::exit(1);
146        }
147
148        // Only run the `SolidityLinter` if lint on build and no compilation errors.
149        if !self.no_lint
150            && config.lint.lint_on_build
151            && !output.output().errors.iter().any(|e| e.is_error())
152            && let Err(err) = self.lint(&project, &config, self.paths.as_deref(), &mut output)
153        {
154            if err.downcast_ref::<DeniedLintDiagnostics>().is_none() {
155                emit_lint_failure_notice();
156            }
157            return Err(err.wrap_err("post-build lint step failed"));
158        }
159
160        Ok(output)
161    }
162
163    fn lint(
164        &self,
165        project: &Project,
166        config: &Config,
167        files: Option<&[PathBuf]>,
168        output: &mut ProjectCompileOutput,
169    ) -> Result<()> {
170        let format_json = shell::is_json();
171        if project.compiler.solc.is_some() && !shell::is_quiet() {
172            let linter = SolidityLinter::new(config.project_paths())
173                .with_json_emitter(format_json)
174                .with_description(!format_json)
175                .with_severity(if config.lint.severity.is_empty() {
176                    None
177                } else {
178                    Some(config.lint.severity.clone())
179                })
180                .without_lints(if config.lint.exclude_lints.is_empty() {
181                    None
182                } else {
183                    Some(
184                        config
185                            .lint
186                            .exclude_lints
187                            .iter()
188                            .filter_map(|s| s.parse::<forge_lint::sol::SolLint>().ok())
189                            .collect(),
190                    )
191                })
192                .with_lint_specific(&config.lint.lint_specific);
193
194            // Expand ignore globs and canonicalize from the get go
195            let ignored = expand_globs(&config.root, config.lint.ignore.iter())?
196                .iter()
197                .flat_map(foundry_common::fs::canonicalize_path)
198                .collect::<Vec<_>>();
199
200            let skip = SkipBuildFilters::new(config.skip.clone(), config.root.clone());
201            let curr_dir = std::env::current_dir()?;
202            let input_files = config
203                .project_paths::<SolcLanguage>()
204                .input_files_iter()
205                .filter(|p| {
206                    // Lint only specified build files, if any.
207                    if let Some(files) = files {
208                        return files.iter().any(|file| &curr_dir.join(file) == p);
209                    }
210                    skip.is_match(p) && !is_ignored_path(p, &ignored, &curr_dir)
211                })
212                .collect::<Vec<_>>();
213
214            let solar_sources =
215                get_solar_sources_from_compile_output(config, output, Some(&input_files), None)?;
216            if solar_sources.input.sources.is_empty() {
217                if !input_files.is_empty() {
218                    sh_warn!("unable to lint. Solar only supports Solidity versions >=0.8.0")?;
219                }
220                return Ok(());
221            }
222
223            // NOTE(rusowsky): Once solar can drop unsupported versions, rather than creating a new
224            // compiler, we should reuse the parser from the project output.
225            let opts = CompileOpts::default();
226            let mut compiler =
227                Compiler::new(Session::builder().opts(opts).with_stderr_emitter().build());
228
229            // Load the solar-compatible sources to the pcx before linting
230            compiler.enter_mut(|compiler| {
231                let mut pcx = compiler.parse();
232                configure_pcx_from_solc(&mut pcx, &config.project_paths(), &solar_sources, true);
233                pcx.set_resolve_imports(true);
234                pcx.parse();
235            });
236
237            linter.lint(&input_files, config.deny, &mut compiler)?;
238        }
239
240        Ok(())
241    }
242
243    /// Returns the `Project` for the current workspace
244    ///
245    /// This loads the `foundry_config::Config` for the current workspace (see
246    /// [`foundry_config::utils::find_project_root`] and merges the cli `BuildArgs` into it before
247    /// returning [`foundry_config::Config::project()`]
248    pub fn project(&self) -> Result<Project> {
249        self.build.project()
250    }
251
252    /// Returns whether `BuildArgs` was configured with `--watch`
253    pub const fn is_watch(&self) -> bool {
254        self.watch.watch.is_some()
255    }
256
257    /// Returns the [`watchexec::Config`] necessary to bootstrap a new watch loop.
258    pub(crate) fn watchexec_config(&self) -> Result<watchexec::Config> {
259        // Use the path arguments or if none where provided the `src`, `test` and `script`
260        // directories as well as the `foundry.toml` configuration file.
261        self.watch.watchexec_config(|| {
262            let config = self.load_config()?;
263            let foundry_toml: PathBuf = config.root.join(Config::FILE_NAME);
264            Ok([config.src, config.test, config.script, foundry_toml])
265        })
266    }
267
268    /// Check soldeer.lock file consistency using soldeer_core APIs
269    async fn check_soldeer_lock_consistency(&self, config: &Config) {
270        let soldeer_lock_path = config.root.join("soldeer.lock");
271        if !soldeer_lock_path.exists() {
272            return;
273        }
274
275        // Note: read_lockfile returns Ok with empty entries for malformed files
276        let Ok(lockfile) = soldeer_core::lock::read_lockfile(&soldeer_lock_path) else {
277            return;
278        };
279
280        let deps_dir = config.root.join("dependencies");
281        for entry in &lockfile.entries {
282            let dep_name = entry.name();
283
284            // Use soldeer_core's integrity check
285            match soldeer_core::install::check_dependency_integrity(entry, &deps_dir).await {
286                Ok(status) => {
287                    // Check if status indicates a problem
288                    if matches!(
289                        status,
290                        DependencyStatus::Missing | DependencyStatus::FailedIntegrity
291                    ) {
292                        sh_warn!("Dependency '{}' integrity check failed: {:?}", dep_name, status)
293                            .ok();
294                    }
295                }
296                Err(e) => {
297                    sh_warn!("Dependency '{}' integrity check error: {}", dep_name, e).ok();
298                }
299            }
300        }
301    }
302
303    /// Checks foundry.lock file consistency with Git submodules.
304    fn check_foundry_lock_consistency(&self, config: &Config) -> Result<()> {
305        let git = Git::new(&config.root);
306        let mut lockfile = Lockfile::new(&config.root).with_git(&git);
307        let mismatches = lockfile.check()?;
308        if mismatches.is_empty() {
309            return Ok(());
310        }
311
312        let mut message = String::from("foundry.lock does not match installed dependencies:");
313        for mismatch in mismatches {
314            write!(message, "\n  {mismatch}")?;
315        }
316        Err(eyre::eyre!(message))
317    }
318}
319
320fn contract_size_limits(config: &Config) -> ContractSizeLimits {
321    config
322        .code_size_limit
323        .map(ContractSizeLimits::with_runtime_limit)
324        .or_else(|| {
325            config
326                .networks
327                .contract_size_limits()
328                .map(|limits| ContractSizeLimits::new(limits.runtime, limits.initcode))
329        })
330        .unwrap_or_else(|| ContractSizeLimits::for_spec_id(config.evm_spec_id()))
331}
332/// Notice shown on lint-on-build failure; printed separately so it survives single-line
333/// cause-chain rendering.
334const LINT_FAILURE_NOTICE: &str = "\
335note: internal lint engine failure (compilation itself succeeded).
336note: please file a bug report at
337      https://github.com/foundry-rs/foundry/issues/new?template=BUG-FORM.yml
338      and attach the full output above.
339help: rerun with `--no-lint` to skip linting for this build, or consider temporarily
340      disabling forge lint on build:
341      https://getfoundry.sh/forge/linting#disable-linting-on-build
342";
343
344fn emit_lint_failure_notice() {
345    if shell::is_json() {
346        return;
347    }
348    let _ = sh_eprintln!("\n{LINT_FAILURE_NOTICE}");
349}
350
351// Make this args a `figment::Provider` so that it can be merged into the `Config`
352impl Provider for BuildArgs {
353    fn metadata(&self) -> Metadata {
354        Metadata::named("Build Args Provider")
355    }
356
357    fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
358        let value = Value::serialize(self)?;
359        let error = InvalidType(value.to_actual(), "map".into());
360        let mut dict = value.into_dict().ok_or(error)?;
361
362        if self.names {
363            dict.insert("names".to_string(), true.into());
364        }
365
366        if self.sizes {
367            dict.insert("sizes".to_string(), true.into());
368        }
369
370        if self.ignore_eip_3860 {
371            dict.insert("ignore_eip_3860".to_string(), true.into());
372        }
373
374        Ok(Map::from([(Config::selected_profile(), dict)]))
375    }
376}