]> git.lizzy.rs Git - rust.git/blob - src/filemap.rs
Add `--quiet` flag, remove `Plain` write mode
[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 // TODO: add tests
12
13 use std::fs::{self, File};
14 use std::io::{self, BufWriter, Read, Write};
15 use std::path::Path;
16
17 use checkstyle::output_checkstyle_file;
18 use config::{Config, NewlineStyle, Verbosity, WriteMode};
19 use rustfmt_diff::{make_diff, output_modified, print_diff, Mismatch};
20 use syntax::codemap::FileName;
21
22 #[cfg(test)]
23 use FileRecord;
24
25 // Append a newline to the end of each file.
26 pub fn append_newline(s: &mut String) {
27     s.push_str("\n");
28 }
29
30 #[cfg(test)]
31 pub(crate) fn write_all_files<T>(
32     file_map: &[FileRecord],
33     out: &mut T,
34     config: &Config,
35 ) -> Result<(), io::Error>
36 where
37     T: Write,
38 {
39     if config.write_mode() == WriteMode::Checkstyle {
40         ::checkstyle::output_header(out)?;
41     }
42     for &(ref filename, ref text) in file_map {
43         write_file(text, filename, out, config)?;
44     }
45     if config.write_mode() == WriteMode::Checkstyle {
46         ::checkstyle::output_footer(out)?;
47     }
48
49     Ok(())
50 }
51
52 // Prints all newlines either as `\n` or as `\r\n`.
53 pub fn write_system_newlines<T>(writer: T, text: &str, config: &Config) -> Result<(), io::Error>
54 where
55     T: Write,
56 {
57     // Buffer output, since we're writing a since char at a time.
58     let mut writer = BufWriter::new(writer);
59
60     let style = if config.newline_style() == NewlineStyle::Native {
61         if cfg!(windows) {
62             NewlineStyle::Windows
63         } else {
64             NewlineStyle::Unix
65         }
66     } else {
67         config.newline_style()
68     };
69
70     match style {
71         NewlineStyle::Unix => write!(writer, "{}", text),
72         NewlineStyle::Windows => {
73             for c in text.chars() {
74                 match c {
75                     '\n' => write!(writer, "\r\n")?,
76                     '\r' => continue,
77                     c => write!(writer, "{}", c)?,
78                 }
79             }
80             Ok(())
81         }
82         NewlineStyle::Native => unreachable!(),
83     }
84 }
85
86 pub fn write_file<T>(
87     text: &str,
88     filename: &FileName,
89     out: &mut T,
90     config: &Config,
91 ) -> Result<bool, io::Error>
92 where
93     T: Write,
94 {
95     fn source_and_formatted_text(
96         text: &str,
97         filename: &Path,
98         config: &Config,
99     ) -> Result<(String, String), io::Error> {
100         let mut f = File::open(filename)?;
101         let mut ori_text = String::new();
102         f.read_to_string(&mut ori_text)?;
103         let mut v = Vec::new();
104         write_system_newlines(&mut v, text, config)?;
105         let fmt_text = String::from_utf8(v).unwrap();
106         Ok((ori_text, fmt_text))
107     }
108
109     fn create_diff(
110         filename: &Path,
111         text: &str,
112         config: &Config,
113     ) -> Result<Vec<Mismatch>, io::Error> {
114         let (ori, fmt) = source_and_formatted_text(text, filename, config)?;
115         Ok(make_diff(&ori, &fmt, 3))
116     }
117
118     let filename_to_path = || match *filename {
119         FileName::Real(ref path) => path,
120         _ => panic!("cannot format `{}` with WriteMode::Replace", filename),
121     };
122
123     match config.write_mode() {
124         WriteMode::Replace => {
125             let filename = filename_to_path();
126             if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
127                 if fmt != ori {
128                     // Do a little dance to make writing safer - write to a temp file
129                     // rename the original to a .bk, then rename the temp file to the
130                     // original.
131                     let tmp_name = filename.with_extension("tmp");
132                     let bk_name = filename.with_extension("bk");
133                     {
134                         // Write text to temp file
135                         let tmp_file = File::create(&tmp_name)?;
136                         write_system_newlines(tmp_file, text, config)?;
137                     }
138
139                     fs::rename(filename, bk_name)?;
140                     fs::rename(tmp_name, filename)?;
141                 }
142             }
143         }
144         WriteMode::Overwrite => {
145             // Write text directly over original file if there is a diff.
146             let filename = filename_to_path();
147             let (source, formatted) = source_and_formatted_text(text, filename, config)?;
148             if source != formatted {
149                 let file = File::create(filename)?;
150                 write_system_newlines(file, text, config)?;
151             }
152         }
153         WriteMode::Display | WriteMode::Coverage => {
154             if config.verbose() != Verbosity::Quiet {
155                 println!("{}:\n", filename);
156             }
157             write_system_newlines(out, text, config)?;
158         }
159         WriteMode::Diff => {
160             let filename = filename_to_path();
161             if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
162                 let mismatch = make_diff(&ori, &fmt, 3);
163                 let has_diff = !mismatch.is_empty();
164                 print_diff(
165                     mismatch,
166                     |line_num| format!("Diff in {} at line {}:", filename.display(), line_num),
167                     config,
168                 );
169                 return Ok(has_diff);
170             }
171         }
172         WriteMode::Modified => {
173             let filename = filename_to_path();
174             if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
175                 let mismatch = make_diff(&ori, &fmt, 0);
176                 let has_diff = !mismatch.is_empty();
177                 output_modified(out, mismatch);
178                 return Ok(has_diff);
179             }
180         }
181         WriteMode::Checkstyle => {
182             let filename = filename_to_path();
183             let diff = create_diff(filename, text, config)?;
184             output_checkstyle_file(out, filename, diff)?;
185         }
186         WriteMode::Check => {
187             let filename = filename_to_path();
188             if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
189                 let mismatch = make_diff(&ori, &fmt, 3);
190                 let has_diff = !mismatch.is_empty();
191                 print_diff(
192                     mismatch,
193                     |line_num| format!("Diff in {} at line {}:", filename.display(), line_num),
194                     config,
195                 );
196                 return Ok(has_diff);
197             }
198         }
199         WriteMode::None => {}
200     }
201
202     // when we are not in diff mode, don't indicate differing files
203     Ok(false)
204 }