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