@@ -2,30 +2,44 @@ extern crate failure;
2
2
extern crate rustfix;
3
3
4
4
use failure:: Error ;
5
- use std:: { env, fs, process, collections:: HashSet } ;
5
+ use std:: io:: { stdin, BufReader , Read } ;
6
+ use std:: { collections:: HashMap , collections:: HashSet , env, fs} ;
6
7
7
8
fn main ( ) -> Result < ( ) , Error > {
8
- let args : Vec < String > = env:: args ( ) . collect ( ) ;
9
- let ( suggestions_file , source_file ) = match args . as_slice ( ) {
10
- [ _ , suggestions_file , source_file ] => ( suggestions_file , source_file ) ,
11
- _ => {
12
- println ! ( "USAGE: fix-json <suggestions-file> <source-file>" ) ;
13
- process :: exit ( 1 ) ;
14
- }
9
+ let suggestions_file = env:: args ( ) . nth ( 1 ) . expect ( "USAGE: fix-json <file or -->" ) ;
10
+ let suggestions = if suggestions_file == "--" {
11
+ let mut buffer = String :: new ( ) ;
12
+ BufReader :: new ( stdin ( ) ) . read_to_string ( & mut buffer ) ? ;
13
+ buffer
14
+ } else {
15
+ fs :: read_to_string ( & suggestions_file ) ?
15
16
} ;
16
-
17
- let suggestions = fs:: read_to_string ( & suggestions_file) ?;
18
17
let suggestions = rustfix:: get_suggestions_from_json (
19
18
& suggestions,
20
19
& HashSet :: new ( ) ,
21
20
rustfix:: Filter :: Everything ,
22
21
) ?;
23
22
24
- let source = fs:: read_to_string ( & source_file) ?;
23
+ let mut files = HashMap :: new ( ) ;
24
+ for suggestion in suggestions {
25
+ let file = suggestion. solutions [ 0 ] . replacements [ 0 ]
26
+ . snippet
27
+ . file_name
28
+ . clone ( ) ;
29
+ files. entry ( file) . or_insert_with ( Vec :: new) . push ( suggestion) ;
30
+ }
25
31
26
- let fixes = rustfix:: apply_suggestions ( & source, & suggestions) ?;
27
-
28
- println ! ( "{}" , fixes) ;
32
+ for ( source_file, suggestions) in & files {
33
+ let source = fs:: read_to_string ( source_file) ?;
34
+ let mut fix = rustfix:: CodeFix :: new ( & source) ;
35
+ for suggestion in suggestions. iter ( ) . rev ( ) {
36
+ if let Err ( e) = fix. apply ( suggestion) {
37
+ eprintln ! ( "Failed to apply suggestion to {}: {}" , source_file, e) ;
38
+ }
39
+ }
40
+ let fixes = fix. finish ( ) ?;
41
+ fs:: write ( source_file, fixes) ?;
42
+ }
29
43
30
44
Ok ( ( ) )
31
45
}
0 commit comments