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};
22 use checkstyle::{output_heading, output_footing, output_checkstyle_file};
24 // A map of the files of a crate, with their new content
25 pub type FileMap = HashMap<String, StringBuffer>;
27 // Append a newline to the end of each file.
28 pub fn append_newlines(file_map: &mut FileMap) {
29 for (_, s) in file_map.iter_mut() {
34 pub fn write_all_files(file_map: &FileMap,
37 -> Result<(), io::Error> {
38 output_heading(mode).ok();
39 for filename in file_map.keys() {
40 try!(write_file(&file_map[filename], filename, mode, config));
42 output_footing(mode).ok();
48 // Prints all newlines either as `\n` or as `\r\n`.
49 pub fn write_system_newlines<T>(writer: T,
52 -> Result<(), io::Error>
55 // Buffer output, since we're writing a since char at a time.
56 let mut writer = BufWriter::new(writer);
58 let style = if config.newline_style == NewlineStyle::Native {
69 NewlineStyle::Unix => write!(writer, "{}", text),
70 NewlineStyle::Windows => {
71 for (c, _) in text.chars() {
73 '\n' => try!(write!(writer, "\r\n")),
75 c => try!(write!(writer, "{}", c)),
80 NewlineStyle::Native => unreachable!(),
84 pub fn write_file(text: &StringBuffer,
88 -> Result<Option<String>, io::Error> {
90 fn source_and_formatted_text(text: &StringBuffer,
93 -> Result<(String, String), io::Error> {
94 let mut f = try!(File::open(filename));
95 let mut ori_text = String::new();
96 try!(f.read_to_string(&mut ori_text));
97 let mut v = Vec::new();
98 try!(write_system_newlines(&mut v, text, config));
99 let fmt_text = String::from_utf8(v).unwrap();
100 Ok((ori_text, fmt_text))
103 fn create_diff(filename: &str,
106 -> Result<Vec<Mismatch>, io::Error> {
107 let (ori, fmt) = try!(source_and_formatted_text(text, filename, config));
108 Ok(make_diff(&ori, &fmt, 3))
112 WriteMode::Replace => {
113 if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
115 // Do a little dance to make writing safer - write to a temp file
116 // rename the original to a .bk, then rename the temp file to the
118 let tmp_name = filename.to_owned() + ".tmp";
119 let bk_name = filename.to_owned() + ".bk";
121 // Write text to temp file
122 let tmp_file = try!(File::create(&tmp_name));
123 try!(write_system_newlines(tmp_file, text, config));
126 try!(fs::rename(filename, bk_name));
127 try!(fs::rename(tmp_name, filename));
131 WriteMode::Overwrite => {
132 // Write text directly over original file.
133 let file = try!(File::create(filename));
134 try!(write_system_newlines(file, text, config));
136 WriteMode::Plain => {
137 let stdout = stdout();
138 let stdout = stdout.lock();
139 try!(write_system_newlines(stdout, text, config));
141 WriteMode::Display | WriteMode::Coverage => {
142 println!("{}:\n", filename);
143 let stdout = stdout();
144 let stdout = stdout.lock();
145 try!(write_system_newlines(stdout, text, config));
148 println!("Diff of {}:\n", filename);
149 if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
150 print_diff(make_diff(&ori, &fmt, 3),
151 |line_num| format!("\nDiff at line {}:", line_num));
154 WriteMode::Default => {
155 unreachable!("The WriteMode should NEVER Be default at this point!");
157 WriteMode::Checkstyle => {
158 let stdout = stdout();
159 let stdout = stdout.lock();
160 let diff = try!(create_diff(filename, text, config));
161 // Output the XML tags for the lines that are different.
162 try!(output_checkstyle_file(stdout, filename, diff));
164 WriteMode::Return => {
165 // io::Write is not implemented for String, working around with
167 let mut v = Vec::new();
168 try!(write_system_newlines(&mut v, text, config));
169 // won't panic, we are writing correct utf8
170 return Ok(Some(String::from_utf8(v).unwrap()));