stylua 2.4.1

A code formatter for Lua
Documentation
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
#![allow(unused_assignments)] // clippy false positive bug - https://github.com/rust-lang/rust/issues/147648. Remove once fixed
use anyhow::{bail, Context, Result};
use clap::StructOpt;
use console::style;
use ignore::{overrides::OverrideBuilder, WalkBuilder};
use log::{LevelFilter, *};
use serde_json::json;
use std::collections::HashSet;
use std::fs;
use std::io::{stderr, stdin, stdout, Read, Write};
use std::path::Path;
use std::sync::atomic::{AtomicI32, AtomicU32, Ordering};
use std::sync::Arc;
use std::time::Instant;
use thiserror::Error;
use threadpool::ThreadPool;

use stylua_lib::{format_code, Config, OutputVerification, Range};

mod config;
#[cfg(feature = "lsp")]
mod lsp;
mod opt;
mod output_diff;
mod stylua_ignore;

use stylua_ignore::{is_explicitly_provided, path_is_stylua_ignored, should_respect_ignores};

static EXIT_CODE: AtomicI32 = AtomicI32::new(0);
static UNFORMATTED_FILE_COUNT: AtomicU32 = AtomicU32::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, errs: Vec<full_moon::Error>) -> serde_json::Value {
    errs.iter()
        .map(|err| {
            let message = match err {
                full_moon::Error::AstError(ast_error) => format!(
                    "unexpected token `{}`: {}",
                    ast_error.token(),
                    ast_error.error_message()
                ),
                full_moon::Error::TokenizerError(error) => 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::InvalidNumber => {
                        "invalid number".to_string()
                    }
                    full_moon::tokenizer::TokenizerErrorType::UnexpectedToken(character) => {
                        format!("unexpected character {character}")
                    }
                    full_moon::tokenizer::TokenizerErrorType::InvalidSymbol(symbol) => {
                        format!("invalid symbol {symbol}")
                    }
                },
            };
            let (start_position, end_position) = err.range();
            json!({
                "type": "parse_error",
                "message": message,
                "filename": file,
                "location": {
                    "start": start_position.bytes(),
                    "start_line": start_position.line(),
                    "start_column": start_position.character(),
                    "end": end_position.bytes(),
                    "end_line": end_position.line(),
                    "end_column": end_position.character(),
                },
            })
        })
        .collect()
}

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()
        }
        opt::OutputFormat::Summary => {
            if original == expected {
                Ok(None)
            } else {
                Ok(Some(format!("{file_name}\n").into_bytes()))
            }
        }
    }
}

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 {
        if formatted_contents != contents {
            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 format(opt: opt::Opt) -> Result<i32> {
    debug!("resolved options: {:#?}", opt);

    if opt.lsp {
        #[cfg(feature = "lsp")]
        {
            lsp::run(opt)?;
            return Ok(0);
        }
        #[cfg(not(feature = "lsp"))]
        {
            bail!("attempted to run stylua in LSP mode, but this binary was not built with 'lsp' feature enabled")
        }
    }

    if opt.files.is_empty() {
        bail!("no files provided");
    }

    // Check for incompatible options
    if !opt.check
        && matches!(
            opt.output_format,
            opt::OutputFormat::Unified | opt::OutputFormat::Summary
        )
    {
        bail!("--output-format=unified and --output-format=summary can only be used when --check is enabled");
    }

    // Load the configuration
    let opt_for_config_resolver = opt.clone();
    let mut config_resolver = config::ConfigResolver::new(&opt_for_config_resolver)?;

    // 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(true)
        .hidden(!opt.allow_hidden)
        .parents(true)
        .git_exclude(!opt.no_ignore_vcs)
        .git_global(!opt.no_ignore_vcs)
        .git_ignore(!opt.no_ignore_vcs)
        .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);

    // Output a header if in summary mode
    if matches!(opt.output_format, opt::OutputFormat::Summary) {
        println!(
            "{} Checking formatting...",
            style("!")
                .cyan()
                .bold()
                .force_styling(opt.color.should_use_color())
        );
    }

    // 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);
                        }

                        UNFORMATTED_FILE_COUNT.fetch_add(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)) => {
                                    let structured_err =
                                        convert_parse_error_to_json(file, err.to_vec());
                                    // 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();
    let mut seen_files = HashSet::new();

    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(path) => {
                            opt.respect_ignores
                                && path_is_stylua_ignored(
                                    path,
                                    opt.search_parent_directories,
                                    None,
                                )?
                        }
                        None => false,
                    };

                    let config = config_resolver.load_configuration_for_stdin()?;

                    pool.execute(move || {
                        let mut buf = String::new();
                        tx.send(
                            stdin()
                                .read_to_string(&mut buf)
                                .map_err(|err| err.into())
                                .and_then(|_| {
                                    format_string(
                                        buf,
                                        config,
                                        range,
                                        &opt,
                                        verify_output,
                                        should_skip_format,
                                    )
                                    .context("could not format from stdin")
                                })
                                .map_err(|error| {
                                    ErrorFileWrapper {
                                        file: "stdin".to_string(),
                                        error,
                                    }
                                    .into()
                                }),
                        )
                        .unwrap()
                    });
                } else {
                    let path = entry.path().to_owned(); // TODO: stop to_owned?
                    let opt = opt.clone();

                    if seen_files.contains(&path) {
                        continue;
                    }
                    seen_files.insert(path.clone());

                    if path.is_file() {
                        // If the user didn't provide a glob pattern, we should match against our default one
                        if use_default_glob && should_respect_ignores(opt.as_ref(), path.as_path())
                        {
                            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;
                            }
                        }

                        // If `--respect-ignores` was given and this is an explicit file path,
                        // we should check .styluaignore
                        if is_explicitly_provided(opt.as_ref(), &path)
                            && should_respect_ignores(opt.as_ref(), &path)
                            && path_is_stylua_ignored(&path, opt.search_parent_directories, None)?
                        {
                            continue;
                        }

                        let config = config_resolver.load_configuration(&path)?;

                        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();

    // Output summary

    if matches!(opt.output_format, opt::OutputFormat::Summary) {
        let file_count = UNFORMATTED_FILE_COUNT.load(Ordering::SeqCst);
        if file_count == 0 {
            println!(
                "{} All files are correctly formatted.",
                style("✓")
                    .green()
                    .bold()
                    .force_styling(opt.color.should_use_color())
            );
        } else {
            println!(
                "{} Code style issues found in {} file{} above.",
                style("✕")
                    .red()
                    .bold()
                    .force_styling(opt.color.should_use_color()),
                style(file_count)
                    .yellow()
                    .bold()
                    .force_styling(opt.color.should_use_color()),
                if file_count == 1 { "" } else { "s" }
            );
        }
    }

    // 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;
    use assert_fs::prelude::*;

    macro_rules! construct_tree {
        ({ $($file_name:literal:$file_contents:literal,)* }) => {{
            let cwd = assert_fs::TempDir::new().unwrap();

            $(
                cwd.child($file_name).write_str($file_contents).unwrap();
            )*

            cwd
        }};
    }

    fn create_stylua() -> Command {
        Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap()
    }

    #[test]
    fn test_no_files_provided() {
        let mut cmd = create_stylua();
        cmd.assert()
            .failure()
            .code(2)
            .stderr("error: no files provided\n");
    }

    #[test]
    fn test_format_stdin() {
        let mut cmd = create_stylua();
        cmd.arg("-")
            .write_stdin("local   x   = 1")
            .assert()
            .success()
            .stdout("local x = 1\n");
    }

    #[test]
    fn test_format_file() {
        let cwd = construct_tree!({
            "foo.lua": "local   x    =   1",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path()).arg(".").assert().success();

        cwd.child("foo.lua").assert("local x = 1\n");

        cwd.close().unwrap();
    }

    #[test]
    fn test_stylua_ignore() {
        let cwd = construct_tree!({
            ".styluaignore": "ignored/",
            "foo.lua": "local   x    =   1",
            "ignored/bar.lua": "local   x    =   1",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path()).arg(".").assert().success();

        cwd.child("foo.lua").assert("local x = 1\n");
        cwd.child("ignored/bar.lua").assert("local   x    =   1");

        cwd.close().unwrap();
    }

    #[test]
    fn explicitly_provided_files_dont_check_ignores() {
        let cwd = construct_tree!({
            ".styluaignore": "foo.lua",
            "foo.lua": "local   x    =   1",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .arg("foo.lua")
            .assert()
            .success();

        cwd.child("foo.lua").assert("local x = 1\n");

        cwd.close().unwrap();
    }

    #[test]
    fn explicitly_provided_files_dont_check_ignores_stdin() {
        let cwd = construct_tree!({
            ".styluaignore": "foo.lua",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .args(["--stdin-filepath", "foo.lua", "-"])
            .write_stdin("local   x    =   1")
            .assert()
            .success()
            .stdout("local x = 1\n");

        cwd.close().unwrap();
    }

    #[test]
    fn explicitly_provided_files_not_in_cwd() {
        let cwd = construct_tree!({
            ".styluaignore": "foo.lua",
        });

        let another = construct_tree!({});

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .args([
                "--respect-ignores",
                "--stdin-filepath",
                another.child("foo.lua").to_str().unwrap(),
                "-",
            ])
            .write_stdin("local   x    =   1")
            .assert()
            .success()
            .stdout("local x = 1\n");

        cwd.close().unwrap();
    }

    #[test]
    fn test_respect_ignores() {
        let cwd = construct_tree!({
            ".styluaignore": "foo.lua",
            "foo.lua": "local   x    =   1",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .args(["--respect-ignores", "foo.lua"])
            .assert()
            .success();

        cwd.child("foo.lua").assert("local   x    =   1");

        cwd.close().unwrap();
    }

    #[test]
    fn test_respect_ignores_stdin() {
        let cwd = construct_tree!({
            ".styluaignore": "foo.lua",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .args(["--respect-ignores", "--stdin-filepath", "foo.lua", "-"])
            .write_stdin("local   x    =   1")
            .assert()
            .success()
            .stdout("local   x    =   1");

        cwd.close().unwrap();
    }

    #[test]
    fn test_respect_ignores_directory_no_glob() {
        // https://github.com/JohnnyMorganz/StyLua/issues/845
        let cwd = construct_tree!({
            ".styluaignore": "build/",
            "build/foo.lua": "local   x    =   1",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .args(["--check", "--respect-ignores", "build/foo.lua"])
            .assert()
            .success();

        cwd.close().unwrap();
    }

    #[test]
    fn test_formatting_respects_gitignore() {
        let cwd = construct_tree!({
            ".git/dummy.txt": "", // Need a .git folder for .gitignore lookup
            ".gitignore": "foo.lua",
            "foo.lua": "local   x    =   1",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path()).args(["."]).assert().success();

        cwd.child("foo.lua").assert("local   x    =   1");

        cwd.close().unwrap();
    }

    #[test]
    fn test_formatting_still_formats_gitignore_files_if_requested() {
        let cwd = construct_tree!({
            ".git/dummy.txt": "", // Need a .git folder for .gitignore lookup
            ".gitignore": "foo.lua",
            "foo.lua": "local   x    =   1",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .args(["--no-ignore-vcs", "."])
            .assert()
            .success();

        cwd.child("foo.lua").assert("local x = 1\n");

        cwd.close().unwrap();
    }

    #[test]
    fn test_stdin_filepath_respects_cwd_configuration_next_to_file() {
        let cwd = construct_tree!({
            "stylua.toml": "quote_style = 'AutoPreferSingle'",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .args(["--stdin-filepath", "foo.lua", "-"])
            .write_stdin("local x = \"hello\"")
            .assert()
            .success()
            .stdout("local x = 'hello'\n");

        cwd.close().unwrap();
    }

    #[test]
    fn test_stdin_filepath_respects_cwd_configuration_for_nested_file() {
        let cwd = construct_tree!({
            "stylua.toml": "quote_style = 'AutoPreferSingle'",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .args(["--stdin-filepath", "build/foo.lua", "-"])
            .write_stdin("local x = \"hello\"")
            .assert()
            .success()
            .stdout("local x = 'hello'\n");

        cwd.close().unwrap();
    }

    #[test]
    fn test_cwd_configuration_respected_when_formatting_from_stdin() {
        let cwd = construct_tree!({
            "stylua.toml": "quote_style = 'AutoPreferSingle'",
            "foo.lua": "local x = \"hello\"",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .arg("-")
            .write_stdin("local x = \"hello\"")
            .assert()
            .success()
            .stdout("local x = 'hello'\n");

        cwd.close().unwrap();
    }

    #[test]
    fn test_cwd_configuration_respected_for_file_in_cwd() {
        let cwd = construct_tree!({
            "stylua.toml": "quote_style = 'AutoPreferSingle'",
            "foo.lua": "local x = \"hello\"",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .arg("foo.lua")
            .assert()
            .success();

        cwd.child("foo.lua").assert("local x = 'hello'\n");

        cwd.close().unwrap();
    }

    #[test]
    fn test_cwd_configuration_respected_for_nested_file() {
        let cwd = construct_tree!({
            "stylua.toml": "quote_style = 'AutoPreferSingle'",
            "build/foo.lua": "local x = \"hello\"",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .arg("build/foo.lua")
            .assert()
            .success();

        cwd.child("build/foo.lua").assert("local x = 'hello'\n");

        cwd.close().unwrap();
    }

    #[test]
    fn test_configuration_is_not_used_outside_of_cwd() {
        let cwd = construct_tree!({
            "stylua.toml": "quote_style = 'AutoPreferSingle'",
            "build/foo.lua": "local x = \"hello\"",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.child("build").path())
            .arg("foo.lua")
            .assert()
            .success();

        cwd.child("build/foo.lua").assert("local x = \"hello\"\n");

        cwd.close().unwrap();
    }

    #[test]
    fn test_configuration_used_outside_of_cwd_when_search_parent_directories_is_enabled() {
        let cwd = construct_tree!({
            "stylua.toml": "quote_style = 'AutoPreferSingle'",
            "build/foo.lua": "local x = \"hello\"",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.child("build").path())
            .args(["--search-parent-directories", "foo.lua"])
            .assert()
            .success();

        cwd.child("build/foo.lua").assert("local x = 'hello'\n");

        cwd.close().unwrap();
    }

    #[test]
    fn test_configuration_is_searched_next_to_file() {
        let cwd = construct_tree!({
            "build/stylua.toml": "quote_style = 'AutoPreferSingle'",
            "build/foo.lua": "local x = \"hello\"",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .arg("build/foo.lua")
            .assert()
            .success();

        cwd.child("build/foo.lua").assert("local x = 'hello'\n");

        cwd.close().unwrap();
    }

    #[test]
    fn test_configuration_is_used_closest_to_the_file() {
        let cwd = construct_tree!({
            "stylua.toml": "quote_style = 'AutoPreferDouble'",
            "build/stylua.toml": "quote_style = 'AutoPreferSingle'",
            "build/foo.lua": "local x = \"hello\"",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .arg("build/foo.lua")
            .assert()
            .success();

        cwd.child("build/foo.lua").assert("local x = 'hello'\n");

        cwd.close().unwrap();
    }

    #[test]
    fn test_respect_config_path_override() {
        let cwd = construct_tree!({
            "stylua.toml": "quote_style = 'AutoPreferDouble'",
            "build/stylua.toml": "quote_style = 'AutoPreferSingle'",
            "foo.lua": "local x = \"hello\"",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .args(["--config-path", "build/stylua.toml", "foo.lua"])
            .assert()
            .success();
    }

    #[test]
    fn test_respect_config_path_override_for_stdin_filepath() {
        let cwd = construct_tree!({
            "stylua.toml": "quote_style = 'AutoPreferDouble'",
            "build/stylua.toml": "quote_style = 'AutoPreferSingle'",
            "foo.lua": "local x = \"hello\"",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .args(["--config-path", "build/stylua.toml", "-"])
            .write_stdin("local x = \"hello\"")
            .assert()
            .success()
            .stdout("local x = 'hello'\n");

        cwd.close().unwrap();
    }

    #[test]
    fn test_uses_cli_overrides_instead_of_default_configuration() {
        let cwd = construct_tree!({
            "foo.lua": "local x = \"hello\"",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .args(["--quote-style", "AutoPreferSingle", "."])
            .assert()
            .success();

        cwd.child("foo.lua").assert("local x = 'hello'\n");

        cwd.close().unwrap();
    }

    #[test]
    fn test_uses_cli_overrides_instead_of_default_configuration_stdin_filepath() {
        let cwd = construct_tree!({
            "foo.lua": "local x = \"hello\"",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .args(["--quote-style", "AutoPreferSingle", "-"])
            .write_stdin("local x = \"hello\"")
            .assert()
            .success()
            .stdout("local x = 'hello'\n");

        cwd.close().unwrap();
    }

    #[test]
    fn test_uses_cli_overrides_instead_of_found_configuration() {
        let cwd = construct_tree!({
            "stylua.toml": "quote_style = 'AutoPreferDouble'",
            "foo.lua": "local x = \"hello\"",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .args(["--quote-style", "AutoPreferSingle", "."])
            .assert()
            .success();

        cwd.child("foo.lua").assert("local x = 'hello'\n");

        cwd.close().unwrap();
    }

    #[test]
    fn test_uses_cli_overrides_instead_of_found_configuration_stdin_filepath() {
        let cwd = construct_tree!({
            "stylua.toml": "quote_style = 'AutoPreferDouble'",
            "foo.lua": "local x = \"hello\"",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .args(["--quote-style", "AutoPreferSingle", "-"])
            .write_stdin("local x = \"hello\"")
            .assert()
            .success()
            .stdout("local x = 'hello'\n");

        cwd.close().unwrap();
    }

    #[test]
    #[cfg(feature = "editorconfig")]
    fn test_editorconfig_child_without_root_merges_with_parent() {
        let cwd = construct_tree!({
            ".editorconfig": "root = true\n\n[*.lua]\nindent_style = space\nindent_size = 2\n",
            "child/.editorconfig": "[*.lua]\nquote_type = single\n",
            "child/foo.lua": "local foo = {\n\ta = 1,\n}\n\nlocal bar = \"\"\n",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .arg("child/foo.lua")
            .assert()
            .success();

        // indent from parent, quotes from child
        cwd.child("child/foo.lua")
            .assert("local foo = {\n  a = 1,\n}\n\nlocal bar = ''\n");

        cwd.close().unwrap();
    }

    #[test]
    #[cfg(feature = "editorconfig")]
    fn test_editorconfig_root_true_stops_upward_search() {
        let cwd = construct_tree!({
            ".editorconfig": "root = true\n\n[*.lua]\nindent_style = space\nindent_size = 2\nquote_type = single\n",
            "child/.editorconfig": "root = true\n\n[*.lua]\nindent_style = space\nindent_size = 4\n",
            "child/foo.lua": "local foo = {\n\ta = 1,\n}\n\nlocal bar = \"\"\n",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .arg("child/foo.lua")
            .assert()
            .success();

        // indent_size=4 from child; parent's quote_type=single must NOT be inherited
        cwd.child("child/foo.lua")
            .assert("local foo = {\n    a = 1,\n}\n\nlocal bar = \"\"\n");

        cwd.close().unwrap();
    }

    #[test]
    #[cfg(feature = "editorconfig")]
    fn test_editorconfig_closer_config_takes_precedence() {
        let cwd = construct_tree!({
            ".editorconfig": "root = true\n\n[*.lua]\nindent_style = space\nindent_size = 2\nquote_type = single\n",
            "child/.editorconfig": "[*.lua]\nindent_size = 4\n",
            "child/foo.lua": "local foo = {\n\ta = 1,\n}\n\nlocal bar = \"\"\n",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .arg("child/foo.lua")
            .assert()
            .success();

        // indent_size=4 from child overrides parent's 2; quote_type=single inherited from parent
        cwd.child("child/foo.lua")
            .assert("local foo = {\n    a = 1,\n}\n\nlocal bar = ''\n");

        cwd.close().unwrap();
    }

    #[test]
    #[cfg(feature = "editorconfig")]
    fn test_editorconfig_merges_across_three_directory_levels() {
        let cwd = construct_tree!({
            ".editorconfig": "root = true\n\n[*.lua]\nindent_style = space\nindent_size = 2\n",
            "middle/.editorconfig": "[*.lua]\nquote_type = single\n",
            "middle/inner/.editorconfig": "[*.lua]\nmax_line_length = 80\n",
            "middle/inner/foo.lua": "local foo = {\n\ta = 1,\n}\n\nlocal bar = \"\"\n",
        });

        let mut cmd = create_stylua();
        cmd.current_dir(cwd.path())
            .arg("middle/inner/foo.lua")
            .assert()
            .success();

        // indent from root, quotes from middle, max_line_length from inner
        cwd.child("middle/inner/foo.lua")
            .assert("local foo = {\n  a = 1,\n}\n\nlocal bar = ''\n");

        cwd.close().unwrap();
    }
}