]> git.lizzy.rs Git - rust.git/blob - src/filemap.rs
Hack together checkstyle output that compiles.
[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, BufWriter};
19
20 use config::{NewlineStyle, Config, WriteMode};
21 use rustfmt_diff::{make_diff, print_diff, Mismatch, DiffLine};
22
23 // A map of the files of a crate, with their new content
24 pub type FileMap = HashMap<String, StringBuffer>;
25
26 // Append a newline to the end of each file.
27 pub fn append_newlines(file_map: &mut FileMap) {
28     for (_, s) in file_map.iter_mut() {
29         s.push_str("\n");
30     }
31 }
32
33 pub fn write_all_files(file_map: &FileMap,
34                        mode: WriteMode,
35                        config: &Config)
36                        -> Result<(), io::Error> {
37     output_heading(&file_map, mode).ok();
38     for filename in file_map.keys() {
39         try!(write_file(&file_map[filename], filename, mode, config));
40     }
41     output_trailing(&file_map, mode).ok();
42
43     Ok(())
44 }
45
46 pub fn output_heading(file_map: &FileMap,
47                       mode: WriteMode) -> Result<(), io::Error> {
48     let stdout = stdout();
49     let mut stdout = stdout.lock();
50     match mode {
51         WriteMode::Checkstyle => {
52             let mut xml_heading = String::new();
53             xml_heading.push_str("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
54             xml_heading.push_str("\n");
55             xml_heading.push_str("<checkstyle version=\"4.3\">");
56             try!(write!(stdout, "{}", xml_heading));
57             Ok(())
58         }
59         _ => {
60             Ok(())
61         }
62     }
63 }
64
65 pub fn output_trailing(file_map: &FileMap,
66                        mode: WriteMode) -> Result<(), io::Error> {
67     let stdout = stdout();
68     let mut stdout = stdout.lock();
69     match mode {
70         WriteMode::Checkstyle => {
71             let mut xml_tail = String::new();
72             xml_tail.push_str("</checkstyle>");
73             try!(write!(stdout, "{}", xml_tail));
74             Ok(())
75         }
76         _ => {
77             Ok(())
78         }
79     }
80 }
81
82 pub fn output_checkstyle_file<T>(mut writer: T,
83                                  filename: &str,
84                                  diff: Vec<Mismatch>) -> Result<(), io::Error>
85     where T: Write
86 {
87     try!(write!(writer, "<file name=\"{}\">", filename));
88     for mismatch in diff {
89         for line in mismatch.lines {
90             match line {
91                 DiffLine::Expected(ref str) => {
92                     try!(write!(writer, "<error line=\"{}\" severity=\"error\" message=\"Should be `{}`\" />", mismatch.line_number, str));
93                 }
94                 _ => {
95                     // Do nothing with context and expected.
96                 }
97             }
98         }
99     }
100     try!(write!(writer, "</file>"));
101     Ok(())
102 }
103
104 // Prints all newlines either as `\n` or as `\r\n`.
105 pub fn write_system_newlines<T>(writer: T,
106                                 text: &StringBuffer,
107                                 config: &Config)
108                                 -> Result<(), io::Error>
109     where T: Write
110 {
111     // Buffer output, since we're writing a since char at a time.
112     let mut writer = BufWriter::new(writer);
113
114     let style = if config.newline_style == NewlineStyle::Native {
115         if cfg!(windows) {
116             NewlineStyle::Windows
117         } else {
118             NewlineStyle::Unix
119         }
120     } else {
121         config.newline_style
122     };
123
124     match style {
125         NewlineStyle::Unix => write!(writer, "{}", text),
126         NewlineStyle::Windows => {
127             for (c, _) in text.chars() {
128                 match c {
129                     '\n' => try!(write!(writer, "\r\n")),
130                     '\r' => continue,
131                     c => try!(write!(writer, "{}", c)),
132                 }
133             }
134             Ok(())
135         }
136         NewlineStyle::Native => unreachable!(),
137     }
138 }
139
140 pub fn write_file(text: &StringBuffer,
141                   filename: &str,
142                   mode: WriteMode,
143                   config: &Config)
144                   -> Result<Option<String>, io::Error> {
145
146     fn source_and_formatted_text(text: &StringBuffer,
147                                  filename: &str,
148                                  config: &Config)
149                                  -> Result<(String, String), io::Error> {
150         let mut f = try!(File::open(filename));
151         let mut ori_text = String::new();
152         try!(f.read_to_string(&mut ori_text));
153         let mut v = Vec::new();
154         try!(write_system_newlines(&mut v, text, config));
155         let fmt_text = String::from_utf8(v).unwrap();
156         Ok((ori_text, fmt_text))
157     }
158
159     match mode {
160         WriteMode::Replace => {
161             if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
162                 if fmt != ori {
163                     // Do a little dance to make writing safer - write to a temp file
164                     // rename the original to a .bk, then rename the temp file to the
165                     // original.
166                     let tmp_name = filename.to_owned() + ".tmp";
167                     let bk_name = filename.to_owned() + ".bk";
168                     {
169                         // Write text to temp file
170                         let tmp_file = try!(File::create(&tmp_name));
171                         try!(write_system_newlines(tmp_file, text, config));
172                     }
173
174                     try!(fs::rename(filename, bk_name));
175                     try!(fs::rename(tmp_name, filename));
176                 }
177             }
178         }
179         WriteMode::Overwrite => {
180             // Write text directly over original file.
181             let file = try!(File::create(filename));
182             try!(write_system_newlines(file, text, config));
183         }
184         WriteMode::Plain => {
185             let stdout = stdout();
186             let stdout = stdout.lock();
187             try!(write_system_newlines(stdout, text, config));
188         }
189         WriteMode::Display | WriteMode::Coverage => {
190             println!("{}:\n", filename);
191             let stdout = stdout();
192             let stdout = stdout.lock();
193             try!(write_system_newlines(stdout, text, config));
194         }
195         WriteMode::Diff => {
196             println!("Diff of {}:\n", filename);
197             if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
198                 print_diff(make_diff(&ori, &fmt, 3),
199                            |line_num| format!("\nDiff at line {}:", line_num));
200             }
201         }
202         WriteMode::Default => {
203             unreachable!("The WriteMode should NEVER Be default at this point!");
204         }
205         WriteMode::Checkstyle => {
206             let stdout = stdout();
207             let stdout = stdout.lock();
208             // Generate the diff for the current file.
209             let mut f = try!(File::open(filename));
210             let mut ori_text = String::new();
211             try!(f.read_to_string(&mut ori_text));
212             let mut v = Vec::new();
213             try!(write_system_newlines(&mut v, text, config));
214             let fmt_text = String::from_utf8(v).unwrap();
215             let diff = make_diff(&ori_text, &fmt_text, 3);
216             // Output the XML tags for the lines that are different.
217             output_checkstyle_file(stdout, filename, diff).unwrap();
218         }
219         WriteMode::Return => {
220             // io::Write is not implemented for String, working around with
221             // Vec<u8>
222             let mut v = Vec::new();
223             try!(write_system_newlines(&mut v, text, config));
224             // won't panic, we are writing correct utf8
225             return Ok(Some(String::from_utf8(v).unwrap()));
226         }
227     }
228
229     Ok(None)
230 }