-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.rs
1430 lines (1283 loc) · 52.1 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::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::{Color, Colorize, Styles};
use ignore::{WalkBuilder, WalkState};
use itertools::Itertools;
use log::{debug, error, info, trace, 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::scoping::langs::csharp::{CSharp, CSharpQuery};
use srgn::scoping::langs::go::{Go, GoQuery};
use srgn::scoping::langs::hcl::{Hcl, HclQuery};
use srgn::scoping::langs::python::{Python, PythonQuery};
use srgn::scoping::langs::rust::{Rust, RustQuery};
use srgn::scoping::langs::typescript::{TypeScript, TypeScriptQuery};
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;
#[allow(clippy::too_many_lines)] // Only slightly above.
fn main() -> Result<()> {
let mut args = cli::Cli::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();
if let Some(shell) = args.shell {
debug!("Generating completions file for {shell:?}.");
cli::print_completions(shell, &mut cli::Cli::command());
debug!("Done generating completions file, exiting.");
return Ok(());
}
info!("Launching app with args: {:?}", args);
debug!("Assembling scopers.");
let general_scoper = get_general_scoper(&args)?;
// 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 = Arc::new(get_language_scopers(&args));
debug!("Done assembling scopers.");
debug!("Assembling actions.");
let mut actions = assemble_actions(&args)?;
debug!("Done assembling 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 (
args.options.stdin_override_to.unwrap_or(is_readable_stdin),
args.options.glob.clone(),
&language_scopers.is_empty(),
) {
// stdin considered viable: always use it.
(true, None, _)
// Nothing explicitly available: this should open an interactive stdin prompt.
| (false, None, true) => 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, false) => {
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_empty();
if search_mode {
info!("Will use search mode."); // Modelled after ripgrep!
let style = Style {
fg: Some(Color::Red),
styles: vec![Styles::Bold],
..Default::default()
};
actions.push(Box::new(style));
args.options.only_matching = true;
args.options.line_numbers = true;
args.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."
);
}
// Now write out
match (input, args.options.sorted) {
(Input::Stdin, _ /* no effect */) => {
info!("Will read from stdin and write to stdout, applying actions.");
handle_actions_on_stdin(&general_scoper, &language_scopers, &actions, &args)?;
}
(Input::WalkOn(validator), false) => {
info!("Will walk file tree, applying actions.");
handle_actions_on_many_files_threaded(
&validator,
&general_scoper,
&language_scopers,
&actions,
&args,
search_mode,
args.options.threads.map_or(
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(
&validator,
&general_scoper,
&language_scopers,
&actions,
&args,
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),
}
/// Main entrypoint for simple `stdin` -> `stdout` processing.
#[allow(clippy::borrowed_box)] // Used throughout, not much of a pain
fn handle_actions_on_stdin(
general_scoper: &Box<dyn Scoper>,
language_scopers: &[Box<dyn LanguageScoper>],
actions: &[Box<dyn Action>],
args: &cli::Cli,
) -> 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::new();
apply(
&source,
&mut destination,
general_scoper,
language_scopers,
actions,
args,
)?;
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(
validator: &Validator,
general_scoper: &Box<dyn Scoper>,
language_scopers: &[Box<dyn LanguageScoper>],
actions: &[Box<dyn Action>],
args: &cli::Cli,
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(!args.options.hidden)
.git_ignore(!args.options.gitignored)
.sort_by_file_path(Ord::cmp)
.build()
{
match entry {
Ok(entry) => {
let path = entry.path();
let res = process_path(
path,
&root,
validator,
general_scoper,
language_scopers,
actions,
args,
search_mode,
);
n_files_seen += match res {
Err(PathProcessingError::NotAFile | PathProcessingError::InvalidFile) => 0,
_ => 1,
};
n_files_processed += match res {
Ok(()) => 1,
Err(PathProcessingError::NotAFile | PathProcessingError::InvalidFile) => 0,
Err(PathProcessingError::ApplicationError(ApplicationError::SomeInScope))
if args.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(
e @ (PathProcessingError::ApplicationError(ApplicationError::ActionError(
..,
))
| PathProcessingError::IoError(..)),
) => {
// Hard errors we should do something about.
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 && args.options.fail_no_files {
Err(ProgramError::NoFilesFound)
} else if n_files_processed == 0 && args.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
fn handle_actions_on_many_files_threaded(
validator: &Validator,
general_scoper: &Box<dyn Scoper>,
language_scopers: &[Box<dyn LanguageScoper>],
actions: &[Box<dyn Action>],
args: &cli::Cli,
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(!args.options.hidden)
.git_ignore(!args.options.gitignored)
.build_parallel()
.run(|| {
Box::new(|entry| match entry {
Ok(entry) => {
let path = entry.path();
let res = process_path(
path,
&root,
validator,
general_scoper,
language_scopers,
actions,
args,
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
}
Err(PathProcessingError::NotAFile | PathProcessingError::InvalidFile) => {
WalkState::Continue
}
Err(
e
@ PathProcessingError::ApplicationError(ApplicationError::SomeInScope),
) if args.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(
e @ (PathProcessingError::ApplicationError(..)
| PathProcessingError::IoError(..)),
) => {
// Hard errors we should do something about.
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
}
}
})
});
if let Some(e) = err.lock().unwrap().take() {
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 && args.options.fail_no_files {
Err(ProgramError::NoFilesFound)
} else if n_files_processed == 0 && args.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(
path: &Path,
root: &Path,
validator: &Validator,
general_scoper: &Box<dyn Scoper>,
language_scopers: &[Box<dyn LanguageScoper>],
actions: &[Box<dyn Action>],
args: &cli::Cli,
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 destination =
String::with_capacity(filesize.try_into().unwrap_or(/* no perf gains for you */ 0));
let mut source = String::new();
file.read_to_string(&mut source)?;
let changed = apply(
&source,
&mut destination,
general_scoper,
language_scopers,
actions,
args,
)?;
(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 {
writeln!(stdout, "{}", path.display())?;
debug!("Got new file contents, writing to file: {:?}", path);
let mut file = tempfile::Builder::new()
.prefix(env!("CARGO_PKG_NAME"))
.tempfile()?;
trace!("Writing to temporary file: {:?}", file.path());
file.write_all(new_contents.as_bytes())?;
// Atomically replace so SIGINT etc. do not leave dangling crap.
file.persist(&path)?;
} 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(
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>],
actions: &[Box<dyn Action>],
args: &cli::Cli,
) -> std::result::Result<bool, ApplicationError> {
debug!("Building view.");
let mut builder = ScopedViewBuilder::new(source);
if args.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 args.options.fail_none && !view.has_any_in_scope() {
return Err(ApplicationError::NoneInScope);
}
if args.options.fail_any && view.has_any_in_scope() {
return Err(ApplicationError::SomeInScope);
};
debug!("Applying actions to view.");
if args.standalone_actions.squeeze {
view.squeeze();
}
for action in actions {
view.map_with_context(action)?;
}
debug!("Writing to destination.");
let line_based = args.options.only_matching || args.options.line_numbers;
if line_based {
for (i, line) in view.lines().into_iter().enumerate() {
let i = i + 1;
if !args.options.only_matching || line.has_any_in_scope() {
if args.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 {
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),
}
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}"),
}
}
}
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 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 From<tempfile::PersistError> for PathProcessingError {
fn from(err: tempfile::PersistError) -> Self {
Self::IoError(err.error, Some(err.file.path().to_owned()))
}
}
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 {}
#[allow(clippy::cognitive_complexity)] // 🤷♀️ macros
fn get_language_scopers(args: &cli::Cli) -> Vec<Box<dyn LanguageScoper>> {
// We have `LanguageScoper: Scoper`, but we cannot upcast
// (https://github.com/rust-lang/rust/issues/65991), so hack around the limitation
// by providing both.
let mut scopers: Vec<Box<dyn LanguageScoper>> = Vec::new();
macro_rules! handle_language_scope {
($lang:ident, $lang_query:ident, $query_type:ident, $lang_type:ident) => {
if let Some(lang_scope) = &args.languages_scopes.$lang {
if !scopers.is_empty() {
let mut cmd = cli::Cli::command();
cmd.error(
clap::error::ErrorKind::ArgumentConflict,
"Can only use one language at a time.",
)
.exit();
}
assert!(scopers.is_empty());
for query in &lang_scope.$lang {
let query = $query_type::Prepared(query.clone());
scopers.push(Box::new($lang_type::new(query.clone())));
}
for query in &lang_scope.$lang_query {
let query = $query_type::Custom(query.clone());
scopers.push(Box::new($lang_type::new(query.clone())));
}
assert!(!scopers.is_empty(), "Language specified, but no scope."); // Internal bug
};
};
}
handle_language_scope!(csharp, csharp_query, CSharpQuery, CSharp);
handle_language_scope!(hcl, hcl_query, HclQuery, Hcl);
handle_language_scope!(go, go_query, GoQuery, Go);
handle_language_scope!(python, python_query, PythonQuery, Python);
handle_language_scope!(rust, rust_query, RustQuery, Rust);
handle_language_scope!(typescript, typescript_query, TypeScriptQuery, TypeScript);
scopers
}
fn get_general_scoper(args: &cli::Cli) -> Result<Box<dyn Scoper>> {
Ok(if args.options.literal_string {
Box::new(Literal::try_from(args.scope.clone()).context("Failed building literal string")?)
} else {
Box::new(Regex::try_from(args.scope.clone()).context("Failed building regex")?)
})
}
fn assemble_actions(args: &cli::Cli) -> Result<Vec<Box<dyn Action>>> {
let mut actions: Vec<Box<dyn Action>> = Vec::new();
if let Some(replacement) = args.composable_actions.replace.clone() {
actions.push(Box::new(
Replacement::try_from(replacement).context("Failed building replacement string")?,
));
debug!("Loaded action: Replacement");
}
#[cfg(feature = "german")]
if args.composable_actions.german {
actions.push(Box::new(German::new(
// Smell? Bug if bools swapped.
args.german_options.german_prefer_original,
args.german_options.german_naive,
)));
debug!("Loaded action: German");
}
#[cfg(feature = "symbols")]
if args.composable_actions.symbols {
if args.options.invert {
actions.push(Box::<SymbolsInversion>::default());
debug!("Loaded action: SymbolsInversion");
} else {
actions.push(Box::<Symbols>::default());
debug!("Loaded action: Symbols");
}
}
if args.standalone_actions.delete {
actions.push(Box::<Deletion>::default());
debug!("Loaded action: Deletion");
}
if args.composable_actions.upper {
actions.push(Box::<Upper>::default());
debug!("Loaded action: Upper");
}
if args.composable_actions.lower {
actions.push(Box::<Lower>::default());
debug!("Loaded action: Lower");
}
if args.composable_actions.titlecase {
actions.push(Box::<Titlecase>::default());
debug!("Loaded action: Titlecase");
}
if args.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 {
let available = LevelFilter::iter().collect::<Vec<_>>();
let default = env_logger::Builder::from_default_env().build().filter();
let mut level = default as usize; // Implementation detail of `log` crate
level += additional_verbosity as usize;
available.get(level).copied().unwrap_or_else(|| {
eprintln!("Requested additional verbosity on top of env default exceeds maximum, will use maximum");
available
.last()
.copied()
.expect("At least one level must be available")
})
}
mod cli {
use std::num::NonZero;
use clap::builder::ArgPredicate;
use clap::{ArgAction, Command, CommandFactory, Parser};
use clap_complete::{generate, Generator, Shell};
use srgn::scoping::langs::csharp::{CustomCSharpQuery, PreparedCSharpQuery};
use srgn::scoping::langs::go::{CustomGoQuery, PreparedGoQuery};
use srgn::scoping::langs::hcl::{CustomHclQuery, PreparedHclQuery};
use srgn::scoping::langs::python::{CustomPythonQuery, PreparedPythonQuery};
use srgn::scoping::langs::rust::{CustomRustQuery, PreparedRustQuery};
use srgn::scoping::langs::typescript::{CustomTypeScriptQuery, PreparedTypeScriptQuery};
use srgn::GLOBAL_SCOPE;
/// Main CLI entrypoint.
///
/// Using `verbatim_doc_comment` a lot as otherwise lines wouldn't wrap neatly. I
/// format them narrowly manually anyway, so can just use them verbatim.
#[derive(Parser, Debug)]
#[command(
author,
version,
about,
long_about = None,
// Really dumb to hard-code, but we need deterministic output for README tests
// to remain stable, and this is probably both a solid default *and* plays with
// this very source file which is wrapped at *below* that, so it fits and clap
// doesn't touch our manually formatted doc strings anymore.
term_width = 90,
)]
pub struct Cli {
/// Scope to apply to, as a regular expression pattern.
///
/// If string literal mode is requested, will be interpreted as a literal
/// string.
///
/// Actions will apply their transformations within this scope only.
///
/// The default is the global scope, matching the entire input. Where that
/// default is meaningless or dangerous (e.g., deletion), this argument is
/// required.
#[arg(
value_name = "SCOPE",
default_value = GLOBAL_SCOPE,
verbatim_doc_comment,
default_value_if("literal_string", ArgPredicate::IsPresent, None)
)]
pub scope: String,
/// Print shell completions for the given shell.
#[arg(long = "completions", value_enum, verbatim_doc_comment)]
// This thing needs to live up here to show up within `Options` next to `--help`
// and `--version`. Further down, it'd show up in the wrong section because we
// alter `next_help_heading`.
pub shell: Option<Shell>,
#[command(flatten)]
pub composable_actions: ComposableActions,
#[command(flatten)]
pub standalone_actions: StandaloneActions,
#[command(flatten)]
pub options: GlobalOptions,
#[command(flatten)]
pub languages_scopes: LanguageScopes,
#[cfg(feature = "german")]
#[command(flatten)]