-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathfmt.rs
251 lines (221 loc) · 8.59 KB
/
fmt.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
use clap::{Parser, ValueHint};
use eyre::{Context, Result};
use forge_fmt::{format_to, parse};
use foundry_cli::utils::{FoundryPathExt, LoadConfig};
use foundry_common::{fs, term::cli_warn};
use foundry_compilers::{compilers::solc::SolcLanguage, solc::SOLC_EXTENSIONS};
use foundry_config::{filter::expand_globs, impl_figment_convert_basic};
use rayon::prelude::*;
use similar::{ChangeTag, TextDiff};
use std::{
fmt::{self, Write},
io,
io::{Read, Write as _},
path::{Path, PathBuf},
};
use yansi::{Color, Paint, Style};
/// CLI arguments for `forge fmt`.
#[derive(Clone, Debug, Parser)]
pub struct FmtArgs {
/// Path to the file, directory or '-' to read from stdin.
#[arg(value_hint = ValueHint::FilePath, value_name = "PATH", num_args(1..))]
paths: Vec<PathBuf>,
/// The project's root path.
///
/// By default root of the Git repository, if in one,
/// or the current working directory.
#[arg(long, value_hint = ValueHint::DirPath, value_name = "PATH")]
root: Option<PathBuf>,
/// Run in 'check' mode.
///
/// Exits with 0 if input is formatted correctly.
/// Exits with 1 if formatting is required.
#[arg(long)]
check: bool,
/// In 'check' and stdin modes, outputs raw formatted code instead of the diff.
#[arg(long, short)]
raw: bool,
}
impl_figment_convert_basic!(FmtArgs);
impl FmtArgs {
pub fn run(self) -> Result<()> {
let config = self.try_load_config_emit_warnings()?;
// Expand ignore globs and canonicalize from the get go
let ignored = expand_globs(&config.root.0, config.fmt.ignore.iter())?
.iter()
.flat_map(foundry_common::fs::canonicalize_path)
.collect::<Vec<_>>();
let cwd = std::env::current_dir()?;
let input = match &self.paths[..] {
[] => {
// Retrieve the project paths, and filter out the ignored ones.
let project_paths: Vec<PathBuf> = config
.project_paths::<SolcLanguage>()
.input_files_iter()
.filter(|p| !(ignored.contains(p) || ignored.contains(&cwd.join(p))))
.collect();
Input::Paths(project_paths)
}
[one] if one == Path::new("-") => {
let mut s = String::new();
io::stdin().read_to_string(&mut s).expect("Failed to read from stdin");
Input::Stdin(s)
}
paths => {
let mut inputs = Vec::with_capacity(paths.len());
for path in paths {
if !ignored.is_empty() &&
((path.is_absolute() && ignored.contains(path)) ||
ignored.contains(&cwd.join(path)))
{
continue
}
if path.is_dir() {
inputs.extend(foundry_compilers::utils::source_files_iter(
path,
SOLC_EXTENSIONS,
));
} else if path.is_sol() {
inputs.push(path.to_path_buf());
} else {
warn!("Cannot process path {}", path.display());
}
}
Input::Paths(inputs)
}
};
let format = |source: String, path: Option<&Path>| -> Result<_> {
let name = match path {
Some(path) => {
path.strip_prefix(&config.root.0).unwrap_or(path).display().to_string()
}
None => "stdin".to_string(),
};
let parsed = parse(&source).wrap_err_with(|| {
format!("Failed to parse Solidity code for {name}. Leaving source unchanged.")
})?;
if !parsed.invalid_inline_config_items.is_empty() {
for (loc, warning) in &parsed.invalid_inline_config_items {
let mut lines = source[..loc.start().min(source.len())].split('\n');
let col = lines.next_back().unwrap().len() + 1;
let row = lines.count() + 1;
cli_warn!("[{}:{}:{}] {}", name, row, col, warning);
}
}
let mut output = String::new();
format_to(&mut output, parsed, config.fmt.clone()).unwrap();
solang_parser::parse(&output, 0).map_err(|diags| {
eyre::eyre!(
"Failed to construct valid Solidity code for {name}. Leaving source unchanged.\n\
Debug info: {diags:?}"
)
})?;
let diff = TextDiff::from_lines(&source, &output);
let new_format = diff.ratio() < 1.0;
if self.check || path.is_none() {
if self.raw {
print!("{output}");
}
// If new format then compute diff summary.
if new_format {
return Ok(Some(format_diff_summary(&name, &diff)))
}
} else if let Some(path) = path {
// If new format then write it on disk.
if new_format {
fs::write(path, output)?;
}
}
Ok(None)
};
let diffs = match input {
Input::Stdin(source) => format(source, None).map(|diff| vec![diff]),
Input::Paths(paths) => {
if paths.is_empty() {
cli_warn!(
"Nothing to format.\n\
HINT: If you are working outside of the project, \
try providing paths to your source files: `forge fmt <paths>`"
);
return Ok(())
}
paths
.par_iter()
.map(|path| {
let source = fs::read_to_string(path)?;
format(source, Some(path))
})
.collect()
}
}?;
let mut diffs = diffs.iter().flatten();
if let Some(first) = diffs.next() {
// This branch is only reachable with stdin or --check
if !self.raw {
let mut stdout = io::stdout().lock();
let first = std::iter::once(first);
for (i, diff) in first.chain(diffs).enumerate() {
if i > 0 {
let _ = stdout.write_all(b"\n");
}
let _ = stdout.write_all(diff.as_bytes());
}
}
if self.check {
std::process::exit(1);
}
}
Ok(())
}
}
struct Line(Option<usize>);
#[derive(Debug)]
enum Input {
Stdin(String),
Paths(Vec<PathBuf>),
}
impl fmt::Display for Line {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
None => f.write_str(" "),
Some(idx) => write!(f, "{:<4}", idx + 1),
}
}
}
fn format_diff_summary<'a>(name: &str, diff: &'a TextDiff<'a, 'a, '_, str>) -> String {
let cap = 128;
let mut diff_summary = String::with_capacity(cap);
let _ = writeln!(diff_summary, "Diff in {name}:");
for (j, group) in diff.grouped_ops(3).into_iter().enumerate() {
if j > 0 {
let s =
"--------------------------------------------------------------------------------";
diff_summary.push_str(s);
}
for op in group {
for change in diff.iter_inline_changes(&op) {
let dimmed = Style::new().dim();
let (sign, s) = match change.tag() {
ChangeTag::Delete => ("-", Color::Red.foreground()),
ChangeTag::Insert => ("+", Color::Green.foreground()),
ChangeTag::Equal => (" ", dimmed),
};
let _ = write!(
diff_summary,
"{}{} |{}",
Line(change.old_index()).paint(dimmed),
Line(change.new_index()).paint(dimmed),
sign.paint(s.bold()),
);
for (emphasized, value) in change.iter_strings_lossy() {
let s = if emphasized { s.underline().bg(Color::Black) } else { s };
let _ = write!(diff_summary, "{}", value.paint(s));
}
if change.missing_newline() {
diff_summary.push('\n');
}
}
}
}
diff_summary
}