1+ use regex:: Regex ;
12use similar:: TextDiff ;
23use std:: path:: Path ;
34
@@ -14,12 +15,19 @@ pub struct Diff {
1415 expected_name : Option < String > ,
1516 actual : Option < String > ,
1617 actual_name : Option < String > ,
18+ normalizers : Vec < ( String , String ) > ,
1719}
1820
1921impl Diff {
2022 /// Construct a bare `diff` invocation.
2123 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+ }
2331 }
2432
2533 /// Specify the expected output for the diff from a file.
@@ -58,15 +66,29 @@ impl Diff {
5866 self
5967 }
6068
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+
6179 /// Executes the diff process, prints any differences to the standard error.
6280 #[ track_caller]
6381 pub fn run ( & self ) {
6482 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 ( ) ;
6684 let expected_name = self . expected_name . as_ref ( ) . unwrap ( ) ;
6785 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+ }
6890
69- let output = TextDiff :: from_lines ( expected, actual)
91+ let output = TextDiff :: from_lines ( expected, & actual)
7092 . unified_diff ( )
7193 . header ( expected_name, actual_name)
7294 . to_string ( ) ;
0 commit comments