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