]> git.lizzy.rs Git - rust.git/blob - src/filemap.rs
Merge pull request #745 from markstory/checkstyle-output
[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_header, output_footer, 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<T>(file_map: &FileMap,
35                           mut out: T,
36                           mode: WriteMode,
37                           config: &Config)
38                           -> Result<(), io::Error>
39     where T: Write
40 {
41     output_header(&mut out, mode).ok();
42     for filename in file_map.keys() {
43         try!(write_file(&file_map[filename], filename, &mut out, mode, config));
44     }
45     output_footer(&mut out, mode).ok();
46
47     Ok(())
48 }
49
50
51 // Prints all newlines either as `\n` or as `\r\n`.
52 pub fn write_system_newlines<T>(writer: T,
53                                 text: &StringBuffer,
54                                 config: &Config)
55                                 -> Result<(), io::Error>
56     where T: Write
57 {
58     // Buffer output, since we're writing a since char at a time.
59     let mut writer = BufWriter::new(writer);
60
61     let style = if config.newline_style == NewlineStyle::Native {
62         if cfg!(windows) {
63             NewlineStyle::Windows
64         } else {
65             NewlineStyle::Unix
66         }
67     } else {
68         config.newline_style
69     };
70
71     match style {
72         NewlineStyle::Unix => write!(writer, "{}", text),
73         NewlineStyle::Windows => {
74             for (c, _) in text.chars() {
75                 match c {
76                     '\n' => try!(write!(writer, "\r\n")),
77                     '\r' => continue,
78                     c => try!(write!(writer, "{}", c)),
79                 }
80             }
81             Ok(())
82         }
83         NewlineStyle::Native => unreachable!(),
84     }
85 }
86
87 pub fn write_file<T>(text: &StringBuffer,
88                      filename: &str,
89                      out: &mut T,
90                      mode: WriteMode,
91                      config: &Config)
92                      -> Result<Option<String>, io::Error>
93     where T: Write
94 {
95
96     fn source_and_formatted_text(text: &StringBuffer,
97                                  filename: &str,
98                                  config: &Config)
99                                  -> Result<(String, String), io::Error> {
100         let mut f = try!(File::open(filename));
101         let mut ori_text = String::new();
102         try!(f.read_to_string(&mut ori_text));
103         let mut v = Vec::new();
104         try!(write_system_newlines(&mut v, text, config));
105         let fmt_text = String::from_utf8(v).unwrap();
106         Ok((ori_text, fmt_text))
107     }
108
109     fn create_diff(filename: &str,
110                    text: &StringBuffer,
111                    config: &Config)
112                    -> Result<Vec<Mismatch>, io::Error> {
113         let (ori, fmt) = try!(source_and_formatted_text(text, filename, config));
114         Ok(make_diff(&ori, &fmt, 3))
115     }
116
117     match mode {
118         WriteMode::Replace => {
119             if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
120                 if fmt != ori {
121                     // Do a little dance to make writing safer - write to a temp file
122                     // rename the original to a .bk, then rename the temp file to the
123                     // original.
124                     let tmp_name = filename.to_owned() + ".tmp";
125                     let bk_name = filename.to_owned() + ".bk";
126                     {
127                         // Write text to temp file
128                         let tmp_file = try!(File::create(&tmp_name));
129                         try!(write_system_newlines(tmp_file, text, config));
130                     }
131
132                     try!(fs::rename(filename, bk_name));
133                     try!(fs::rename(tmp_name, filename));
134                 }
135             }
136         }
137         WriteMode::Overwrite => {
138             // Write text directly over original file.
139             let file = try!(File::create(filename));
140             try!(write_system_newlines(file, text, config));
141         }
142         WriteMode::Plain => {
143             let stdout = stdout();
144             let stdout = stdout.lock();
145             try!(write_system_newlines(stdout, text, config));
146         }
147         WriteMode::Display | WriteMode::Coverage => {
148             println!("{}:\n", filename);
149             let stdout = stdout();
150             let stdout = stdout.lock();
151             try!(write_system_newlines(stdout, text, config));
152         }
153         WriteMode::Diff => {
154             println!("Diff of {}:\n", filename);
155             if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
156                 print_diff(make_diff(&ori, &fmt, 3),
157                            |line_num| format!("\nDiff at line {}:", line_num));
158             }
159         }
160         WriteMode::Default => {
161             unreachable!("The WriteMode should NEVER Be default at this point!");
162         }
163         WriteMode::Checkstyle => {
164             let diff = try!(create_diff(filename, text, config));
165             try!(output_checkstyle_file(out, filename, diff));
166         }
167     }
168
169     Ok(None)
170 }