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,24 @@ impl Diff {
58
66
self
59
67
}
60
68
69
+ pub fn normalize ( & mut self , regex : & str , replacement : & str ) -> & mut Self {
70
+ self . normalizers . push ( ( regex. to_owned ( ) , replacement. to_owned ( ) ) ) ;
71
+ self
72
+ }
73
+
61
74
/// Executes the diff process, prints any differences to the standard error.
62
75
#[ track_caller]
63
76
pub fn run ( & self ) {
64
77
let expected = self . expected . as_ref ( ) . expect ( "expected text not set" ) ;
65
- let actual = self . actual . as_ref ( ) . expect ( "actual text not set" ) ;
78
+ let mut actual = self . actual . as_ref ( ) . expect ( "actual text not set" ) . to_string ( ) ;
66
79
let expected_name = self . expected_name . as_ref ( ) . unwrap ( ) ;
67
80
let actual_name = self . actual_name . as_ref ( ) . unwrap ( ) ;
81
+ for ( regex, replacement) in & self . normalizers {
82
+ let re = Regex :: new ( regex) . expect ( "bad regex in custom normalization rule" ) ;
83
+ actual = re. replace_all ( & actual, replacement) . into_owned ( ) ;
84
+ }
68
85
69
- let output = TextDiff :: from_lines ( expected, actual)
86
+ let output = TextDiff :: from_lines ( expected, & actual)
70
87
. unified_diff ( )
71
88
. header ( expected_name, actual_name)
72
89
. to_string ( ) ;
0 commit comments