@@ -14,7 +14,7 @@ mod fixture;
14
14
use std:: {
15
15
convert:: { TryFrom , TryInto } ,
16
16
env, fs,
17
- path:: PathBuf ,
17
+ path:: { Path , PathBuf } ,
18
18
} ;
19
19
20
20
use profile:: StopWatch ;
@@ -353,3 +353,36 @@ pub fn bench(label: &'static str) -> impl Drop {
353
353
354
354
Bencher { sw : StopWatch :: start ( ) , label }
355
355
}
356
+
357
+ /// Checks that the `file` has the specified `contents`. If that is not the
358
+ /// case, updates the file and then fails the test.
359
+ pub fn ensure_file_contents ( file : & Path , contents : & str ) {
360
+ if let Err ( ( ) ) = try_ensure_file_contents ( file, contents) {
361
+ panic ! ( "Some files were not up-to-date" ) ;
362
+ }
363
+ }
364
+
365
+ /// Checks that the `file` has the specified `contents`. If that is not the
366
+ /// case, updates the file and return an Error.
367
+ pub fn try_ensure_file_contents ( file : & Path , contents : & str ) -> Result < ( ) , ( ) > {
368
+ match std:: fs:: read_to_string ( file) {
369
+ Ok ( old_contents) if normalize_newlines ( & old_contents) == normalize_newlines ( contents) => {
370
+ return Ok ( ( ) )
371
+ }
372
+ _ => ( ) ,
373
+ }
374
+ let display_path = file. strip_prefix ( & project_dir ( ) ) . unwrap_or ( file) ;
375
+ eprintln ! (
376
+ "\n \x1b [31;1merror\x1b [0m: {} was not up-to-date, updating\n " ,
377
+ display_path. display( )
378
+ ) ;
379
+ if let Some ( parent) = file. parent ( ) {
380
+ let _ = std:: fs:: create_dir_all ( parent) ;
381
+ }
382
+ std:: fs:: write ( file, contents) . unwrap ( ) ;
383
+ Err ( ( ) )
384
+ }
385
+
386
+ fn normalize_newlines ( s : & str ) -> String {
387
+ s. replace ( "\r \n " , "\n " )
388
+ }
0 commit comments