]> git.lizzy.rs Git - rust.git/blob - src/filemap.rs
Extract checkstyle output into a separate module.
[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};
22 use checkstyle::{output_heading, output_footing, output_checkstyle_file};
23
24 // A map of the files of a crate, with their new content
25 pub type FileMap = HashMap<String, StringBuffer>;
26
27 // Append a newline to the end of each file.
28 pub fn append_newlines(file_map: &mut FileMap) {
29     for (_, s) in file_map.iter_mut() {
30         s.push_str("\n");
31     }
32 }
33
34 pub fn write_all_files(file_map: &FileMap,
35                        mode: WriteMode,
36                        config: &Config)
37                        -> Result<(), io::Error> {
38     output_heading(mode).ok();
39     for filename in file_map.keys() {
40         try!(write_file(&file_map[filename], filename, mode, config));
41     }
42     output_footing(mode).ok();
43
44     Ok(())
45 }
46
47
48 // Prints all newlines either as `\n` or as `\r\n`.
49 pub fn write_system_newlines<T>(writer: T,
50                                 text: &StringBuffer,
51                                 config: &Config)
52                                 -> Result<(), io::Error>
53     where 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' => try!(write!(writer, "\r\n")),
74                     '\r' => continue,
75                     c => try!(write!(writer, "{}", c)),
76                 }
77             }
78             Ok(())
79         }
80         NewlineStyle::Native => unreachable!(),
81     }
82 }
83
84 pub fn write_file(text: &StringBuffer,
85                   filename: &str,
86                   mode: WriteMode,
87                   config: &Config)
88                   -> Result<Option<String>, io::Error> {
89
90     fn source_and_formatted_text(text: &StringBuffer,
91                                  filename: &str,
92                                  config: &Config)
93                                  -> Result<(String, String), io::Error> {
94         let mut f = try!(File::open(filename));
95         let mut ori_text = String::new();
96         try!(f.read_to_string(&mut ori_text));
97         let mut v = Vec::new();
98         try!(write_system_newlines(&mut v, text, config));
99         let fmt_text = String::from_utf8(v).unwrap();
100         Ok((ori_text, fmt_text))
101     }
102
103     fn create_diff(filename: &str,
104                    text: &StringBuffer,
105                    config: &Config)
106                    -> Result<Vec<Mismatch>, io::Error> {
107         let (ori, fmt) = try!(source_and_formatted_text(text, filename, config));
108         Ok(make_diff(&ori, &fmt, 3))
109     }
110
111     match mode {
112         WriteMode::Replace => {
113             if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
114                 if fmt != ori {
115                     // Do a little dance to make writing safer - write to a temp file
116                     // rename the original to a .bk, then rename the temp file to the
117                     // original.
118                     let tmp_name = filename.to_owned() + ".tmp";
119                     let bk_name = filename.to_owned() + ".bk";
120                     {
121                         // Write text to temp file
122                         let tmp_file = try!(File::create(&tmp_name));
123                         try!(write_system_newlines(tmp_file, text, config));
124                     }
125
126                     try!(fs::rename(filename, bk_name));
127                     try!(fs::rename(tmp_name, filename));
128                 }
129             }
130         }
131         WriteMode::Overwrite => {
132             // Write text directly over original file.
133             let file = try!(File::create(filename));
134             try!(write_system_newlines(file, text, config));
135         }
136         WriteMode::Plain => {
137             let stdout = stdout();
138             let stdout = stdout.lock();
139             try!(write_system_newlines(stdout, text, config));
140         }
141         WriteMode::Display | WriteMode::Coverage => {
142             println!("{}:\n", filename);
143             let stdout = stdout();
144             let stdout = stdout.lock();
145             try!(write_system_newlines(stdout, text, config));
146         }
147         WriteMode::Diff => {
148             println!("Diff of {}:\n", filename);
149             if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
150                 print_diff(make_diff(&ori, &fmt, 3),
151                            |line_num| format!("\nDiff at line {}:", line_num));
152             }
153         }
154         WriteMode::Default => {
155             unreachable!("The WriteMode should NEVER Be default at this point!");
156         }
157         WriteMode::Checkstyle => {
158             let stdout = stdout();
159             let stdout = stdout.lock();
160             let diff = try!(create_diff(filename, text, config));
161             // Output the XML tags for the lines that are different.
162             try!(output_checkstyle_file(stdout, filename, diff));
163         }
164         WriteMode::Return => {
165             // io::Write is not implemented for String, working around with
166             // Vec<u8>
167             let mut v = Vec::new();
168             try!(write_system_newlines(&mut v, text, config));
169             // won't panic, we are writing correct utf8
170             return Ok(Some(String::from_utf8(v).unwrap()));
171         }
172     }
173
174     Ok(None)
175 }