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