1use super::watch::WatchArgs;
2use clap::{Parser, ValueHint};
3use eyre::Result;
4use foundry_cli::utils::{FoundryPathExt, LoadConfig};
5use foundry_common::{errors::convert_solar_errors, fs};
6use foundry_compilers::{compilers::solc::SolcLanguage, solc::SOLC_EXTENSIONS};
7use foundry_config::{
8 Config, filter::expand_globs, find_project_root, fmt::FormatterConfig,
9 impl_figment_convert_basic,
10};
11use rayon::prelude::*;
12use similar::{ChangeTag, TextDiff};
13use solar::sema::Compiler;
14use std::{
15 collections::{HashMap, hash_map::Entry},
16 fmt::{self, Write},
17 io,
18 io::Write as _,
19 path::{Path, PathBuf},
20 sync::Arc,
21};
22use yansi::{Color, Paint, Style};
23
24#[derive(Clone, Debug, Parser)]
26pub struct FmtArgs {
27 #[arg(value_hint = ValueHint::FilePath, value_name = "PATH", num_args(1..))]
29 paths: Vec<PathBuf>,
30
31 #[arg(long, value_hint = ValueHint::DirPath, value_name = "PATH")]
36 root: Option<PathBuf>,
37
38 #[arg(long, conflicts_with = "root")]
40 nearest: bool,
41
42 #[arg(long)]
47 check: bool,
48
49 #[arg(long, short)]
51 raw: bool,
52
53 #[command(flatten)]
54 pub watch: WatchArgs,
55}
56
57impl_figment_convert_basic!(FmtArgs);
58
59impl FmtArgs {
60 pub fn run(self) -> Result<()> {
61 if self.nearest {
62 for var in ["FOUNDRY_CONFIG", "FOUNDRY_ROOT", "DAPP_ROOT"] {
63 if std::env::var_os(var).is_some() {
64 eyre::bail!("`--nearest` cannot be used when `{var}` is set");
65 }
66 }
67 }
68 let config = self.load_config()?;
69 let cwd = std::env::current_dir()?;
70
71 let ignored = if self.nearest {
74 Vec::new()
75 } else {
76 expand_globs(&config.root, config.fmt.ignore.iter())?
77 .iter()
78 .flat_map(fs::canonicalize_path)
79 .collect::<Vec<_>>()
80 };
81
82 let libs = expand_globs(&config.root, config.libs.iter().filter_map(|p| p.to_str()))?
84 .iter()
85 .flat_map(fs::canonicalize_path)
86 .collect::<Vec<_>>();
87
88 let is_under_dir = |file_path: &Path, dirs: &[PathBuf]| -> bool {
90 let check_against_dir = |dir: &PathBuf| {
91 file_path.starts_with(dir)
92 || cwd.join(file_path).starts_with(dir)
93 || fs::canonicalize_path(file_path).is_ok_and(|p| p.starts_with(dir))
94 };
95
96 dirs.iter().any(check_against_dir)
97 };
98
99 let root = fs::canonicalize_path(&config.root).unwrap_or_else(|_| config.root.clone());
102 let is_contained = |file_path: &Path, dir: &Path, allow_external_dir: bool| -> bool {
103 let Ok(resolved) = fs::canonicalize_path(file_path) else { return false };
104 if resolved.starts_with(&root) || (allow_external_dir && resolved.starts_with(dir)) {
105 return true;
106 }
107 let _ = sh_warn!(
108 "Skipping {}: it resolves outside of the project root.\n\
109 HINT: Pass the path explicitly to format it: `forge fmt <paths>`",
110 file_path.display()
111 );
112 false
113 };
114
115 let default_paths = self.paths.is_empty();
116 let paths = if default_paths {
117 let paths = config.project_paths::<SolcLanguage>();
118 [paths.sources, paths.tests, paths.scripts]
120 .into_iter()
121 .filter(|path| path.exists())
122 .collect()
123 } else {
124 self.paths
125 };
126 let mut input = match &paths[..] {
127 [one] if one == Path::new("-") => Input::Stdin,
128 paths => {
129 let mut inputs = Vec::with_capacity(paths.len());
130 for path in paths {
131 if !self.nearest
133 && !ignored.is_empty()
134 && ((path.is_absolute() && ignored.contains(path))
135 || ignored.contains(&cwd.join(path)))
136 {
137 continue;
138 }
139
140 if path.is_dir() {
141 let exclude_libs = default_paths || !is_under_dir(path, &libs);
143 let dir = fs::canonicalize_path(path)?;
144 inputs.extend(
145 foundry_compilers::utils::source_files_iter(path, SOLC_EXTENSIONS)
146 .filter(|p| {
147 !((!self.nearest
148 && (ignored.contains(p)
149 || ignored.contains(&cwd.join(p))
150 || is_under_dir(p, &ignored)))
151 || (exclude_libs && is_under_dir(p, &libs)))
152 })
153 .filter(|p| is_contained(p, &dir, !default_paths)),
154 );
155 } else if path.is_sol() {
156 if default_paths
157 && ((!self.nearest && is_under_dir(path, &ignored))
158 || is_under_dir(path, &libs))
159 {
160 continue;
161 }
162 if default_paths && !is_contained(path, &root, false) {
163 continue;
164 }
165 inputs.push(path.clone());
167 } else {
168 warn!("Cannot process path {}", path.display());
169 }
170 }
171 Input::Paths(inputs)
172 }
173 };
174
175 let nearest_fmt_configs = if self.nearest {
176 let Input::Paths(paths) = &mut input else {
177 eyre::bail!("`--nearest` cannot be used with stdin");
178 };
179 let mut root_configs: HashMap<PathBuf, (Arc<FormatterConfig>, Vec<PathBuf>)> =
180 HashMap::new();
181 let mut path_configs = HashMap::new();
182 let mut filtered_paths = Vec::with_capacity(paths.len());
183
184 for path in std::mem::take(paths) {
185 let path = fs::canonicalize_path(path)?;
186 let root = find_project_root(path.parent())?;
187 let (fmt_config, ignored) = match root_configs.entry(root) {
188 Entry::Occupied(entry) => entry.into_mut(),
189 Entry::Vacant(entry) => {
190 let nearest_config = Config::load_with_root(entry.key())?.sanitized();
191 if entry.key() != &config.root {
192 for warning in &nearest_config.warnings {
193 let _ = sh_warn!("{warning}");
194 }
195 }
196 let ignored =
197 expand_globs(&nearest_config.root, nearest_config.fmt.ignore.iter())?
198 .iter()
199 .flat_map(fs::canonicalize_path)
200 .collect();
201 entry.insert((Arc::new(nearest_config.fmt), ignored))
202 }
203 };
204 if ignored.iter().any(|ignored| path.starts_with(ignored)) {
207 continue;
208 }
209 path_configs.insert(path.clone(), fmt_config.clone());
210 filtered_paths.push(path);
211 }
212 *paths = filtered_paths;
213 Some(path_configs)
214 } else {
215 None
216 };
217
218 let mut compiler = Compiler::new(
219 solar::interface::Session::builder().with_buffer_emitter(Default::default()).build(),
220 );
221
222 compiler.enter_mut(|compiler| {
224 let mut pcx = compiler.parse();
225 pcx.set_resolve_imports(false);
226 match input {
227 Input::Paths(paths) if paths.is_empty() => {
228 sh_warn!(
229 "Nothing to format.\n\
230 HINT: If you are working outside of the project, \
231 try providing paths to your source files: `forge fmt <paths>`"
232 )?;
233 return Ok(());
234 }
235 Input::Paths(paths) => _ = pcx.par_load_files(paths),
236 Input::Stdin => _ = pcx.load_stdin(),
237 }
238 pcx.parse();
239 convert_solar_errors(compiler.dcx())?;
240
241 let gcx = compiler.gcx();
242 let fmt_config = Arc::new(config.fmt);
243 let diffs: Vec<String> = gcx
244 .sources
245 .raw
246 .par_iter()
247 .filter_map(|source_unit| {
248 let path = source_unit.file.name.as_real();
249 let original = source_unit.file.src.as_str();
250 let source_fmt_config =
251 if let Some(nearest_fmt_configs) = nearest_fmt_configs.as_ref() {
252 let Some(source_path) = path else {
253 return Some(Err(eyre::eyre!(
254 "could not resolve formatter config for stdin"
255 )));
256 };
257 let source_path = match fs::canonicalize_path(source_path) {
258 Ok(path) => path,
259 Err(err) => return Some(Err(err.into())),
260 };
261 let Some(fmt_config) = nearest_fmt_configs.get(&source_path) else {
262 return Some(Err(eyre::eyre!(
263 "could not resolve formatter config for {}",
264 source_path.display()
265 )));
266 };
267 fmt_config.clone()
268 } else {
269 fmt_config.clone()
270 };
271 let formatted = forge_fmt::format_ast(gcx, source_unit, source_fmt_config)?;
272 let from_stdin = path.is_none();
273
274 if from_stdin && self.raw {
277 return Some(Ok(formatted));
278 }
279
280 if original == formatted {
281 return None;
282 }
283
284 if self.check || from_stdin {
285 let summary = if self.raw {
286 formatted
287 } else {
288 let name = match path {
289 Some(path) => path
290 .strip_prefix(&config.root)
291 .unwrap_or(path)
292 .display()
293 .to_string(),
294 None => "stdin".to_string(),
295 };
296 format_diff_summary(&name, &TextDiff::from_lines(original, &formatted))
297 };
298 Some(Ok(summary))
299 } else if let Some(path) = path {
300 match fs::write(path, formatted) {
301 Ok(()) => {}
302 Err(e) => return Some(Err(e.into())),
303 }
304 let _ = sh_status!("Formatted {}", path.display());
305 None
306 } else {
307 unreachable!()
308 }
309 })
310 .collect::<Result<_>>()?;
311
312 if !diffs.is_empty() {
313 let mut stdout = io::stdout().lock();
315 for (i, diff) in diffs.iter().enumerate() {
316 if i > 0 {
317 let _ = stdout.write_all(b"\n");
318 }
319 let _ = stdout.write_all(diff.as_bytes());
320 }
321 if self.check {
322 std::process::exit(1);
323 }
324 }
325
326 convert_solar_errors(compiler.dcx())
327 })
328 }
329
330 pub const fn is_watch(&self) -> bool {
332 self.watch.watch.is_some()
333 }
334}
335
336#[derive(Debug)]
337enum Input {
338 Stdin,
339 Paths(Vec<PathBuf>),
340}
341
342struct Line(Option<usize>);
343
344impl fmt::Display for Line {
345 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
346 match self.0 {
347 None => f.write_str(" "),
348 Some(idx) => write!(f, "{:<4}", idx + 1),
349 }
350 }
351}
352
353fn format_diff_summary<'a>(name: &str, diff: &'a TextDiff<'a, 'a, str>) -> String {
354 let cap = 128;
355 let mut diff_summary = String::with_capacity(cap);
356
357 let _ = writeln!(diff_summary, "Diff in {name}:");
358 for (j, group) in diff.grouped_ops(3).into_iter().enumerate() {
359 if j > 0 {
360 let s =
361 "--------------------------------------------------------------------------------";
362 diff_summary.push_str(s);
363 }
364 for op in group {
365 for change in diff.iter_inline_changes(&op) {
366 let dimmed = Style::new().dim();
367 let (sign, s) = match change.tag() {
368 ChangeTag::Delete => ("-", Color::Red.foreground()),
369 ChangeTag::Insert => ("+", Color::Green.foreground()),
370 ChangeTag::Equal => (" ", dimmed),
371 };
372
373 let _ = write!(
374 diff_summary,
375 "{}{} |{}",
376 Line(change.old_index()).paint(dimmed),
377 Line(change.new_index()).paint(dimmed),
378 sign.paint(s.bold()),
379 );
380
381 for (emphasized, value) in change.iter_strings_lossy() {
382 let s = if emphasized { s.underline().bg(Color::Black) } else { s };
383 let _ = write!(diff_summary, "{}", value.paint(s));
384 }
385
386 if change.missing_newline() {
387 diff_summary.push('\n');
388 }
389 }
390 }
391 }
392
393 diff_summary
394}