-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathmain.rs
More file actions
1253 lines (1172 loc) · 41.1 KB
/
main.rs
File metadata and controls
1253 lines (1172 loc) · 41.1 KB
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
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::borrow::Cow;
use std::cmp::max;
use std::cmp::min;
use std::collections::HashSet;
use std::env;
use std::fmt;
use std::fs;
use std::fs::read_to_string;
use std::iter;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use std::process::exit;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::mpsc::channel;
use std::thread;
use anyhow::Context;
use anyhow::Error;
use anyhow::ensure;
use clap::App;
use clap::Arg;
use clap::crate_version;
use diff::Result as DiffResult;
use grep::regex::RegexMatcher;
use grep::regex::RegexMatcherBuilder;
use grep::searcher::BinaryDetection;
use grep::searcher::Searcher;
use grep::searcher::SearcherBuilder;
use grep::searcher::Sink;
use grep::searcher::SinkMatch;
use ignore::WalkBuilder;
use ignore::WalkState;
use ignore::overrides::OverrideBuilder;
use regex::Regex;
use regex::RegexBuilder;
mod terminal;
use rprompt::prompt_reply_stderr;
use rprompt::prompt_reply_stdout;
use crate::terminal::print_bolded_diff_to_terminal;
type Result<T> = ::std::result::Result<T, Error>;
#[derive(Clone)]
enum FileSet {
Extensions(Vec<String>),
Glob {
matches: Vec<String>,
case_insensitive: bool,
},
}
fn get_file_set(matches: &clap::ArgMatches) -> Option<FileSet> {
if let Some(files) = matches.values_of_lossy("extensions") {
return Some(FileSet::Extensions(files));
}
if let Some(files) = matches.values_of_lossy("glob") {
return Some(FileSet::Glob {
matches: files,
case_insensitive: false,
});
}
if let Some(files) = matches.values_of_lossy("iglob") {
return Some(FileSet::Glob {
matches: files,
case_insensitive: true,
});
}
None
}
fn notify_fast_mode() {
eprintln!("Fast mode activated. Sit back, relax, and enjoy the brief flight.");
}
fn run_editor(path: &Path, start_line: usize) -> Result<()> {
let editor = env::var("EDITOR").unwrap_or_else(|_| String::from("vim"));
let args: Vec<&str> = editor.split(' ').collect();
let mut editor_cmd = {
let mut cmd = Command::new(args[0])
.args(&args[1..])
.arg(format!("+{}", start_line))
.arg(path)
.spawn()
.with_context(|| format!("Unable to launch editor {} on path {:?}", editor, path));
if cfg!(target_os = "windows") && cmd.is_err() {
// Windows-only fallback to notepad.exe.
cmd = Command::new("notepad.exe")
.arg(path)
.spawn()
.with_context(|| format!("Unable to launch editor notepad.exe on path {:?}", path));
}
cmd?
};
editor_cmd
.wait()
.context("Error waiting for editor to exit")?;
Ok(())
}
fn looks_like_code(path: &Path) -> bool {
let s = path.to_string_lossy();
!s.ends_with('~') && !s.ends_with("tags") && !s.ends_with("TAGS")
}
fn prompt(prompt_text: &str, letters: &str, default: Option<char>) -> Result<char> {
loop {
let input = prompt_reply_stdout(prompt_text).context("Unable to read user input")?;
if input.is_empty() && default.is_some() {
return Ok(default.unwrap());
}
if input.len() == 1 && letters.contains(&input) {
return Ok(input.chars().next().unwrap());
}
println!("Come again?")
}
}
fn walk_builder_with_file_set(dirs: Vec<&str>, file_set: Option<FileSet>) -> Result<WalkBuilder> {
ensure!(!dirs.is_empty(), "must provide at least one path to walk!");
let mut builder = WalkBuilder::new(dirs[0]);
for dir in &dirs[1..] {
builder.add(dir);
}
if let Some(file_set) = file_set {
use crate::FileSet::*;
match file_set {
Extensions(e) => {
let mut override_builder = OverrideBuilder::new(".");
for ext in e {
override_builder
.add(&format!("*.{}", ext))
.context("Unable to register extension with directory walker")?;
}
builder.overrides(
override_builder
.build()
.context("Unable to register extensions with directory walker")?,
);
}
Glob {
matches,
case_insensitive,
} => {
let mut override_builder = OverrideBuilder::new(".");
// Case sensitivity needs to be added before the patterns are.
if case_insensitive {
override_builder
.case_insensitive(true)
.context("Unable to toggle case sensitivity")?;
}
for file in matches {
override_builder
.add(&file)
.context("Unable to register glob with directory walker")?;
}
builder.overrides(
override_builder
.build()
.context("Unable to register glob with directory walker")?,
);
}
}
}
Ok(builder)
}
/// Convert a 0-based character offset to 0-based line number and column.
fn index_to_row_col(s: &str, index: usize) -> (usize, usize) {
let chunk = &s[..index];
let line_num = chunk.chars().filter(|x| x == &'\n').count();
let last_newline = if let Some(result) = chunk.rfind('\n') {
result as isize
} else {
-1
};
let col = index as isize - last_newline - 1;
(line_num, col as usize)
}
fn display_warning(error: &Error) -> DisplayWarning {
DisplayWarning { inner: error }
}
fn make_searcher() -> Searcher {
SearcherBuilder::new()
.line_number(false)
.multi_line(true)
.binary_detection(BinaryDetection::quit(b'\x00'))
.bom_sniffing(false)
.build()
}
fn file_contents_if_matches(
searcher: &mut Searcher,
matcher: &RegexMatcher,
path: &Path,
) -> Option<String> {
let mut sink = FastmodSink::new();
if let Err(e) = searcher.search_path(&matcher, path, &mut sink) {
eprintln!("{}", display_warning(&e.into()));
};
if sink.did_match {
match read_to_string(&path) {
Ok(c) => Some(c),
Err(e) => {
eprintln!("{}", display_warning(&e.into()));
None
}
}
} else {
None
}
}
#[derive(Debug)]
struct DisplayWarning<'a> {
inner: &'a Error,
}
impl<'a> fmt::Display for DisplayWarning<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
writeln!(fmt, "Warning: {:?}", self.inner)?;
Ok(())
}
}
struct FastmodSink {
did_match: bool,
}
impl FastmodSink {
fn new() -> Self {
Self { did_match: false }
}
}
struct Fastmod {
yes_to_all: bool,
hidden: bool,
no_ignore: bool,
changed_files: Option<Vec<PathBuf>>,
}
impl Sink for FastmodSink {
type Error = std::io::Error;
fn matched(
&mut self,
_searcher: &Searcher,
_mat: &SinkMatch,
) -> std::result::Result<bool, std::io::Error> {
self.did_match = true;
Ok(false)
}
}
fn to_char_boundary(s: &str, mut index: usize) -> usize {
while index < s.len() && !s.is_char_boundary(index) {
index += 1;
}
debug_assert!(
index > s.len() || s.is_char_boundary(index),
"index: {}, len: {}",
index,
s.len()
);
index
}
fn backward_to_char_boundary(s: &str, mut index: usize) -> usize {
while !s.is_char_boundary(index) {
index -= 1;
}
index
}
impl Fastmod {
fn new(accept_all: bool, hidden: bool, no_ignore: bool, print_changed_files: bool) -> Fastmod {
Fastmod {
yes_to_all: accept_all,
hidden,
no_ignore,
changed_files: if print_changed_files {
Some(Vec::new())
} else {
None
},
}
}
fn save(&mut self, path: &Path, text: &str) -> Result<()> {
fs::write(path, text).with_context(|| format!("Unable to write to {:?}", path))?;
self.record_change(path.to_owned());
Ok(())
}
fn record_change(&mut self, path: PathBuf) {
if let Some(ref mut changed_files) = self.changed_files {
changed_files.push(path);
}
}
fn print_changed_files_if_needed(&mut self) {
if let Some(ref mut changed_files) = self.changed_files {
changed_files.sort();
for file in changed_files {
println!("{}", file.display());
}
}
}
// Returns true if the file was changed, false otherwise.
fn fast_patch(
&mut self,
regex: &Regex,
subst: &str,
path: &Path,
contents: &str,
) -> Result<bool> {
let new_contents = regex.replace_all(contents, subst);
match new_contents {
Cow::Borrowed(_) => Ok(false),
Cow::Owned(_) => {
self.save(path, &new_contents)?;
Ok(true)
}
}
}
fn present_and_apply_patches(
&mut self,
regex: &Regex,
subst: &str,
path: &Path,
mut contents: String,
) -> Result<()> {
// Overall flow:
// 0) offset = 0.
// 1) Find next patch from *current* contents of the file at
// given offset. If none, we are done.
// 2) Set the offset to the start of the previous patch + 1.
// 3) Ask the user to make a modification to the file.
// 4) Re-read the file. (User may have made arbitrary edits!)
let mut offset = 0;
while offset < contents.len() {
{
let mat = regex.find(&contents[offset..]);
match mat {
None => break,
Some(mat) => {
let mut new_contents = contents[..offset].to_string();
let new_trailing_contents = regex.replace(&contents[offset..], subst);
new_contents.push_str(&new_trailing_contents);
// Zero-length matches can happen with any
// regex that matches the empty string,
// such as `a?` or the empty regex.
let is_zero_length_match = mat.end() == mat.start();
let (start_line, _) = index_to_row_col(&contents, mat.start() + offset);
let (end_line, _) = index_to_row_col(
&contents,
// Avoid generating index of -1 when start
// == end == offset = 0 for a zero-length
// match.
backward_to_char_boundary(
&contents,
mat.end() + offset - if is_zero_length_match { 0 } else { 1 },
),
);
let accepted = self.ask_about_patch(
path,
&contents,
start_line + 1,
end_line + 1,
&new_contents,
)?;
if accepted {
offset = to_char_boundary(
&contents,
offset
+ mat.start()
+ subst.len()
// Ensure forward progress when there
// is a zero-length match.
+ if is_zero_length_match { 1 } else { 0 },
);
} else {
// Advance to the next character after the match.
offset = to_char_boundary(&contents, offset + mat.end() + 1);
}
}
}
}
// re-open file in case contents changed.
contents = read_to_string(path)?;
}
Ok(())
}
/// Returns true if the patch was accepted, false otherwise.
fn ask_about_patch<'a>(
&mut self,
path: &Path,
old: &'a str,
start_line: usize,
end_line: usize,
new: &'a str,
) -> Result<bool> {
terminal::clear();
let diffs = self.diffs_to_print(old, new);
if diffs.is_empty() {
return Ok(false);
}
if start_line == end_line {
println!("{}:{}", path.to_string_lossy(), start_line);
} else {
println!("{}:{}-{}", path.to_string_lossy(), start_line, end_line);
}
self.print_diff(&diffs);
let mut user_input = if self.yes_to_all {
'y'
} else {
prompt(
"Accept change (y = yes [default], \
n = no, e = edit, A = yes to all, E = yes+edit, q = quit)?\n",
"yneAEq",
Some('y'),
)?
};
if user_input == 'A' {
self.yes_to_all = true;
user_input = 'y';
}
match user_input {
'y' => {
self.save(path, new)?;
Ok(true)
}
'E' => {
self.save(path, new)?;
run_editor(path, start_line)?;
Ok(true)
}
'e' => {
self.record_change(path.to_owned());
run_editor(path, start_line)?;
Ok(true)
}
'q' => exit(0),
'n' => Ok(false),
_ => unreachable!(),
}
}
fn diffs_to_print<'a>(&self, orig: &'a str, edit: &'a str) -> Vec<DiffResult<&'a str>> {
let mut diffs = diff::lines(orig, edit);
fn is_same(x: &DiffResult<&str>) -> bool {
match x {
DiffResult::Both(..) => true,
_ => false,
}
}
let lines_to_print = match terminal::size() {
Some((_w, h)) => h,
None => 25,
} - 20;
let num_prefix_lines = diffs.iter().take_while(|diff| is_same(diff)).count();
let num_suffix_lines = diffs.iter().rev().take_while(|diff| is_same(diff)).count();
// If the prefix is the length of the diff then the file matched <regex>
// but applying <subst> didn't result in any changes, there are no diffs
// to print so we return an empty Vec.
if diffs.len() == num_prefix_lines {
return vec![];
}
let size_of_diff = diffs.len() - num_prefix_lines - num_suffix_lines;
let size_of_context = lines_to_print.saturating_sub(size_of_diff);
let size_of_up_context = size_of_context / 2;
let size_of_down_context = size_of_context / 2 + size_of_context % 2;
let start_offset = num_prefix_lines.saturating_sub(size_of_up_context);
let end_offset = min(
diffs.len(),
num_prefix_lines + size_of_diff + size_of_down_context,
);
diffs.truncate(end_offset);
diffs.splice(..start_offset, iter::empty());
assert!(
diffs.len() <= max(lines_to_print, size_of_diff),
"changeset too long: {} > max({}, {})",
diffs.len(),
lines_to_print,
size_of_diff
);
diffs
}
fn print_diff<'a>(&mut self, diffs: &[DiffResult<&'a str>]) {
for window in diffs.windows(2) {
match window {
[DiffResult::Left(l), DiffResult::Right(r)] => {
let _ = print_bolded_diff_to_terminal(l, r);
},
[DiffResult::Both(l, _), _] => println!(" {}", l),
_ => (),
}
}
}
fn run_interactive(
&mut self,
regex: &Regex,
matcher: &RegexMatcher,
subst: &str,
dirs: Vec<&str>,
file_set: Option<FileSet>,
) -> Result<()> {
let walk = walk_builder_with_file_set(dirs.clone(), file_set.clone())?
.hidden(!self.hidden)
.parents(!self.no_ignore)
.ignore(!self.no_ignore)
.git_ignore(!self.no_ignore)
.git_global(!self.no_ignore)
.git_exclude(!self.no_ignore)
.threads(min(12, num_cpus::get()))
.build_parallel();
let (tx, rx) = channel();
let thread_matcher = matcher.clone();
thread::spawn(|| {
walk.run(move || {
let mut searcher = make_searcher();
let tx = tx.clone();
let matcher = thread_matcher.clone();
Box::new(move |result| {
let dirent = match result {
Ok(d) => d,
Err(e) => {
eprintln!("Warning: {}", &e);
return WalkState::Continue;
}
};
if let Some(file_type) = dirent.file_type() {
if !file_type.is_file() {
return WalkState::Continue;
}
let path = dirent.path();
if !looks_like_code(path) {
return WalkState::Continue;
}
if let Some(contents) =
file_contents_if_matches(&mut searcher, &matcher, path)
{
if tx.send((path.to_path_buf(), contents)).is_err() {
return WalkState::Quit;
}
}
}
WalkState::Continue
})
})
});
// We have to keep track of which paths we've visited so that
// if the user presses A to accept all changes and we kick
// over into run_fast(), we don't apply the regex to files the
// user has already addressed interactively. (The user may
// have made manual edits or declined to replace some files.)
// Since the user is doing this interactively and we don't
// support bookmarks, this set presumably isn't going to grow so large
// that the memory usage becomes a concern.
let mut visited = HashSet::default();
while let Ok((path, contents)) = rx.recv() {
visited.insert(path.clone());
self.present_and_apply_patches(®ex, subst, &path, contents)?;
if self.yes_to_all {
// Kick over into fast mode. We restart the
// search, but we have our visited set so that
// we won't apply changes to files the user
// has already addressed.
terminal::clear();
notify_fast_mode();
return Fastmod::run_fast_impl(
®ex,
&matcher,
subst,
dirs,
file_set,
self.hidden,
self.no_ignore,
self.changed_files.clone(),
Some(visited),
);
}
}
self.print_changed_files_if_needed();
Ok(())
}
fn run_fast(
regex: &Regex,
matcher: &RegexMatcher,
subst: &str,
dirs: Vec<&str>,
file_set: Option<FileSet>,
hidden: bool,
no_ignore: bool,
print_changed_files: bool,
) -> Result<()> {
Fastmod::run_fast_impl(
regex,
matcher,
subst,
dirs,
file_set,
hidden,
no_ignore,
if print_changed_files {
Some(Vec::new())
} else {
None
},
None,
)
}
fn run_fast_impl(
regex: &Regex,
matcher: &RegexMatcher,
subst: &str,
dirs: Vec<&str>,
file_set: Option<FileSet>,
hidden: bool,
no_ignore: bool,
changed_files: Option<Vec<PathBuf>>,
visited: Option<HashSet<PathBuf>>,
) -> Result<()> {
let walk = walk_builder_with_file_set(dirs, file_set)?
.hidden(!hidden)
.parents(!no_ignore)
.ignore(!no_ignore)
.git_ignore(!no_ignore)
.git_global(!no_ignore)
.git_exclude(!no_ignore)
.threads(min(12, num_cpus::get()))
.build_parallel();
let matcher = matcher.clone();
let visited = Arc::new(visited);
let should_record_changed_files = changed_files.is_some();
let changed_files = Arc::new(Mutex::new(changed_files.unwrap_or_else(Vec::new)));
let changed_files_inner = changed_files.clone();
walk.run(move || {
// We have to do our own changed file tracking, so don't
// enable it in our Fastmod instance.
let mut fm = Fastmod::new(true, hidden, no_ignore, false);
let regex = regex.clone();
let matcher = matcher.clone();
let subst = subst.to_string();
let visited = visited.clone();
let changed_files = changed_files_inner.clone();
let mut searcher = make_searcher();
Box::new(move |result| {
let dirent = match result {
Ok(d) => d,
Err(e) => {
eprintln!("Warning: {}", &e);
return WalkState::Continue;
}
};
if let Some(file_type) = dirent.file_type() {
if !file_type.is_file() {
return WalkState::Continue;
}
let path = dirent.path();
if let Some(ref visited) = *visited {
if visited.contains(path) {
return WalkState::Continue;
}
}
if !looks_like_code(path) {
return WalkState::Continue;
}
if let Some(contents) = file_contents_if_matches(&mut searcher, &matcher, path)
{
let patching_result = fm.fast_patch(®ex, &subst, path, &contents);
match patching_result {
Ok(changed_file) => {
if should_record_changed_files && changed_file {
let mut changed_files = changed_files.lock().unwrap();
changed_files.push(path.to_owned())
}
}
Err(error) => eprintln!("{}", display_warning(&error)),
}
}
}
WalkState::Continue
})
});
if should_record_changed_files {
let mut changed_files = changed_files.lock().unwrap();
(*changed_files).sort();
for file in &*changed_files {
println!("{}", file.display());
}
}
Ok(())
}
}
fn fastmod() -> Result<()> {
let matches = App::new("fastmod")
.about("fastmod is a fast partial replacement for codemod.")
.version(crate_version!())
.long_about(
"fastmod is a tool to assist you with large-scale codebase refactors
that can be partially automated but still require human oversight and occasional
intervention.
Example: Let's say you're deprecating your use of the <font> tag. From the
command line, you might make progress by running:
fastmod -m -d www --extensions php,html \\
'<font *color=\"?(.*?)\"?>(.*?)</font>' \\
'<span style=\"color: ${1};\">${2}</span>'
For each match of the regex, you'll be shown a colored diff and asked if you
want to accept the change, reject it, or edit the line in question in your
$EDITOR of choice.
NOTE: Whereas codemod uses Python regexes, fastmod uses the Rust regex
crate, which supports a slightly different regex syntax and does not
support look around or backreferences. In particular, use ${1} instead
of \\1 to get the contents of the first capture group, and use $$ to
write a literal $ in the replacement string. See
https://docs.rs/regex#syntax for details.
A consequence of this syntax is that the use of single quotes instead
of double quotes around the replacment text is important, because the
bash shell itself cares about the $ character in double-quoted
strings. If you must double-quote your input text, be careful to
escape $ characters properly!",
)
.arg(
Arg::with_name("multiline")
.short("m")
.long("multiline")
.help("Have regex work over multiple lines (i.e., have dot match newlines)."),
)
.arg(
Arg::with_name("dir")
.short("d")
.long("dir")
.value_name("DIR")
.help("The path whose descendent files are to be explored.")
.long_help(
"The path whose descendent files are to be explored.
Included as a flag instead of a positional argument for
compatibility with the original codemod.",
)
.multiple(true)
.number_of_values(1),
)
.arg(
Arg::with_name("file_or_dir")
.value_name("FILE OR DIR")
.help("Paths whose descendent files are to be explored.")
.multiple(true)
.index(3),
)
.arg(
Arg::with_name("ignore_case")
.short("i")
.long("ignore-case")
.help("Perform case-insensitive search."),
)
.arg(
Arg::with_name("extensions")
.short("e")
.long("extensions")
.value_name("EXTENSION")
.multiple(true)
.require_delimiter(true)
.conflicts_with_all(&["glob", "iglob"])
// TODO: support Unix pattern-matching of extensions?
.help("A comma-delimited list of file extensions to process."),
)
.arg(
Arg::with_name("glob")
.short("g")
.long("glob")
.value_name("GLOB")
.multiple(true)
.conflicts_with("iglob")
.help("A space-delimited list of globs to process.")
)
.arg(
Arg::with_name("hidden")
.long("hidden")
.help("Search hidden files.")
)
.arg(
Arg::with_name("no_ignore")
.short("u")
.long("no-ignore")
.help("Also search ignored files.")
)
.arg(
Arg::with_name("iglob")
.long("iglob")
.value_name("IGLOB")
.multiple(true)
.help("A space-delimited list of case-insensitive globs to process.")
)
.arg(
Arg::with_name("accept_all")
.long("accept-all")
.help("Automatically accept all changes (use with caution)."),
)
.arg(
Arg::with_name("print_changed_files")
.long("print-changed-files")
.help("Print the paths of changed files. (Recommended to be combined with --accept-all.)"),
)
.arg(
Arg::with_name("fixed_strings")
.long("fixed-strings")
.short("F")
.help("Treat REGEX as a literal string. Avoids the need to escape regex metacharacters (compare to ripgrep's option of the same name).")
)
.arg(
Arg::with_name("match")
.value_name("REGEX")
.help("Regular expression to match.")
.required(true)
.index(1),
)
.arg(
Arg::with_name("subst")
// TODO: support empty substitution to mean "open my
// editor at instances of this regex"?
.required(true)
.help("Substitution to replace with.")
.index(2),
)
.get_matches();
let multiline = matches.is_present("multiline");
let dirs = {
let mut dirs: Vec<_> = matches
.values_of("dir")
.unwrap_or_default()
.chain(matches.values_of("file_or_dir").unwrap_or_default())
.collect();
if dirs.is_empty() {
dirs.push(".");
}
dirs
};
let ignore_case = matches.is_present("ignore_case");
let file_set = get_file_set(&matches);
let accept_all = matches.is_present("accept_all");
let hidden = matches.is_present("hidden");
let no_ignore = matches.is_present("no_ignore");
let print_changed_files = matches.is_present("print_changed_files");
let regex_str = matches.value_of("match").expect("match is required!");
let subst = matches.value_of("subst").expect("subst is required!");
let (maybe_escaped_regex, subst) = if matches.is_present("fixed_strings") {
(regex::escape(regex_str), subst.replace("$", "$$"))
} else {
(regex_str.to_string(), subst.to_string())
};
let regex = RegexBuilder::new(&maybe_escaped_regex)
.case_insensitive(ignore_case)
.multi_line(true) // match codemod behavior for ^ and $.
.dot_matches_new_line(multiline)
.build()
.with_context(|| format!("Unable to make regex from {}", regex_str))?;
if regex.is_match("") {
let _ = prompt_reply_stderr(&format!(
"Warning: your regex {:?} matches the empty string. This is probably
not what you want. Press Enter to continue anyway or Ctrl-C to quit.",
regex,
))?;
}
let matcher = RegexMatcherBuilder::new()
.case_insensitive(ignore_case)
.multi_line(true)
.dot_matches_new_line(multiline)
.build(&maybe_escaped_regex)?;
if accept_all {
Fastmod::run_fast(
®ex,
&matcher,
&subst,
dirs,
file_set,
hidden,
no_ignore,
print_changed_files,
)
} else {
Fastmod::new(accept_all, hidden, no_ignore, print_changed_files)
.run_interactive(®ex, &matcher, &subst, dirs, file_set)
}
}
fn main() {
if let Err(e) = fastmod() {
eprint!("{:?}", e);
}
}
#[cfg(test)]
mod tests {
use std::fs::File;
use std::io::Write;
use assert_cmd::Command;
use tempfile::TempDir;
use super::*;
#[test]
fn test_index_to_row_col() {
assert_eq!(index_to_row_col("abc", 1), (0, 1));
assert_eq!(index_to_row_col("abc\ndef", 2), (0, 2));
assert_eq!(index_to_row_col("abc\ndef", 3), (0, 3));
assert_eq!(index_to_row_col("abc\ndef", 4), (1, 0));
assert_eq!(index_to_row_col("abc\ndef\nghi", 8), (2, 0));
}
fn create_test_files<'a>(
names_and_contents: impl IntoIterator<Item = &'a (&'a str, &'a str)>,
) -> TempDir {
let dir = TempDir::with_prefix("fastmodtest.").unwrap();
for (name, contents) in names_and_contents {
let path = dir.path().join(name);
let mut file = File::create(path.clone()).unwrap();
file.write_all(contents.as_bytes()).unwrap();
file.sync_all().unwrap();
}
dir
}
#[test]
fn test_simple_replace_all() {
let dir = create_test_files(&[("file1.c", "foo\nfoo blah foo")]);
Command::cargo_bin("fastmod")
.unwrap()
.args(&[
"foo",
"bar",
"--accept-all",
"--dir",
dir.path().to_str().unwrap(),
])
.assert()
.success();
let contents = read_to_string(dir.path().join("file1.c")).unwrap();
assert_eq!(contents, "bar\nbar blah bar");
}
#[test]
fn test_glob_matches() {
let dir = create_test_files(&[
("f1.txt", "some awesome text"),
("f2.TXT", "some more awesome text"),
("skip.rs", "i should be skipped but i am still awesome"),
]);
Command::cargo_bin("fastmod")
.unwrap()
.args(&[