-
Notifications
You must be signed in to change notification settings - Fork 64
/
main.rs
549 lines (501 loc) · 19.3 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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
use anyhow::{bail, Context, Result};
use clap::StructOpt;
use console::style;
use ignore::{gitignore::Gitignore, overrides::OverrideBuilder, WalkBuilder};
use log::{LevelFilter, *};
use serde_json::json;
use std::fs;
use std::io::{stderr, stdin, stdout, Read, Write};
use std::path::Path;
use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::Arc;
use std::time::Instant;
use thiserror::Error;
use threadpool::ThreadPool;
use stylua_lib::{format_code, Config, OutputVerification, Range};
use crate::config::find_ignore_file_path;
mod config;
mod opt;
mod output_diff;
static EXIT_CODE: AtomicI32 = AtomicI32::new(0);
enum FormatResult {
/// Operation was a success, the output was either written to a file or stdout. If diffing, there was no diff to create.
Complete,
/// Formatting was a success, but the formatted contents are buffered, ready to be sent to stdout.
/// This is used when formatting from stdin - we want to buffer the output so it can be sent in a locked channel.
SuccessBufferedOutput(Vec<u8>),
/// There is a diff output. This stores the diff created
Diff(Vec<u8>),
}
/// Wraps an error to include information about the file it resonated from
#[derive(Error, Debug)]
#[error("{:#}", .error)]
struct ErrorFileWrapper {
file: String,
error: anyhow::Error,
}
fn convert_parse_error_to_json(file: &str, err: &full_moon::Error) -> Option<serde_json::Value> {
Some(match err {
full_moon::Error::AstError(full_moon::ast::AstError::UnexpectedToken {
token,
additional,
}) => json!({
"type": "parse_error",
"message": format!("unexpected token `{}`{}", token, additional.as_ref().map(|x| format!(": {}", x)).unwrap_or_default()),
"filename": file,
"location": {
"start": token.start_position().bytes(),
"start_line": token.start_position().line(),
"start_column": token.start_position().character(),
"end": token.end_position().bytes(),
"end_line": token.end_position().line(),
"end_column": token.end_position().character(),
},
}),
full_moon::Error::TokenizerError(error) => json!({
"type": "parse_error",
"message": match error.error() {
full_moon::tokenizer::TokenizerErrorType::UnclosedComment => {
"unclosed comment".to_string()
}
full_moon::tokenizer::TokenizerErrorType::UnclosedString => {
"unclosed string".to_string()
}
full_moon::tokenizer::TokenizerErrorType::UnexpectedShebang => {
"unexpected shebang".to_string()
}
full_moon::tokenizer::TokenizerErrorType::UnexpectedToken(
character,
) => {
format!("unexpected character {}", character)
}
full_moon::tokenizer::TokenizerErrorType::InvalidSymbol(symbol) => {
format!("invalid symbol {}", symbol)
}
},
"filename": file,
"location": {
"start": error.position().bytes(),
"start_line": error.position().line(),
"start_column": error.position().character(),
"end": error.position().bytes(),
"end_line": error.position().line(),
"end_column": error.position().character(),
},
}),
_ => {
error!("{:#}", err);
return None;
}
})
}
fn create_diff(
opt: &opt::Opt,
original: &str,
expected: &str,
file_name: &str,
) -> Result<Option<Vec<u8>>> {
match opt.output_format {
opt::OutputFormat::Standard => output_diff::output_diff(
original,
expected,
3,
&format!("Diff in {}:", file_name),
opt.color,
),
opt::OutputFormat::Unified => output_diff::output_diff_unified(original, expected),
opt::OutputFormat::Json => {
output_diff::output_diff_json(original, expected)
.map(|mismatches| {
serde_json::to_vec(&json!({
"file": file_name,
"mismatches": mismatches
}))
// Add newline to end
.map(|mut vec| {
vec.push(b'\n');
vec
})
// Covert to anyhow::Error
.map_err(|err| err.into())
})
.transpose()
}
}
}
fn format_file(
path: &Path,
config: Config,
range: Option<Range>,
opt: &opt::Opt,
verify_output: OutputVerification,
) -> Result<FormatResult> {
let contents =
fs::read_to_string(path).with_context(|| format!("failed to read {}", path.display()))?;
let before_formatting = Instant::now();
let formatted_contents = format_code(&contents, config, range, verify_output)
.with_context(|| format!("could not format file {}", path.display()))?;
let after_formatting = Instant::now();
debug!(
"formatted {} in {:?}",
path.display(),
after_formatting.duration_since(before_formatting)
);
if opt.check {
let diff = create_diff(
opt,
&contents,
&formatted_contents,
path.display().to_string().as_str(),
)
.context("failed to create diff")?;
match diff {
Some(diff) => Ok(FormatResult::Diff(diff)),
None => Ok(FormatResult::Complete),
}
} else {
fs::write(path, formatted_contents)
.with_context(|| format!("could not write to {}", path.display()))?;
Ok(FormatResult::Complete)
}
}
/// Takes in a string and returns the formatted output in a buffer
/// Used when input has been provided to stdin
fn format_string(
input: String,
config: Config,
range: Option<Range>,
opt: &opt::Opt,
verify_output: OutputVerification,
should_skip: bool,
) -> Result<FormatResult> {
let formatted_contents = if should_skip {
input.clone()
} else {
format_code(&input, config, range, verify_output).context("failed to format from stdin")?
};
if opt.check {
let diff = create_diff(opt, &input, &formatted_contents, "stdin")
.context("failed to create diff")?;
match diff {
Some(diff) => Ok(FormatResult::Diff(diff)),
None => Ok(FormatResult::Complete),
}
} else {
Ok(FormatResult::SuccessBufferedOutput(
formatted_contents.into_bytes(),
))
}
}
fn get_ignore(
directory: &Path,
search_parent_directories: bool,
) -> Result<Gitignore, ignore::Error> {
let file_path = find_ignore_file_path(directory.to_path_buf(), search_parent_directories);
if let Some(file_path) = file_path {
let (ignore, err) = Gitignore::new(file_path);
if let Some(err) = err {
Err(err)
} else {
Ok(ignore)
}
} else {
Ok(Gitignore::empty())
}
}
fn format(opt: opt::Opt) -> Result<i32> {
if opt.files.is_empty() {
bail!("no files provided");
}
// Check for incompatible options
if !opt.check && matches!(opt.output_format, opt::OutputFormat::Unified) {
bail!("--output-format=unified can only be used when --check is enabled");
}
// Load the configuration
let config = config::load_config(&opt)?;
// Handle any configuration overrides provided by options
let config = config::load_overrides(config, &opt);
debug!("config: {:#?}", config);
// Create range if provided
let range = if opt.range_start.is_some() || opt.range_end.is_some() {
Some(Range::from_values(opt.range_start, opt.range_end))
} else {
None
};
// Determine if we need to verify the output
let verify_output = if opt.verify {
OutputVerification::Full
} else {
OutputVerification::None
};
let cwd = std::env::current_dir()?;
// Build WalkBuilder with the files given, using any overrides set
let mut walker_builder = WalkBuilder::new(&opt.files[0]);
for file_path in &opt.files[1..] {
walker_builder.add(file_path);
}
walker_builder
.standard_filters(false)
.hidden(true)
.parents(true)
.add_custom_ignore_filename(".styluaignore");
// Look for an ignore file in the current working directory
let ignore_path = cwd.join(".styluaignore");
if ignore_path.is_file() {
walker_builder.add_ignore(ignore_path);
}
let use_default_glob = match opt.glob {
Some(ref globs) => {
// Build overriders with any patterns given
let mut overrides = OverrideBuilder::new(cwd);
for pattern in globs {
overrides.add(pattern)?;
}
let overrides = overrides.build()?;
walker_builder.overrides(overrides);
// We shouldn't use the default glob anymore
false
}
None => true,
};
debug!("creating a pool with {} threads", opt.num_threads);
let pool = ThreadPool::new(std::cmp::max(opt.num_threads, 2)); // Use a minimum of 2 threads, because we need at least one output reader as well as a formatter
let (tx, rx) = crossbeam_channel::unbounded::<Result<_>>();
let output_format = opt.output_format;
let opt = Arc::new(opt);
// Create a thread to handle the formatting output
pool.execute(move || {
for output in rx {
match output {
Ok(result) => match result {
FormatResult::Complete => (),
FormatResult::SuccessBufferedOutput(output) => {
let stdout = stdout();
let mut handle = stdout.lock();
match handle.write_all(&output) {
Ok(_) => (),
Err(err) => {
error!("could not output to stdout: {:#}", err)
}
};
}
FormatResult::Diff(diff) => {
if EXIT_CODE.load(Ordering::SeqCst) != 2 {
EXIT_CODE.store(1, Ordering::SeqCst);
}
let stdout = stdout();
let mut handle = stdout.lock();
match handle.write_all(&diff) {
Ok(_) => (),
Err(err) => error!("{:#}", err),
}
}
},
Err(err) if matches!(output_format, opt::OutputFormat::Json) => {
match err.downcast_ref::<ErrorFileWrapper>() {
Some(ErrorFileWrapper { file, error }) => {
match error.downcast_ref::<stylua_lib::Error>() {
Some(stylua_lib::Error::ParseError(err)) => {
if let Some(structured_err) =
convert_parse_error_to_json(file, err)
{
// Force write to stderr directly
// TODO: can we do this through error! instead?
let stderr = stderr();
let mut handle = stderr.lock();
match handle
.write_all(structured_err.to_string().as_bytes())
{
Ok(_) => (),
Err(err) => {
error!("could not output to stdout: {:#}", err)
}
};
}
}
_ => error!("{:#}", err),
}
}
_ => error!("{:#}", err),
}
}
Err(err) => error!("{:#}", err),
}
}
});
let walker = walker_builder.build();
for result in walker {
match result {
Ok(entry) => {
if entry.is_stdin() {
let tx = tx.clone();
let opt = opt.clone();
let should_skip_format = match &opt.stdin_filepath {
Some(filepath) => {
let ignore = get_ignore(
filepath.parent().expect("cannot get parent directory"),
opt.search_parent_directories,
)
.context("failed to parse ignore file")?;
matches!(ignore.matched(&filepath, false), ignore::Match::Ignore(_))
}
None => false,
};
pool.execute(move || {
let mut buf = String::new();
match stdin().read_to_string(&mut buf) {
Ok(_) => tx.send(format_string(
buf,
config,
range,
&opt,
verify_output,
should_skip_format,
)),
Err(error) => tx.send(
Err(ErrorFileWrapper {
file: "stdin".to_string(),
error: error.into(),
})
.context("could not format from stdin"),
),
}
.unwrap();
});
} else {
let path = entry.path().to_owned(); // TODO: stop to_owned?
let opt = opt.clone();
if path.is_file() {
// If the user didn't provide a glob pattern, we should match against our default one
// We should ignore the glob check if the path provided was explicitly given to the CLI
if use_default_glob && !opt.files.iter().any(|p| path == *p) {
lazy_static::lazy_static! {
static ref DEFAULT_GLOB: globset::GlobSet = {
let mut builder = globset::GlobSetBuilder::new();
builder.add(globset::Glob::new("**/*.lua").expect("cannot create default glob"));
#[cfg(feature = "luau")]
builder.add(globset::Glob::new("**/*.luau").expect("cannot create default luau glob"));
builder.build().expect("cannot build default globset")
};
}
if !DEFAULT_GLOB.is_match(&path) {
continue;
}
}
let tx = tx.clone();
pool.execute(move || {
tx.send(
format_file(&path, config, range, &opt, verify_output).map_err(
|error| {
ErrorFileWrapper {
file: path.display().to_string(),
error,
}
.into()
},
),
)
.unwrap()
});
}
}
}
Err(error) => match error {
ignore::Error::WithPath { path, err } => match *err {
ignore::Error::Io(error) => match error.kind() {
std::io::ErrorKind::NotFound => {
error!("no file or directory found matching '{:#}'", path.display())
}
_ => error!("{:#}", error),
},
_ => error!("{:#}", err),
},
_ => error!("{:#}", error),
},
}
}
drop(tx);
pool.join();
// Exit with non-zero code if we have a panic
let output_code = if pool.panic_count() > 0 {
2
} else {
EXIT_CODE.load(Ordering::SeqCst)
};
Ok(output_code)
}
fn main() {
let opt = opt::Opt::parse();
let output_format = opt.output_format;
let should_use_color = opt.color.should_use_color_stderr();
let level_filter = if opt.verbose {
LevelFilter::Debug
} else {
LevelFilter::Warn
};
env_logger::Builder::from_env("STYLUA_LOG")
.filter(None, level_filter)
.format(move |buf, record| {
// Side effect: set exit code
if let Level::Error = record.level() {
EXIT_CODE.store(2, Ordering::SeqCst);
}
let tag = match record.level() {
Level::Error => style("error").red(),
Level::Warn => style("warn").yellow(),
Level::Info => style("info").green(),
Level::Debug => style("debug").cyan(),
Level::Trace => style("trace").magenta(),
}
.bold()
.force_styling(should_use_color);
if let opt::OutputFormat::Json = output_format {
writeln!(
buf,
"{}",
json!({
"type": record.level().to_string().to_lowercase(),
"message": record.args().to_string(),
})
)
} else {
writeln!(
buf,
"{}{} {}",
tag,
style(":").bold().force_styling(should_use_color),
record.args()
)
}
})
.init();
let exit_code = match format(opt) {
Ok(code) => code,
Err(err) => {
error!("{:#}", err);
2
}
};
std::process::exit(exit_code);
}
#[cfg(test)]
mod tests {
use assert_cmd::Command;
#[test]
fn test_no_files_provided() {
let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
cmd.assert()
.failure()
.code(2)
.stderr("error: no files provided\n");
}
#[test]
fn test_format_stdin() {
let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
cmd.arg("-")
.write_stdin("local x = 1")
.assert()
.success()
.stdout("local x = 1\n");
}
}