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