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,
47 mode: WriteMode) -> Result<(), io::Error> {
48 let stdout = stdout();
49 let mut stdout = stdout.lock();
51 WriteMode::Checkstyle => {
52 let mut xml_heading = String::new();
53 xml_heading.push_str("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
54 xml_heading.push_str("\n");
55 xml_heading.push_str("<checkstyle version=\"4.3\">");
56 try!(write!(stdout, "{}", xml_heading));
65 pub fn output_trailing(file_map: &FileMap,
66 mode: WriteMode) -> Result<(), io::Error> {
67 let stdout = stdout();
68 let mut stdout = stdout.lock();
70 WriteMode::Checkstyle => {
71 let mut xml_tail = String::new();
72 xml_tail.push_str("</checkstyle>");
73 try!(write!(stdout, "{}", xml_tail));
82 pub fn output_checkstyle_file<T>(mut writer: T,
84 diff: Vec<Mismatch>) -> Result<(), io::Error>
87 try!(write!(writer, "<file name=\"{}\">", filename));
88 for mismatch in diff {
89 for line in mismatch.lines {
91 DiffLine::Expected(ref str) => {
92 try!(write!(writer, "<error line=\"{}\" severity=\"error\" message=\"Should be `{}`\" />", mismatch.line_number, str));
95 // Do nothing with context and expected.
100 try!(write!(writer, "</file>"));
104 // Prints all newlines either as `\n` or as `\r\n`.
105 pub fn write_system_newlines<T>(writer: T,
108 -> Result<(), io::Error>
111 // Buffer output, since we're writing a since char at a time.
112 let mut writer = BufWriter::new(writer);
114 let style = if config.newline_style == NewlineStyle::Native {
116 NewlineStyle::Windows
125 NewlineStyle::Unix => write!(writer, "{}", text),
126 NewlineStyle::Windows => {
127 for (c, _) in text.chars() {
129 '\n' => try!(write!(writer, "\r\n")),
131 c => try!(write!(writer, "{}", c)),
136 NewlineStyle::Native => unreachable!(),
140 pub fn write_file(text: &StringBuffer,
144 -> Result<Option<String>, io::Error> {
146 fn source_and_formatted_text(text: &StringBuffer,
149 -> Result<(String, String), io::Error> {
150 let mut f = try!(File::open(filename));
151 let mut ori_text = String::new();
152 try!(f.read_to_string(&mut ori_text));
153 let mut v = Vec::new();
154 try!(write_system_newlines(&mut v, text, config));
155 let fmt_text = String::from_utf8(v).unwrap();
156 Ok((ori_text, fmt_text))
160 WriteMode::Replace => {
161 if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
163 // Do a little dance to make writing safer - write to a temp file
164 // rename the original to a .bk, then rename the temp file to the
166 let tmp_name = filename.to_owned() + ".tmp";
167 let bk_name = filename.to_owned() + ".bk";
169 // Write text to temp file
170 let tmp_file = try!(File::create(&tmp_name));
171 try!(write_system_newlines(tmp_file, text, config));
174 try!(fs::rename(filename, bk_name));
175 try!(fs::rename(tmp_name, filename));
179 WriteMode::Overwrite => {
180 // Write text directly over original file.
181 let file = try!(File::create(filename));
182 try!(write_system_newlines(file, text, config));
184 WriteMode::Plain => {
185 let stdout = stdout();
186 let stdout = stdout.lock();
187 try!(write_system_newlines(stdout, text, config));
189 WriteMode::Display | WriteMode::Coverage => {
190 println!("{}:\n", filename);
191 let stdout = stdout();
192 let stdout = stdout.lock();
193 try!(write_system_newlines(stdout, text, config));
196 println!("Diff of {}:\n", filename);
197 if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
198 print_diff(make_diff(&ori, &fmt, 3),
199 |line_num| format!("\nDiff at line {}:", line_num));
202 WriteMode::Default => {
203 unreachable!("The WriteMode should NEVER Be default at this point!");
205 WriteMode::Checkstyle => {
206 let stdout = stdout();
207 let stdout = stdout.lock();
208 // Generate the diff for the current file.
209 let mut f = try!(File::open(filename));
210 let mut ori_text = String::new();
211 try!(f.read_to_string(&mut ori_text));
212 let mut v = Vec::new();
213 try!(write_system_newlines(&mut v, text, config));
214 let fmt_text = String::from_utf8(v).unwrap();
215 let diff = make_diff(&ori_text, &fmt_text, 3);
216 // Output the XML tags for the lines that are different.
217 output_checkstyle_file(stdout, filename, diff).unwrap();
219 WriteMode::Return => {
220 // io::Write is not implemented for String, working around with
222 let mut v = Vec::new();
223 try!(write_system_newlines(&mut v, text, config));
224 // won't panic, we are writing correct utf8
225 return Ok(Some(String::from_utf8(v).unwrap()));