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