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.
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.
14 use strings::string_buffer::StringBuffer;
16 use std::collections::HashMap;
17 use std::fs::{self, File};
18 use std::io::{self, Write, Read, stdout, BufWriter};
20 use config::{NewlineStyle, Config, WriteMode};
21 use rustfmt_diff::{make_diff, print_diff, Mismatch, DiffLine};
23 // A map of the files of a crate, with their new content
24 pub type FileMap = HashMap<String, StringBuffer>;
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() {
33 pub fn write_all_files(file_map: &FileMap,
36 -> Result<(), io::Error> {
37 output_heading(&file_map, mode).ok();
38 for filename in file_map.keys() {
39 try!(write_file(&file_map[filename], filename, mode, config));
41 output_trailing(&file_map, mode).ok();
46 pub fn output_heading(file_map: &FileMap, mode: WriteMode) -> Result<(), io::Error> {
47 let stdout = stdout();
48 let mut stdout = stdout.lock();
50 WriteMode::Checkstyle => {
51 let mut xml_heading = String::new();
52 xml_heading.push_str("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
53 xml_heading.push_str("\n");
54 xml_heading.push_str("<checkstyle version=\"4.3\">");
55 try!(write!(stdout, "{}", xml_heading));
62 pub fn output_trailing(file_map: &FileMap, mode: WriteMode) -> Result<(), io::Error> {
63 let stdout = stdout();
64 let mut stdout = stdout.lock();
66 WriteMode::Checkstyle => {
67 let mut xml_tail = String::new();
68 xml_tail.push_str("</checkstyle>");
69 try!(write!(stdout, "{}", xml_tail));
76 pub fn output_checkstyle_file<T>(mut writer: T,
79 -> Result<(), io::Error>
82 try!(write!(writer, "<file name=\"{}\">", filename));
83 for mismatch in diff {
84 for line in mismatch.lines {
86 DiffLine::Expected(ref str) => {
88 "<error line=\"{}\" severity=\"error\" message=\"Should be \
94 // Do nothing with context and expected.
99 try!(write!(writer, "</file>"));
103 // Prints all newlines either as `\n` or as `\r\n`.
104 pub fn write_system_newlines<T>(writer: T,
107 -> Result<(), io::Error>
110 // Buffer output, since we're writing a since char at a time.
111 let mut writer = BufWriter::new(writer);
113 let style = if config.newline_style == NewlineStyle::Native {
115 NewlineStyle::Windows
124 NewlineStyle::Unix => write!(writer, "{}", text),
125 NewlineStyle::Windows => {
126 for (c, _) in text.chars() {
128 '\n' => try!(write!(writer, "\r\n")),
130 c => try!(write!(writer, "{}", c)),
135 NewlineStyle::Native => unreachable!(),
139 pub fn write_file(text: &StringBuffer,
143 -> Result<Option<String>, io::Error> {
145 fn source_and_formatted_text(text: &StringBuffer,
148 -> Result<(String, String), io::Error> {
149 let mut f = try!(File::open(filename));
150 let mut ori_text = String::new();
151 try!(f.read_to_string(&mut ori_text));
152 let mut v = Vec::new();
153 try!(write_system_newlines(&mut v, text, config));
154 let fmt_text = String::from_utf8(v).unwrap();
155 Ok((ori_text, fmt_text))
159 WriteMode::Replace => {
160 if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
162 // Do a little dance to make writing safer - write to a temp file
163 // rename the original to a .bk, then rename the temp file to the
165 let tmp_name = filename.to_owned() + ".tmp";
166 let bk_name = filename.to_owned() + ".bk";
168 // Write text to temp file
169 let tmp_file = try!(File::create(&tmp_name));
170 try!(write_system_newlines(tmp_file, text, config));
173 try!(fs::rename(filename, bk_name));
174 try!(fs::rename(tmp_name, filename));
178 WriteMode::Overwrite => {
179 // Write text directly over original file.
180 let file = try!(File::create(filename));
181 try!(write_system_newlines(file, text, config));
183 WriteMode::Plain => {
184 let stdout = stdout();
185 let stdout = stdout.lock();
186 try!(write_system_newlines(stdout, text, config));
188 WriteMode::Display | WriteMode::Coverage => {
189 println!("{}:\n", filename);
190 let stdout = stdout();
191 let stdout = stdout.lock();
192 try!(write_system_newlines(stdout, text, config));
195 println!("Diff of {}:\n", filename);
196 if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
197 print_diff(make_diff(&ori, &fmt, 3),
198 |line_num| format!("\nDiff at line {}:", line_num));
201 WriteMode::Default => {
202 unreachable!("The WriteMode should NEVER Be default at this point!");
204 WriteMode::Checkstyle => {
205 let stdout = stdout();
206 let stdout = stdout.lock();
207 // Generate the diff for the current file.
208 let mut f = try!(File::open(filename));
209 let mut ori_text = String::new();
210 try!(f.read_to_string(&mut ori_text));
211 let mut v = Vec::new();
212 try!(write_system_newlines(&mut v, text, config));
213 let fmt_text = String::from_utf8(v).unwrap();
214 let diff = make_diff(&ori_text, &fmt_text, 3);
215 // Output the XML tags for the lines that are different.
216 output_checkstyle_file(stdout, filename, diff).unwrap();
218 WriteMode::Return => {
219 // io::Write is not implemented for String, working around with
221 let mut v = Vec::new();
222 try!(write_system_newlines(&mut v, text, config));
223 // won't panic, we are writing correct utf8
224 return Ok(Some(String::from_utf8(v).unwrap()));