]> git.lizzy.rs Git - rust.git/blob - src/filemap.rs
Merge pull request #1615 from Mitranim/patch-1
[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::fs::{self, File};
17 use std::io::{self, Write, Read, BufWriter};
18
19 use config::{NewlineStyle, Config, WriteMode};
20 use rustfmt_diff::{make_diff, print_diff, Mismatch};
21 use checkstyle::{output_header, output_footer, output_checkstyle_file};
22
23 // A map of the files of a crate, with their new content
24 pub type FileMap = Vec<FileRecord>;
25
26 pub type FileRecord = (String, StringBuffer);
27
28 // Append a newline to the end of each file.
29 pub fn append_newline(s: &mut StringBuffer) {
30     s.push_str("\n");
31 }
32
33 pub fn write_all_files<T>(file_map: &FileMap, out: &mut T, config: &Config) -> Result<(), io::Error>
34 where
35     T: Write,
36 {
37     output_header(out, config.write_mode()).ok();
38     for &(ref filename, ref text) in file_map {
39         write_file(text, filename, out, config)?;
40     }
41     output_footer(out, config.write_mode()).ok();
42
43     Ok(())
44 }
45
46 // Prints all newlines either as `\n` or as `\r\n`.
47 pub fn write_system_newlines<T>(
48     writer: T,
49     text: &StringBuffer,
50     config: &Config,
51 ) -> Result<(), io::Error>
52 where
53     T: Write,
54 {
55     // Buffer output, since we're writing a since char at a time.
56     let mut writer = BufWriter::new(writer);
57
58     let style = if config.newline_style() == NewlineStyle::Native {
59         if cfg!(windows) {
60             NewlineStyle::Windows
61         } else {
62             NewlineStyle::Unix
63         }
64     } else {
65         config.newline_style()
66     };
67
68     match style {
69         NewlineStyle::Unix => write!(writer, "{}", text),
70         NewlineStyle::Windows => {
71             for (c, _) in text.chars() {
72                 match c {
73                     '\n' => write!(writer, "\r\n")?,
74                     '\r' => continue,
75                     c => write!(writer, "{}", c)?,
76                 }
77             }
78             Ok(())
79         }
80         NewlineStyle::Native => unreachable!(),
81     }
82 }
83
84 pub fn write_file<T>(
85     text: &StringBuffer,
86     filename: &str,
87     out: &mut T,
88     config: &Config,
89 ) -> Result<bool, io::Error>
90 where
91     T: Write,
92 {
93
94     fn source_and_formatted_text(
95         text: &StringBuffer,
96         filename: &str,
97         config: &Config,
98     ) -> Result<(String, String), io::Error> {
99         let mut f = File::open(filename)?;
100         let mut ori_text = String::new();
101         f.read_to_string(&mut ori_text)?;
102         let mut v = Vec::new();
103         write_system_newlines(&mut v, text, config)?;
104         let fmt_text = String::from_utf8(v).unwrap();
105         Ok((ori_text, fmt_text))
106     }
107
108     fn create_diff(
109         filename: &str,
110         text: &StringBuffer,
111         config: &Config,
112     ) -> Result<Vec<Mismatch>, io::Error> {
113         let (ori, fmt) = source_and_formatted_text(text, filename, config)?;
114         Ok(make_diff(&ori, &fmt, 3))
115     }
116
117     match config.write_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 = File::create(&tmp_name)?;
129                         write_system_newlines(tmp_file, text, config)?;
130                     }
131
132                     fs::rename(filename, bk_name)?;
133                     fs::rename(tmp_name, filename)?;
134                 }
135             }
136         }
137         WriteMode::Overwrite => {
138             // Write text directly over original file if there is a diff.
139             let (source, formatted) = source_and_formatted_text(text, filename, config)?;
140             if source != formatted {
141                 let file = File::create(filename)?;
142                 write_system_newlines(file, text, config)?;
143             }
144         }
145         WriteMode::Plain => {
146             write_system_newlines(out, text, config)?;
147         }
148         WriteMode::Display | WriteMode::Coverage => {
149             println!("{}:\n", filename);
150             write_system_newlines(out, text, config)?;
151         }
152         WriteMode::Diff => {
153             if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
154                 let mismatch = make_diff(&ori, &fmt, 3);
155                 let has_diff = !mismatch.is_empty();
156                 print_diff(mismatch, |line_num| {
157                     format!("Diff in {} at line {}:", filename, line_num)
158                 });
159                 return Ok(has_diff);
160             }
161         }
162         WriteMode::Checkstyle => {
163             let diff = create_diff(filename, text, config)?;
164             output_checkstyle_file(out, filename, diff)?;
165         }
166     }
167
168     // when we are not in diff mode, don't indicate differing files
169     Ok(false)
170 }