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