]> git.lizzy.rs Git - rust.git/blob - src/filemap.rs
Merge pull request #2270 from topecongiro/issue-2260
[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 // TODO: add tests
12
13 use std::fs::{self, File};
14 use std::io::{self, BufWriter, Read, Write};
15
16 use checkstyle::{output_checkstyle_file, output_footer, output_header};
17 use config::{Config, NewlineStyle, WriteMode};
18 use rustfmt_diff::{make_diff, print_diff, Mismatch};
19
20 // A map of the files of a crate, with their new content
21 pub type FileMap = Vec<FileRecord>;
22
23 pub type FileRecord = (String, String);
24
25 // Append a newline to the end of each file.
26 pub fn append_newline(s: &mut String) {
27     s.push_str("\n");
28 }
29
30 pub fn write_all_files<T>(
31     file_map: &[FileRecord],
32     out: &mut T,
33     config: &Config,
34 ) -> Result<(), io::Error>
35 where
36     T: Write,
37 {
38     output_header(out, config.write_mode()).ok();
39     for &(ref filename, ref text) in file_map {
40         write_file(text, filename, out, config)?;
41     }
42     output_footer(out, config.write_mode()).ok();
43
44     Ok(())
45 }
46
47 // Prints all newlines either as `\n` or as `\r\n`.
48 pub fn write_system_newlines<T>(writer: T, text: &String, config: &Config) -> Result<(), io::Error>
49 where
50     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' => write!(writer, "\r\n")?,
71                     '\r' => continue,
72                     c => write!(writer, "{}", c)?,
73                 }
74             }
75             Ok(())
76         }
77         NewlineStyle::Native => unreachable!(),
78     }
79 }
80
81 pub fn write_file<T>(
82     text: &String,
83     filename: &str,
84     out: &mut T,
85     config: &Config,
86 ) -> Result<bool, io::Error>
87 where
88     T: Write,
89 {
90     fn source_and_formatted_text(
91         text: &String,
92         filename: &str,
93         config: &Config,
94     ) -> Result<(String, String), io::Error> {
95         let mut f = File::open(filename)?;
96         let mut ori_text = String::new();
97         f.read_to_string(&mut ori_text)?;
98         let mut v = Vec::new();
99         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(
105         filename: &str,
106         text: &String,
107         config: &Config,
108     ) -> Result<Vec<Mismatch>, io::Error> {
109         let (ori, fmt) = source_and_formatted_text(text, filename, config)?;
110         Ok(make_diff(&ori, &fmt, 3))
111     }
112
113     match config.write_mode() {
114         WriteMode::Replace => {
115             if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
116                 if fmt != ori {
117                     // Do a little dance to make writing safer - write to a temp file
118                     // rename the original to a .bk, then rename the temp file to the
119                     // original.
120                     let tmp_name = filename.to_owned() + ".tmp";
121                     let bk_name = filename.to_owned() + ".bk";
122                     {
123                         // Write text to temp file
124                         let tmp_file = File::create(&tmp_name)?;
125                         write_system_newlines(tmp_file, text, config)?;
126                     }
127
128                     fs::rename(filename, bk_name)?;
129                     fs::rename(tmp_name, filename)?;
130                 }
131             }
132         }
133         WriteMode::Overwrite => {
134             // Write text directly over original file if there is a diff.
135             let (source, formatted) = source_and_formatted_text(text, filename, config)?;
136             if source != formatted {
137                 let file = File::create(filename)?;
138                 write_system_newlines(file, text, config)?;
139             }
140         }
141         WriteMode::Plain => {
142             write_system_newlines(out, text, config)?;
143         }
144         WriteMode::Display | WriteMode::Coverage => {
145             println!("{}:\n", filename);
146             write_system_newlines(out, text, config)?;
147         }
148         WriteMode::Diff => {
149             if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
150                 let mismatch = make_diff(&ori, &fmt, 3);
151                 let has_diff = !mismatch.is_empty();
152                 print_diff(
153                     mismatch,
154                     |line_num| format!("Diff in {} at line {}:", filename, line_num),
155                     config.color(),
156                 );
157                 return Ok(has_diff);
158             }
159         }
160         WriteMode::Checkstyle => {
161             let diff = create_diff(filename, text, config)?;
162             output_checkstyle_file(out, filename, diff)?;
163         }
164     }
165
166     // when we are not in diff mode, don't indicate differing files
167     Ok(false)
168 }