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