-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.rs
1681 lines (1499 loc) · 61.4 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
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
//! The main entrypoint to `srgn` as a CLI application.
//!
//! It mainly draws from `srgn`, the library, for actual implementations. This file then
//! deals with CLI argument handling, I/O, threading, and more.
use std::error::Error;
use std::fs::{self, File};
use std::io::{self, stdout, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::{env, fmt};
use anyhow::{Context, Result};
use colored::Colorize;
use ignore::{WalkBuilder, WalkState};
use itertools::Itertools;
use log::{debug, error, info, trace, warn, LevelFilter};
use pathdiff::diff_paths;
#[cfg(feature = "german")]
use srgn::actions::German;
use srgn::actions::{
Action, ActionError, Deletion, Lower, Normalization, Replacement, Style, Titlecase, Upper,
};
#[cfg(feature = "symbols")]
use srgn::actions::{Symbols, SymbolsInversion};
use srgn::iterext::ParallelZipExt;
use srgn::scoping::langs::LanguageScoper;
use srgn::scoping::literal::{Literal, LiteralError};
use srgn::scoping::regex::{Regex, RegexError};
use srgn::scoping::view::ScopedViewBuilder;
use srgn::scoping::Scoper;
use tree_sitter::QueryError as TSQueryError;
// We have `LanguageScoper: Scoper`, but we cannot upcast
// (https://github.com/rust-lang/rust/issues/65991), so hack around the limitation
// by providing both.
type ScoperList = Vec<Box<dyn LanguageScoper>>;
#[allow(clippy::too_many_lines)] // Only slightly above.
#[allow(clippy::cognitive_complexity)]
fn main() -> Result<()> {
let args = cli::Args::init();
let level_filter = level_filter_from_env_and_verbosity(args.options.additional_verbosity);
env_logger::Builder::new()
.filter_level(level_filter)
.format_timestamp_micros() // High precision is nice for benchmarks
.init();
info!("Launching app with args: {:?}", args);
let cli::Args {
scope,
shell,
composable_actions,
standalone_actions,
mut options,
languages_scopes,
#[cfg(feature = "german")]
german_options,
} = args;
if let Some(shell) = shell {
debug!("Generating completions file for {shell:?}.");
cli::print_completions(shell, &mut cli::Args::command());
debug!("Done generating completions file, exiting.");
return Ok(());
}
let standalone_action = standalone_actions.into();
debug!("Assembling scopers.");
let general_scoper = get_general_scoper(&options, scope)?;
// Will be sent across threads and might (the borrow checker is convinced at least)
// outlive the main one. Scoped threads would work here, `ignore` uses them
// internally even, but we have no access here.
let language_scopers = languages_scopes
.compile_query_sources_to_scopes()?
.map(Arc::new);
debug!("Done assembling scopers.");
let mut actions = {
debug!("Assembling actions.");
let mut actions = assemble_common_actions(&composable_actions, standalone_action)?;
#[cfg(feature = "symbols")]
if composable_actions.symbols {
if options.invert {
actions.push(Box::<SymbolsInversion>::default());
debug!("Loaded action: SymbolsInversion");
} else {
actions.push(Box::<Symbols>::default());
debug!("Loaded action: Symbols");
}
}
#[cfg(feature = "german")]
if composable_actions.german {
actions.push(Box::new(German::new(
// Smell? Bug if bools swapped.
german_options.german_prefer_original,
german_options.german_naive,
)));
debug!("Loaded action: German");
}
debug!("Done assembling actions.");
actions
};
let is_readable_stdin = grep_cli::is_readable_stdin();
info!("Detected stdin as readable: {is_readable_stdin}.");
// See where we're reading from
let input = match (
options.stdin_override_to.unwrap_or(is_readable_stdin),
options.glob.clone(),
&language_scopers,
) {
// stdin considered viable: always use it.
(true, None, _)
// Nothing explicitly available: this should open an interactive stdin prompt.
| (false, None, None) => Input::Stdin,
(true, Some(..), _) => {
// Usage error... warn loudly, the user is likely interested.
error!("Detected stdin, and request for files: will use stdin and ignore files.");
Input::Stdin
}
// When a pattern is specified, it takes precedence.
(false, Some(pattern), _) => Input::WalkOn(Box::new(move |path| {
let res = pattern.matches_path(path);
trace!("Path '{}' matches: {}.", path.display(), res);
res
})),
// If pattern wasn't manually overridden, consult the language scoper itself, if
// any.
(false, None, Some(language_scopers)) => {
let language_scopers = Arc::clone(language_scopers);
Input::WalkOn(Box::new(move |path| {
// TODO: perform this work only once (it's super fast but in the hot
// path).
let res = language_scopers
.iter()
.map(|s| s.is_valid_path(path))
.all_equal_value()
.expect("all language scopers to agree on path validity");
trace!(
"Language scoper considers path '{}' valid: {}",
path.display(),
res
);
res
}))
},
};
// Only have this kick in if a language scoper is in play; otherwise, we'd just be a
// poor imitation of ripgrep itself. Plus, this retains the `tr`-like behavior,
// setting it apart from other utilities.
let search_mode = actions.is_empty() && language_scopers.is_some() || options.dry_run;
if search_mode {
info!("Will use search mode."); // Modelled after ripgrep!
let style = if options.dry_run {
Style::green_bold() // "Would change to this", like git diff
} else {
Style::red_bold() // "Found!", like ripgrep
};
actions.push(Box::new(style));
options.only_matching = true;
options.line_numbers = true;
options.fail_none = true;
}
if actions.is_empty() && !search_mode {
// Also kind of an error users will likely want to know about.
error!(
"No actions specified, and not in search mode. Will return input unchanged, if any."
);
}
let pipeline = if options.dry_run {
let action: Box<dyn Action> = Box::new(Style::red_bold());
let color_only = vec![action];
vec![color_only, actions]
} else {
vec![actions]
};
let pipeline: Vec<&[Box<dyn Action>]> = pipeline.iter().map(Vec::as_slice).collect();
let language_scopers = language_scopers.unwrap_or_default();
// Now write out
match (input, options.sorted) {
(Input::Stdin, _ /* no effect */) => {
info!("Will read from stdin and write to stdout, applying actions.");
handle_actions_on_stdin(
&options,
standalone_action,
&general_scoper,
&language_scopers,
&pipeline,
)?;
}
(Input::WalkOn(validator), false) => {
info!("Will walk file tree, applying actions.");
handle_actions_on_many_files_threaded(
&options,
standalone_action,
&validator,
&general_scoper,
&language_scopers,
&pipeline,
search_mode,
options.threads.map_or_else(
|| std::thread::available_parallelism().map_or(1, std::num::NonZero::get),
std::num::NonZero::get,
),
)?;
}
(Input::WalkOn(validator), true) => {
info!("Will walk file tree, applying actions.");
handle_actions_on_many_files_sorted(
&options,
standalone_action,
&validator,
&general_scoper,
&language_scopers,
&pipeline,
search_mode,
)?;
}
};
info!("Done, exiting");
Ok(())
}
/// Indicates whether a filesystem path is valid according to some criteria (glob
/// pattern, ...).
type Validator = Box<dyn Fn(&Path) -> bool + Send + Sync>;
/// The input to read from.
enum Input {
/// Standard input.
Stdin,
/// Use a recursive directory walker, and apply the contained validator, which
/// indicates valid filesystem entries. This is similar to globbing, but more
/// flexible.
WalkOn(Validator),
}
/// A standalone action to perform on the results of applying a scope.
#[derive(Clone, Copy, Debug)]
enum StandaloneAction {
/// Delete anything in scope.
///
/// Cannot be used with any other action: there is no point in deleting and
/// performing any other processing. Sibling actions would either receive empty
/// input or have their work wiped.
Delete,
/// Squeeze consecutive occurrences of scope into one.
Squeeze,
/// No stand alone action is set.
None,
}
/// A "pipeline" in that there's not just a single sequence (== slice) of actions, but
/// instead multiple. These can be used in parallel (on the same or different views),
/// and the different results then used for advanced use cases. For example, diffing
/// different results against one another.
type Pipeline<'a> = &'a [&'a [Box<dyn Action>]];
/// Main entrypoint for simple `stdin` -> `stdout` processing.
#[allow(clippy::borrowed_box)] // Used throughout, not much of a pain
fn handle_actions_on_stdin(
global_options: &cli::GlobalOptions,
standalone_action: StandaloneAction,
general_scoper: &Box<dyn Scoper>,
language_scopers: &[Box<dyn LanguageScoper>],
pipeline: Pipeline<'_>,
) -> Result<(), ProgramError> {
info!("Will use stdin to stdout.");
let mut source = String::new();
io::stdin().lock().read_to_string(&mut source)?;
let mut destination = String::with_capacity(source.len());
apply(
global_options,
standalone_action,
&source,
&mut destination,
general_scoper,
language_scopers,
pipeline,
)?;
stdout().lock().write_all(destination.as_bytes())?;
Ok(())
}
/// Main entrypoint for processing using strictly sequential, *single-threaded*
/// processing.
///
/// If it's good enough for [ripgrep], it's good enough for us :-). Main benefit it full
/// control of output for testing anyway.
///
/// [ripgrep]:
/// https://github.com/BurntSushi/ripgrep/blob/71d71d2d98964653cdfcfa315802f518664759d7/GUIDE.md#L1016-L1017
#[allow(clippy::borrowed_box)] // Used throughout, not much of a pain
fn handle_actions_on_many_files_sorted(
global_options: &cli::GlobalOptions,
standalone_action: StandaloneAction,
validator: &Validator,
general_scoper: &Box<dyn Scoper>,
language_scopers: &[Box<dyn LanguageScoper>],
pipeline: Pipeline<'_>,
search_mode: bool,
) -> Result<(), ProgramError> {
let root = env::current_dir()?;
info!(
"Will walk file tree sequentially, in sorted order, starting from: {:?}",
root.canonicalize()
);
let mut n_files_processed: usize = 0;
let mut n_files_seen: usize = 0;
for entry in WalkBuilder::new(&root)
.hidden(!global_options.hidden)
.git_ignore(!global_options.gitignored)
.sort_by_file_path(Ord::cmp)
.build()
{
match entry {
Ok(entry) => {
let path = entry.path();
let res = process_path(
global_options,
standalone_action,
path,
&root,
validator,
general_scoper,
language_scopers,
pipeline,
search_mode,
);
n_files_seen += match res {
Err(PathProcessingError::NotAFile | PathProcessingError::InvalidFile) => 0,
_ => 1,
};
n_files_processed += match res {
Ok(()) => 1,
// Soft errors with reasonable handling available:
Err(PathProcessingError::NotAFile | PathProcessingError::InvalidFile) => 0,
Err(PathProcessingError::ApplicationError(ApplicationError::SomeInScope))
if global_options.fail_any =>
{
// Early-out
info!("Match at {}, exiting early", path.display());
return Err(ProgramError::SomethingProcessed);
}
#[allow(clippy::match_same_arms)]
Err(PathProcessingError::ApplicationError(
ApplicationError::NoneInScope | ApplicationError::SomeInScope,
)) => 0,
Err(PathProcessingError::IoError(e, _))
if e.kind() == io::ErrorKind::BrokenPipe && search_mode =>
{
trace!("Detected broken pipe, stopping search.");
break;
}
Err(PathProcessingError::IoError(e, _))
// `InvalidData` does NOT equal "invalid utf-8", but that's how
// it's _effectively_ used in the "read to string" type of
// functions we use throughout.
// https://github.com/rust-lang/rust/blob/096277e989d6de11c3077472fc05778e261e7b8e/library/std/src/io/error.rs#L78-L79
if e.kind() == io::ErrorKind::InvalidData =>
{
warn!("File contains unreadable data (binary? invalid utf-8?), skipped: {}", path.display());
0
}
// Hard errors we should do something about:
Err(
e @ (PathProcessingError::ApplicationError(ApplicationError::ActionError(
..,
))
| PathProcessingError::IoError(..)),
) => {
if search_mode {
error!("Error walking at {}: {}", path.display(), e);
0
} else {
error!("Aborting walk at {} due to: {}", path.display(), e);
return Err(e.into());
}
}
}
}
Err(e) => {
if search_mode {
error!("Error walking: {}", e);
} else {
error!("Aborting walk due to: {}", e);
return Err(e.into());
}
}
}
}
info!("Saw {} items", n_files_seen);
info!("Processed {} files", n_files_processed);
if n_files_seen == 0 && global_options.fail_no_files {
Err(ProgramError::NoFilesFound)
} else if n_files_processed == 0 && global_options.fail_none {
Err(ProgramError::NothingProcessed)
} else {
Ok(())
}
}
/// Main entrypoint for processing using at least 1 thread.
#[allow(clippy::borrowed_box)] // Used throughout, not much of a pain
#[allow(clippy::too_many_lines)]
#[allow(clippy::too_many_arguments)]
fn handle_actions_on_many_files_threaded(
global_options: &cli::GlobalOptions,
standalone_action: StandaloneAction,
validator: &Validator,
general_scoper: &Box<dyn Scoper>,
language_scopers: &[Box<dyn LanguageScoper>],
pipeline: Pipeline<'_>,
search_mode: bool,
n_threads: usize,
) -> Result<(), ProgramError> {
let root = env::current_dir()?;
info!(
"Will walk file tree using {:?} thread(s), processing in arbitrary order, starting from: {:?}",
n_threads,
root.canonicalize()
);
let n_files_processed = Arc::new(Mutex::new(0usize));
let n_files_seen = Arc::new(Mutex::new(0usize));
let err: Arc<Mutex<Option<ProgramError>>> = Arc::new(Mutex::new(None));
WalkBuilder::new(&root)
.threads(
// https://github.com/BurntSushi/ripgrep/issues/2854
n_threads,
)
.hidden(!global_options.hidden)
.git_ignore(!global_options.gitignored)
.build_parallel()
.run(|| {
Box::new(|entry| match entry {
Ok(entry) => {
let path = entry.path();
let res = process_path(
global_options,
standalone_action,
path,
&root,
validator,
general_scoper,
language_scopers,
pipeline,
search_mode,
);
match res {
Err(PathProcessingError::NotAFile | PathProcessingError::InvalidFile) => (),
_ => *n_files_seen.lock().unwrap() += 1,
}
match res {
Ok(()) => {
*n_files_processed.lock().unwrap() += 1;
WalkState::Continue
}
// Soft errors with reasonable handling available:
Err(PathProcessingError::NotAFile | PathProcessingError::InvalidFile) => {
WalkState::Continue
}
Err(
e
@ PathProcessingError::ApplicationError(ApplicationError::SomeInScope),
) if global_options.fail_any => {
// Early-out
info!("Match at {}, exiting early", path.display());
*err.lock().unwrap() = Some(e.into());
WalkState::Quit
}
Err(PathProcessingError::ApplicationError(
ApplicationError::NoneInScope | ApplicationError::SomeInScope,
)) => WalkState::Continue,
Err(PathProcessingError::IoError(e, _))
if e.kind() == io::ErrorKind::BrokenPipe && search_mode =>
{
trace!("Detected broken pipe, stopping search.");
WalkState::Quit
}
Err(PathProcessingError::IoError(e, _))
// `InvalidData` does NOT equal "invalid utf-8", but that's
// how it's _effectively_ used in the "read to string" type
// of functions we use throughout.
// https://github.com/rust-lang/rust/blob/096277e989d6de11c3077472fc05778e261e7b8e/library/std/src/io/error.rs#L78-L79
if e.kind() == io::ErrorKind::InvalidData =>
{
warn!("File contains unreadable data (binary? invalid utf-8?), skipped: {}", path.display());
WalkState::Continue
}
// Hard errors we should do something about:
Err(
e @ (PathProcessingError::ApplicationError(..)
| PathProcessingError::IoError(..)),
) => {
error!("Error walking at {} due to: {}", path.display(), e);
if search_mode {
WalkState::Continue
} else {
// Chances are something bad and/or unintended happened;
// bail out to limit any potential damage.
error!("Aborting walk for safety");
*err.lock().unwrap() = Some(e.into());
WalkState::Quit
}
}
}
}
Err(e) => {
if search_mode {
error!("Error walking: {}", e);
WalkState::Continue
} else {
error!("Aborting walk due to: {}", e);
*err.lock().unwrap() = Some(e.into());
WalkState::Quit
}
}
})
});
let error = err.lock().unwrap().take();
if let Some(e) = error {
return Err(e);
}
let n_files_seen = *n_files_seen.lock().unwrap();
info!("Saw {} items", n_files_seen);
let n_files_processed = *n_files_processed.lock().unwrap();
info!("Processed {} files", n_files_processed);
if n_files_seen == 0 && global_options.fail_no_files {
Err(ProgramError::NoFilesFound)
} else if n_files_processed == 0 && global_options.fail_none {
Err(ProgramError::NothingProcessed)
} else {
Ok(())
}
}
#[allow(clippy::too_many_arguments)]
#[allow(clippy::borrowed_box)] // Used throughout, not much of a pain
fn process_path(
global_options: &cli::GlobalOptions,
standalone_action: StandaloneAction,
path: &Path,
root: &Path,
validator: &Validator,
general_scoper: &Box<dyn Scoper>,
language_scopers: &[Box<dyn LanguageScoper>],
pipeline: Pipeline<'_>,
search_mode: bool,
) -> std::result::Result<(), PathProcessingError> {
if !path.is_file() {
trace!("Skipping path (not a file): {:?}", path);
return Err(PathProcessingError::NotAFile);
}
let path = diff_paths(path, root).expect("started walk at root, so relative to root works");
if !validator(&path) {
trace!("Skipping path (invalid): {:?}", path);
return Err(PathProcessingError::InvalidFile);
}
debug!("Processing path: {:?}", path);
let (new_contents, filesize, changed) = {
let mut file = File::open(&path)?;
let filesize = file.metadata().map_or(0, |m| m.len());
let mut source =
String::with_capacity(filesize.try_into().unwrap_or(/* no perf gains for you */ 0));
file.read_to_string(&mut source)?;
let mut destination = String::with_capacity(source.len());
let changed = apply(
global_options,
standalone_action,
&source,
&mut destination,
general_scoper,
language_scopers,
pipeline,
)?;
(destination, filesize, changed)
};
// Hold the lock so results aren't intertwined
let mut stdout = stdout().lock();
if search_mode {
if !new_contents.is_empty() {
writeln!(
stdout,
"{}\n{}",
path.display().to_string().magenta(),
&new_contents
)?;
}
} else {
if filesize > 0 && new_contents.is_empty() {
error!(
"Failsafe triggered: file {} is nonempty ({} bytes), but new contents are empty. Will not wipe file.",
path.display(),
filesize
);
return Err(io::Error::new(
io::ErrorKind::Other,
"attempt to wipe non-empty file (failsafe guard)",
)
.into());
}
if changed {
debug!("Got new file contents, writing to file: {:?}", path);
assert!(
!global_options.dry_run,
// Dry run leverages search mode, so should never get here. Assert for
// extra safety.
"Dry running, but attempted to write file!"
);
fs::write(&path, new_contents.as_bytes())?;
// Confirm after successful processing.
writeln!(stdout, "{}", path.display())?;
} else {
debug!(
"Skipping writing file anew (nothing changed): {}",
path.display()
);
}
debug!("Done processing file: {:?}", path);
};
Ok(())
}
/// Runs the actual core processing, returning whether anything changed in the output
/// compared to the input.
///
/// TODO: The way this interacts with [`process_path`] etc. is just **awful** spaghetti
/// of the most imperative, procedural kind. Refactor needed.
#[allow(clippy::borrowed_box)] // Used throughout, not much of a pain
fn apply(
global_options: &cli::GlobalOptions,
standalone_action: StandaloneAction,
source: &str,
// Use a string to avoid repeated and unnecessary bytes -> utf8 conversions and
// corresponding checks.
destination: &mut String,
general_scoper: &Box<dyn Scoper>,
language_scopers: &[Box<dyn LanguageScoper>],
pipeline: Pipeline<'_>,
) -> std::result::Result<bool, ApplicationError> {
debug!("Building view.");
let mut builder = ScopedViewBuilder::new(source);
if global_options.join_language_scopes {
// All at once, as a slice: hits a specific, 'joining' `impl`
builder.explode(&language_scopers);
} else {
// One by one: hits a different, 'intersecting' `impl`
for scoper in language_scopers {
builder.explode(scoper);
}
}
builder.explode(general_scoper);
let mut view = builder.build();
debug!("Done building view: {view:?}");
if global_options.fail_none && !view.has_any_in_scope() {
return Err(ApplicationError::NoneInScope);
}
if global_options.fail_any && view.has_any_in_scope() {
return Err(ApplicationError::SomeInScope);
};
debug!("Applying actions to view.");
if matches!(standalone_action, StandaloneAction::Squeeze) {
view.squeeze();
}
// Give each pipeline its own fresh view
let mut views = vec![view; pipeline.len()];
for (actions, view) in pipeline.iter().zip_eq(&mut views) {
for action in *actions {
view.map_with_context(action)?;
}
}
debug!("Writing to destination.");
let line_based = global_options.only_matching || global_options.line_numbers;
if line_based {
let line_based_views = views.iter().map(|v| v.lines().into_iter()).collect_vec();
for (i, lines) in line_based_views.into_iter().parallel_zip().enumerate() {
let i = i + 1;
for line in lines {
if !global_options.only_matching || line.has_any_in_scope() {
if global_options.line_numbers {
// `ColoredString` needs to be 'evaluated' to do anything; make sure
// to not forget even if this is moved outside of `format!`.
#[allow(clippy::to_string_in_format_args)]
destination.push_str(&format!("{}:", i.to_string().green().to_string()));
}
destination.push_str(&line.to_string());
}
}
}
} else {
assert_eq!(
views.len(),
1,
// Multiple views are useful for e.g. diffing, which works line-based (see
// `dry_run`). When not line-based, they *currently* do not make sense, as
// there's neither any code path where there *would* be multiple views at
// this point, *nor* a valid use case. Printing multiple views here would
// probably wreak havoc.
"Multiple views at this stage make no sense."
);
for view in views {
destination.push_str(&view.to_string());
}
};
debug!("Done writing to destination.");
Ok(source != *destination)
}
/// Top-level, user-facing errors, affecting and possibly terminating program execution
/// as a whole.
#[derive(Debug)]
enum ProgramError {
/// Error when handling a path.
PathProcessingError(PathProcessingError),
/// Error when applying.
ApplicationError(ApplicationError),
/// No files were found, unexpectedly.
NoFilesFound,
/// Files were found but nothing ended up being processed, unexpectedly.
NothingProcessed,
/// Files were found but some input ended up being processed, unexpectedly.
SomethingProcessed,
/// I/O error.
IoError(io::Error),
/// Error while processing files for walking.
IgnoreError(ignore::Error),
/// The given query failed to parse
QueryError(TSQueryError),
}
impl fmt::Display for ProgramError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::PathProcessingError(e) => write!(f, "Error processing path: {e}"),
Self::ApplicationError(e) => write!(f, "Error applying: {e}"),
Self::NoFilesFound => write!(f, "No files found"),
Self::NothingProcessed => write!(f, "No input was in scope"),
Self::SomethingProcessed => write!(f, "Some input was in scope"),
Self::IoError(e) => write!(f, "I/O error: {e}"),
Self::IgnoreError(e) => write!(f, "Error walking files: {e}"),
Self::QueryError(e) => {
write!(f, "Error occurred while creating a tree-sitter query: {e}")
}
}
}
}
impl From<ApplicationError> for ProgramError {
fn from(err: ApplicationError) -> Self {
Self::ApplicationError(err)
}
}
impl From<PathProcessingError> for ProgramError {
fn from(err: PathProcessingError) -> Self {
Self::PathProcessingError(err)
}
}
impl From<io::Error> for ProgramError {
fn from(err: io::Error) -> Self {
Self::IoError(err)
}
}
impl From<ignore::Error> for ProgramError {
fn from(err: ignore::Error) -> Self {
Self::IgnoreError(err)
}
}
impl From<TSQueryError> for ProgramError {
fn from(err: TSQueryError) -> Self {
Self::QueryError(err)
}
}
impl Error for ProgramError {}
/// Errors when applying actions to scoped views.
#[derive(Debug)]
enum ApplicationError {
/// Something was *unexpectedly* in scope.
SomeInScope,
/// Nothing was in scope, *unexpectedly*.
NoneInScope,
/// Error with an [`Action`].
ActionError(ActionError),
}
impl fmt::Display for ApplicationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::SomeInScope => write!(f, "Some input was in scope"),
Self::NoneInScope => write!(f, "No input was in scope"),
Self::ActionError(e) => write!(f, "Error in an action: {e}"),
}
}
}
impl From<ActionError> for ApplicationError {
fn from(err: ActionError) -> Self {
Self::ActionError(err)
}
}
impl Error for ApplicationError {}
/// Errors when processing a (file) path.
#[derive(Debug)]
enum PathProcessingError {
/// I/O error.
IoError(io::Error, Option<PathBuf>),
/// Item was not a file (directory, symlink, ...).
NotAFile,
/// Item is a file but is unsuitable for processing.
InvalidFile,
/// Error when applying.
ApplicationError(ApplicationError),
}
impl fmt::Display for PathProcessingError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::IoError(e, None) => write!(f, "I/O error: {e}"),
Self::IoError(e, Some(path)) => write!(f, "I/O error at path {}: {e}", path.display()),
Self::NotAFile => write!(f, "Item is not a file"),
Self::InvalidFile => write!(f, "Item is not a valid file"),
Self::ApplicationError(e) => write!(f, "Error applying: {e}"),
}
}
}
impl From<io::Error> for PathProcessingError {
fn from(err: io::Error) -> Self {
Self::IoError(err, None)
}
}
impl From<ApplicationError> for PathProcessingError {
fn from(err: ApplicationError) -> Self {
Self::ApplicationError(err)
}
}
impl Error for PathProcessingError {}
#[derive(Debug)]
enum ScoperBuildError {
RegexError(RegexError),
LiteralError(LiteralError),
}
impl From<LiteralError> for ScoperBuildError {
fn from(e: LiteralError) -> Self {
Self::LiteralError(e)
}
}
impl From<RegexError> for ScoperBuildError {
fn from(e: RegexError) -> Self {
Self::RegexError(e)
}
}
impl fmt::Display for ScoperBuildError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::RegexError(e) => write!(f, "Regex error: {e}"),
Self::LiteralError(e) => write!(f, "Literal error: {e}"),
}
}
}
impl Error for ScoperBuildError {}
fn get_general_scoper(options: &cli::GlobalOptions, scope: String) -> Result<Box<dyn Scoper>> {
Ok(if options.literal_string {
Box::new(Literal::try_from(scope).context("Failed building literal string")?)
} else {
Box::new(Regex::try_from(scope).context("Failed building regex")?)
})
}
fn assemble_common_actions(
composable_actions: &cli::ComposableActions,
standalone_actions: StandaloneAction,
) -> Result<Vec<Box<dyn Action>>> {
let mut actions: Vec<Box<dyn Action>> = Vec::new();
if let Some(replacement) = composable_actions.replace.clone() {
actions.push(Box::new(
Replacement::try_from(replacement).context("Failed building replacement string")?,
));
debug!("Loaded action: Replacement");
}
if matches!(standalone_actions, StandaloneAction::Delete) {
actions.push(Box::<Deletion>::default());
debug!("Loaded action: Deletion");
}
if composable_actions.upper {
actions.push(Box::<Upper>::default());
debug!("Loaded action: Upper");
}
if composable_actions.lower {
actions.push(Box::<Lower>::default());
debug!("Loaded action: Lower");
}
if composable_actions.titlecase {
actions.push(Box::<Titlecase>::default());
debug!("Loaded action: Titlecase");
}
if composable_actions.normalize {
actions.push(Box::<Normalization>::default());
debug!("Loaded action: Normalization");
}
Ok(actions)
}
/// To the default log level found in the environment, adds the requested additional
/// verbosity level, clamped to the maximum available.
///
/// See also
/// <https://docs.rs/env_logger/latest/env_logger/struct.Env.html#default-environment-variables>
/// and <https://docs.rs/env_logger/latest/env_logger/#enabling-logging>
fn level_filter_from_env_and_verbosity(additional_verbosity: u8) -> LevelFilter {