forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
235 lines (212 loc) · 6.61 KB
/
Copy pathmain.rs
File metadata and controls
235 lines (212 loc) · 6.61 KB
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
#![allow(clippy::print_stderr, clippy::print_stdout)]
mod check;
mod test;
#[cfg(not(target_arch = "wasm32"))]
mod tree;
use std::fs;
use camino::Utf8PathBuf;
use check::check;
use clap::{Parser, Subcommand};
use colored::Colorize;
use fmt as fe_fmt;
use similar::{ChangeTag, TextDiff};
use walkdir::WalkDir;
#[derive(Debug, Clone, Parser)]
#[command(version, about, long_about = None)]
pub struct Options {
#[command(subcommand)]
pub command: Command,
}
#[derive(Debug, Clone, Subcommand)]
pub enum Command {
Build,
Check {
#[arg(default_value_t = default_project_path())]
path: Utf8PathBuf,
#[arg(short, long)]
core: Option<Utf8PathBuf>,
#[arg(long)]
dump_mir: bool,
#[arg(long)]
emit_yul_min: bool,
},
#[cfg(not(target_arch = "wasm32"))]
Tree {
path: Utf8PathBuf,
},
/// Format Fe source code.
Fmt {
/// Path to a Fe source file or directory. If omitted, formats all .fe files in the current project.
path: Option<Utf8PathBuf>,
/// Check if files are formatted, but do not write changes.
#[arg(long)]
check: bool,
},
/// Run Fe tests in a file or directory.
Test {
/// Path to a .fe file or directory containing an ingot with tests.
#[arg(default_value_t = default_project_path())]
path: Utf8PathBuf,
/// Optional filter pattern for test names.
#[arg(short, long)]
filter: Option<String>,
/// Show event logs from test execution.
#[arg(long)]
show_logs: bool,
},
New,
}
fn default_project_path() -> Utf8PathBuf {
driver::files::find_project_root().unwrap_or(Utf8PathBuf::from("."))
}
fn main() {
let opts = Options::parse();
run(&opts);
}
pub fn run(opts: &Options) {
match &opts.command {
Command::Build => eprintln!("`fe build` doesn't work at the moment"),
Command::Check {
path,
core: _,
dump_mir,
emit_yul_min,
} => {
//: TODO readd custom core
check(path, *dump_mir, *emit_yul_min);
}
#[cfg(not(target_arch = "wasm32"))]
Command::Tree { path } => {
tree::print_tree(path);
}
Command::Fmt { path, check } => {
run_fmt(path.as_ref(), *check);
}
Command::Test {
path,
filter,
show_logs,
} => {
test::run_tests(path, filter.as_deref(), *show_logs);
}
Command::New => eprintln!("`fe new` doesn't work at the moment"),
}
}
fn run_fmt(path: Option<&Utf8PathBuf>, check: bool) {
let config = fe_fmt::Config::default();
// Collect files to format
let files: Vec<Utf8PathBuf> = match path {
Some(p) if p.is_file() => vec![p.clone()],
Some(p) if p.is_dir() => collect_fe_files(p),
Some(p) => {
eprintln!("Path does not exist: {}", p);
std::process::exit(1);
}
None => {
// Find project root and format all .fe files in src/
match driver::files::find_project_root() {
Some(root) => collect_fe_files(&root.join("src")),
None => {
eprintln!(
"No fe.toml found. Run from a Fe project directory or specify a path."
);
std::process::exit(1);
}
}
}
};
if files.is_empty() {
eprintln!("No .fe files found");
std::process::exit(1);
}
let mut unformatted_files = Vec::new();
let mut error_count = 0;
for file in &files {
match format_single_file(file, &config, check) {
FormatResult::Unchanged => {}
FormatResult::Formatted {
original,
formatted,
} => {
if check {
print_diff(file, &original, &formatted);
unformatted_files.push(file.clone());
}
}
FormatResult::ParseError(errs) => {
eprintln!("Skipping {} (parse errors):", file);
for err in errs {
eprintln!(" {}", err.msg());
}
}
FormatResult::IoError(err) => {
eprintln!("Error processing {}: {}", file, err);
error_count += 1;
}
}
}
if check && !unformatted_files.is_empty() {
std::process::exit(1);
}
if error_count > 0 {
std::process::exit(1);
}
}
fn print_diff(path: &Utf8PathBuf, original: &str, formatted: &str) {
let diff = TextDiff::from_lines(original, formatted);
println!("{}", format!("Diff {}:", path).bold());
for hunk in diff.unified_diff().context_radius(3).iter_hunks() {
// Print hunk header
println!("{}", format!("{}", hunk.header()).cyan());
for change in hunk.iter_changes() {
match change.tag() {
ChangeTag::Delete => print!("{}", format!("-{}", change).red()),
ChangeTag::Insert => print!("{}", format!("+{}", change).green()),
ChangeTag::Equal => print!(" {}", change),
};
}
}
println!();
}
fn collect_fe_files(dir: &Utf8PathBuf) -> Vec<Utf8PathBuf> {
if !dir.exists() {
return Vec::new();
}
WalkDir::new(dir)
.into_iter()
.filter_map(|e| e.ok())
.filter(|e| e.file_type().is_file())
.filter(|e| e.path().extension().is_some_and(|ext| ext == "fe"))
.filter_map(|e| Utf8PathBuf::from_path_buf(e.into_path()).ok())
.collect()
}
enum FormatResult {
Unchanged,
Formatted { original: String, formatted: String },
ParseError(Vec<fe_fmt::ParseError>),
IoError(std::io::Error),
}
fn format_single_file(path: &Utf8PathBuf, config: &fe_fmt::Config, check: bool) -> FormatResult {
let original = match fs::read_to_string(path.as_std_path()) {
Ok(s) => s,
Err(e) => return FormatResult::IoError(e),
};
let formatted = match fe_fmt::format_str(&original, config) {
Ok(f) => f,
Err(fe_fmt::FormatError::ParseErrors(errs)) => return FormatResult::ParseError(errs),
Err(fe_fmt::FormatError::Io(e)) => return FormatResult::IoError(e),
};
if formatted == original {
return FormatResult::Unchanged;
}
if !check {
if let Err(e) = fs::write(path.as_std_path(), &formatted) {
return FormatResult::IoError(e);
}
println!("Formatted {}", path);
}
FormatResult::Formatted {
original,
formatted,
}
}