1
+ use regex:: Regex ;
1
2
use similar:: TextDiff ;
2
3
use std:: path:: Path ;
3
4
@@ -14,12 +15,19 @@ pub struct Diff {
14
15
expected_name : Option < String > ,
15
16
actual : Option < String > ,
16
17
actual_name : Option < String > ,
18
+ normalizers : Vec < ( String , String ) > ,
17
19
}
18
20
19
21
impl Diff {
20
22
/// Construct a bare `diff` invocation.
21
23
pub fn new ( ) -> Self {
22
- Self { expected : None , expected_name : None , actual : None , actual_name : None }
24
+ Self {
25
+ expected : None ,
26
+ expected_name : None ,
27
+ actual : None ,
28
+ actual_name : None ,
29
+ normalizers : Vec :: new ( ) ,
30
+ }
23
31
}
24
32
25
33
/// Specify the expected output for the diff from a file.
@@ -58,15 +66,29 @@ impl Diff {
58
66
self
59
67
}
60
68
69
+ /// Specify a regex that should replace text in the "actual" text that will be compared.
70
+ pub fn normalize < R : Into < String > , I : Into < String > > (
71
+ & mut self ,
72
+ regex : R ,
73
+ replacement : I ,
74
+ ) -> & mut Self {
75
+ self . normalizers . push ( ( regex. into ( ) , replacement. into ( ) ) ) ;
76
+ self
77
+ }
78
+
61
79
/// Executes the diff process, prints any differences to the standard error.
62
80
#[ track_caller]
63
81
pub fn run ( & self ) {
64
82
let expected = self . expected . as_ref ( ) . expect ( "expected text not set" ) ;
65
- let actual = self . actual . as_ref ( ) . expect ( "actual text not set" ) ;
83
+ let mut actual = self . actual . as_ref ( ) . expect ( "actual text not set" ) . to_string ( ) ;
66
84
let expected_name = self . expected_name . as_ref ( ) . unwrap ( ) ;
67
85
let actual_name = self . actual_name . as_ref ( ) . unwrap ( ) ;
86
+ for ( regex, replacement) in & self . normalizers {
87
+ let re = Regex :: new ( regex) . expect ( "bad regex in custom normalization rule" ) ;
88
+ actual = re. replace_all ( & actual, replacement) . into_owned ( ) ;
89
+ }
68
90
69
- let output = TextDiff :: from_lines ( expected, actual)
91
+ let output = TextDiff :: from_lines ( expected, & actual)
70
92
. unified_diff ( )
71
93
. header ( expected_name, actual_name)
72
94
. to_string ( ) ;
0 commit comments