]> git.lizzy.rs Git - rust.git/blob - src/filemap.rs
stop creating bk files if there are no changes. Fixes #733
[rust.git] / src / filemap.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11
12 // TODO: add tests
13
14 use strings::string_buffer::StringBuffer;
15
16 use std::collections::HashMap;
17 use std::fs::{self, File};
18 use std::io::{self, Write, Read, stdout};
19
20 use WriteMode;
21 use config::{NewlineStyle, Config};
22 use rustfmt_diff::{make_diff, print_diff};
23
24 // A map of the files of a crate, with their new content
25 pub type FileMap = HashMap<String, StringBuffer>;
26
27 // Append a newline to the end of each file.
28 pub fn append_newlines(file_map: &mut FileMap) {
29     for (_, s) in file_map.iter_mut() {
30         s.push_str("\n");
31     }
32 }
33
34 pub fn write_all_files(file_map: &FileMap,
35                        mode: WriteMode,
36                        config: &Config)
37                        -> Result<(HashMap<String, String>), io::Error> {
38     let mut result = HashMap::new();
39     for filename in file_map.keys() {
40         let one_result = try!(write_file(&file_map[filename], filename, mode, config));
41         if let Some(r) = one_result {
42             result.insert(filename.clone(), r);
43         }
44     }
45
46     Ok(result)
47 }
48
49 pub fn write_file(text: &StringBuffer,
50                   filename: &str,
51                   mode: WriteMode,
52                   config: &Config)
53                   -> Result<Option<String>, io::Error> {
54
55     // prints all newlines either as `\n` or as `\r\n`
56     fn write_system_newlines<T>(mut writer: T,
57                                 text: &StringBuffer,
58                                 config: &Config)
59                                 -> Result<(), io::Error>
60         where T: Write
61     {
62         let style = if config.newline_style == NewlineStyle::Native {
63             if cfg!(windows) {
64                 NewlineStyle::Windows
65             } else {
66                 NewlineStyle::Unix
67             }
68         } else {
69             config.newline_style
70         };
71
72         match style {
73             NewlineStyle::Unix => write!(writer, "{}", text),
74             NewlineStyle::Windows => {
75                 for (c, _) in text.chars() {
76                     match c {
77                         '\n' => try!(write!(writer, "\r\n")),
78                         '\r' => continue,
79                         c => try!(write!(writer, "{}", c)),
80                     }
81                 }
82                 Ok(())
83             }
84             NewlineStyle::Native => unreachable!(),
85         }
86     }
87
88     fn source_and_formatted_text(text: &StringBuffer,
89                                  filename: &str,
90                                  config: &Config)
91                                  -> Result<(String, String), io::Error> {
92         let mut f = try!(File::open(filename));
93         let mut ori_text = String::new();
94         try!(f.read_to_string(&mut ori_text));
95         let mut v = Vec::new();
96         try!(write_system_newlines(&mut v, text, config));
97         let fmt_text = String::from_utf8(v).unwrap();
98         Ok((ori_text, fmt_text))
99     }
100
101     match mode {
102         WriteMode::Replace => {
103             if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
104                 if fmt != ori {
105                     // Do a little dance to make writing safer - write to a temp file
106                     // rename the original to a .bk, then rename the temp file to the
107                     // original.
108                     let tmp_name = filename.to_owned() + ".tmp";
109                     let bk_name = filename.to_owned() + ".bk";
110                     {
111                         // Write text to temp file
112                         let tmp_file = try!(File::create(&tmp_name));
113                         try!(write_system_newlines(tmp_file, text, config));
114                     }
115
116                     try!(fs::rename(filename, bk_name));
117                     try!(fs::rename(tmp_name, filename));
118                 }
119             }
120         }
121         WriteMode::Overwrite => {
122             // Write text directly over original file.
123             let file = try!(File::create(filename));
124             try!(write_system_newlines(file, text, config));
125         }
126         WriteMode::NewFile(extn) => {
127             let filename = filename.to_owned() + "." + extn;
128             let file = try!(File::create(&filename));
129             try!(write_system_newlines(file, text, config));
130         }
131         WriteMode::Plain => {
132             let stdout = stdout();
133             let stdout = stdout.lock();
134             try!(write_system_newlines(stdout, text, config));
135         }
136         WriteMode::Display | WriteMode::Coverage => {
137             println!("{}:\n", filename);
138             let stdout = stdout();
139             let stdout = stdout.lock();
140             try!(write_system_newlines(stdout, text, config));
141         }
142         WriteMode::Diff => {
143             println!("Diff of {}:\n", filename);
144             if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
145                 print_diff(make_diff(&ori, &fmt, 3),
146                            |line_num| format!("\nDiff at line {}:", line_num));
147             }
148         }
149         WriteMode::Return => {
150             // io::Write is not implemented for String, working around with
151             // Vec<u8>
152             let mut v = Vec::new();
153             try!(write_system_newlines(&mut v, text, config));
154             // won't panic, we are writing correct utf8
155             return Ok(Some(String::from_utf8(v).unwrap()));
156         }
157     }
158
159     Ok(None)
160 }