forked from crate-ci/typos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
362 lines (322 loc) · 11.9 KB
/
main.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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
use std::io::{BufRead as _, BufReader, Write as _};
use std::path::PathBuf;
use clap::Parser;
mod args;
mod report;
use proc_exit::prelude::*;
fn main() {
human_panic::setup_panic!();
let result = run();
proc_exit::exit(result);
}
fn run() -> proc_exit::ExitResult {
// clap's `get_matches` uses Failure rather than Usage, so bypass it for `get_matches_safe`.
let args = match args::Args::try_parse() {
Ok(args) => args,
Err(e) if e.use_stderr() => {
let _ = e.print();
return proc_exit::sysexits::USAGE_ERR.ok();
}
Err(e) => {
let _ = e.print();
return proc_exit::Code::SUCCESS.ok();
}
};
args.color.write_global();
init_logging(args.verbose.log_level());
if let Some(output_path) = args.dump_config.as_ref() {
run_dump_config(&args, output_path)
} else if args.type_list {
run_type_list(&args)
} else {
run_checks(&args)
}
}
fn run_dump_config(args: &args::Args, output_path: &std::path::Path) -> proc_exit::ExitResult {
let global_cwd = std::env::current_dir().to_sysexits()?;
let path = &args.path[0];
let cwd = if path == std::path::Path::new("-") {
global_cwd
} else if path.is_file() {
let mut cwd = path
.canonicalize()
.with_code(proc_exit::sysexits::USAGE_ERR)?;
cwd.pop();
cwd
} else {
path.canonicalize()
.with_code(proc_exit::sysexits::USAGE_ERR)?
};
let cwd = cwd
.canonicalize()
.with_code(proc_exit::sysexits::USAGE_ERR)?;
let storage = typos_cli::policy::ConfigStorage::new();
let mut engine = typos_cli::policy::ConfigEngine::new(&storage);
engine.set_isolated(args.isolated);
let mut overrides = typos_cli::config::Config::default();
if let Some(path) = args.custom_config.as_ref() {
let custom = typos_cli::config::Config::from_file(path)
.with_code(proc_exit::sysexits::CONFIG_ERR)?;
if let Some(custom) = custom {
overrides.update(&custom);
}
}
overrides.update(&args.config.to_config());
engine.set_overrides(overrides);
let config = engine
.load_config(&cwd)
.with_code(proc_exit::sysexits::CONFIG_ERR)?;
let mut defaulted_config = typos_cli::config::Config::from_defaults();
defaulted_config.update(&config);
let output = toml::to_string_pretty(&defaulted_config).with_code(proc_exit::Code::FAILURE)?;
if output_path == std::path::Path::new("-") {
std::io::stdout()
.write_all(output.as_bytes())
.to_sysexits()?;
} else {
std::fs::write(output_path, &output).to_sysexits()?;
}
Ok(())
}
fn run_type_list(args: &args::Args) -> proc_exit::ExitResult {
let global_cwd = std::env::current_dir().to_sysexits()?;
let path = &args.path[0];
let cwd = if path == std::path::Path::new("-") {
global_cwd
} else if path.is_file() {
let mut cwd = path
.canonicalize()
.with_code(proc_exit::sysexits::USAGE_ERR)?;
cwd.pop();
cwd
} else {
path.canonicalize()
.with_code(proc_exit::sysexits::USAGE_ERR)?
};
let cwd = cwd
.canonicalize()
.with_code(proc_exit::sysexits::USAGE_ERR)?;
let storage = typos_cli::policy::ConfigStorage::new();
let mut engine = typos_cli::policy::ConfigEngine::new(&storage);
engine.set_isolated(args.isolated);
let mut overrides = typos_cli::config::Config::default();
if let Some(path) = args.custom_config.as_ref() {
let custom = typos_cli::config::Config::from_file(path)
.with_code(proc_exit::sysexits::CONFIG_ERR)?;
if let Some(custom) = custom {
overrides.update(&custom);
}
}
overrides.update(&args.config.to_config());
engine.set_overrides(overrides);
engine
.init_dir(&cwd)
.with_code(proc_exit::sysexits::CONFIG_ERR)?;
let definitions = engine.file_types(&cwd);
let stdout = std::io::stdout();
let mut handle = stdout.lock();
for (name, globs) in definitions {
writeln!(handle, "{}: {}", name, itertools::join(globs, ", ")).to_sysexits()?;
}
Ok(())
}
fn run_checks(args: &args::Args) -> proc_exit::ExitResult {
let global_cwd = std::env::current_dir()
.map_err(|err| {
let kind = err.kind();
std::io::Error::new(kind, "no current working directory".to_owned())
})
.to_sysexits()?;
let storage = typos_cli::policy::ConfigStorage::new();
let mut engine = typos_cli::policy::ConfigEngine::new(&storage);
engine.set_isolated(args.isolated);
let mut overrides = typos_cli::config::Config::default();
if let Some(path) = args.custom_config.as_ref() {
let custom = typos_cli::config::Config::from_file(path)
.with_code(proc_exit::sysexits::CONFIG_ERR)?;
if let Some(custom) = custom {
overrides.update(&custom);
}
}
overrides.update(&args.config.to_config());
engine.set_overrides(overrides);
let mut typos_found = false;
let mut errors_found = false;
let file_list = match args.file_list.as_deref() {
Some(dash) if dash == PathBuf::from("-") => Some(
std::io::stdin()
.lines()
.map(|res| res.map(PathBuf::from))
.collect::<Result<_, _>>()
.with_code(proc_exit::sysexits::IO_ERR)?,
),
Some(path) => Some(
BufReader::new(std::fs::File::open(path).with_code(proc_exit::sysexits::IO_ERR)?)
.lines()
.map(|res| res.map(PathBuf::from))
.collect::<Result<_, _>>()
.with_code(proc_exit::sysexits::IO_ERR)?,
),
None => None,
};
// Note: file_list and args.path are mutually exclusive, enforced by clap
'path: for path in file_list.as_ref().unwrap_or(&args.path) {
// Note paths are passed through stdin, `-` is treated like a normal path
let cwd = if path == std::path::Path::new("-") {
if args.file_list.is_some() {
return Err(proc_exit::sysexits::USAGE_ERR.with_message(
"Can't use `-` (stdin) while using `--file_list` provided paths",
));
};
global_cwd.clone()
} else if path.is_file() {
let mut cwd = path
.canonicalize()
.map_err(|err| {
let kind = err.kind();
std::io::Error::new(kind, format!("argument `{}` is not found", path.display()))
})
.with_code(proc_exit::sysexits::USAGE_ERR)?;
cwd.pop();
cwd
} else {
path.canonicalize()
.map_err(|err| {
let kind = err.kind();
std::io::Error::new(kind, format!("argument `{}` is not found", path.display()))
})
.with_code(proc_exit::sysexits::USAGE_ERR)?
};
engine
.init_dir(&cwd)
.with_code(proc_exit::sysexits::CONFIG_ERR)?;
let walk_policy = engine.walk(&cwd);
let threads = if path.is_file() || args.sort {
1
} else {
args.threads
};
let single_threaded = threads == 1;
let mut walk = ignore::WalkBuilder::new(path);
walk.threads(threads)
.skip_stdout(true)
.hidden(walk_policy.ignore_hidden())
.ignore(walk_policy.ignore_dot())
.git_global(walk_policy.ignore_global())
.git_ignore(walk_policy.ignore_vcs())
.git_exclude(walk_policy.ignore_vcs())
.parents(walk_policy.ignore_parent());
if args.sort {
walk.sort_by_file_name(|a, b| a.cmp(b));
}
if !walk_policy.extend_exclude.is_empty() {
let mut overrides = ignore::overrides::OverrideBuilder::new(".");
for pattern in walk_policy.extend_exclude.iter() {
overrides
.add(&format!("!{}", pattern))
.with_code(proc_exit::sysexits::CONFIG_ERR)?;
}
let overrides = overrides
.build()
.with_code(proc_exit::sysexits::CONFIG_ERR)?;
if args.force_exclude {
let mut ancestors = path.ancestors().collect::<Vec<_>>();
ancestors.reverse();
for path in ancestors {
match overrides.matched(path, path.is_dir()) {
ignore::Match::None => {}
ignore::Match::Ignore(_) => continue 'path,
ignore::Match::Whitelist(_) => break,
}
}
}
walk.overrides(overrides);
}
// HACK: Diff doesn't handle mixing content
let output_reporter = if args.diff {
Box::new(crate::report::PrintSilent)
} else {
args.format.reporter()
};
let status_reporter = report::MessageStatus::new(output_reporter.as_ref());
let reporter: &dyn typos_cli::report::Report = &status_reporter;
let selected_checks: &dyn typos_cli::file::FileChecker = if args.files {
&typos_cli::file::FoundFiles
} else if args.file_types {
&typos_cli::file::FileTypes
} else if args.identifiers {
&typos_cli::file::Identifiers
} else if args.words {
&typos_cli::file::Words
} else if args.write_changes {
&typos_cli::file::FixTypos
} else if args.diff {
&typos_cli::file::DiffTypos
} else {
&typos_cli::file::Typos
};
if single_threaded {
typos_cli::file::walk_path(walk.build(), selected_checks, &engine, reporter)
} else {
typos_cli::file::walk_path_parallel(
walk.build_parallel(),
selected_checks,
&engine,
reporter,
)
}
.map_err(|e| {
e.io_error()
.map(|i| {
let kind = i.kind();
proc_exit::sysexits::io_to_sysexists(kind)
.or_else(|| proc_exit::bash::io_to_signal(kind))
.unwrap_or(proc_exit::sysexits::IO_ERR)
})
.unwrap_or_default()
.with_message(e)
})?;
if status_reporter.typos_found() {
typos_found = true;
}
if status_reporter.errors_found() {
errors_found = true;
}
}
if errors_found {
proc_exit::Code::FAILURE.ok()
} else if typos_found {
// Can;'t use `Failure` since its so prevalent, it could be easy to get a
// `Failure` from something else and get it mixed up with typos.
//
// Can't use DataErr or anything else an std::io::ErrorKind might map to.
proc_exit::Code::new(2).ok()
} else {
proc_exit::Code::SUCCESS.ok()
}
}
fn init_logging(level: Option<log::Level>) {
if let Some(level) = level {
let mut builder = env_logger::Builder::new();
let choice = anstream::AutoStream::choice(&std::io::stderr());
builder.write_style(if matches!(choice, anstream::ColorChoice::Never) {
env_logger::WriteStyle::Never
} else {
env_logger::WriteStyle::Always
});
builder.filter(None, level.to_level_filter());
if level == log::LevelFilter::Trace {
builder.format_timestamp_secs();
} else {
builder.format(|f, record| {
writeln!(
f,
"[{}] {}",
record.level().to_string().to_lowercase(),
record.args()
)
});
}
builder.init();
}
}