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};
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 for filename in file_map.keys() {
38 try!(write_file(&file_map[filename], filename, mode, config));
41 // Output trailers for write mode.
45 // Prints all newlines either as `\n` or as `\r\n`.
46 pub fn write_system_newlines<T>(writer: T,
49 -> Result<(), io::Error>
52 // Buffer output, since we're writing a since char at a time.
53 let mut writer = BufWriter::new(writer);
55 let style = if config.newline_style == NewlineStyle::Native {
66 NewlineStyle::Unix => write!(writer, "{}", text),
67 NewlineStyle::Windows => {
68 for (c, _) in text.chars() {
70 '\n' => try!(write!(writer, "\r\n")),
72 c => try!(write!(writer, "{}", c)),
77 NewlineStyle::Native => unreachable!(),
81 pub fn write_file(text: &StringBuffer,
85 -> Result<Option<String>, io::Error> {
87 fn source_and_formatted_text(text: &StringBuffer,
90 -> Result<(String, String), io::Error> {
91 let mut f = try!(File::open(filename));
92 let mut ori_text = String::new();
93 try!(f.read_to_string(&mut ori_text));
94 let mut v = Vec::new();
95 try!(write_system_newlines(&mut v, text, config));
96 let fmt_text = String::from_utf8(v).unwrap();
97 Ok((ori_text, fmt_text))
101 WriteMode::Replace => {
102 if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
104 // Do a little dance to make writing safer - write to a temp file
105 // rename the original to a .bk, then rename the temp file to the
107 let tmp_name = filename.to_owned() + ".tmp";
108 let bk_name = filename.to_owned() + ".bk";
110 // Write text to temp file
111 let tmp_file = try!(File::create(&tmp_name));
112 try!(write_system_newlines(tmp_file, text, config));
115 try!(fs::rename(filename, bk_name));
116 try!(fs::rename(tmp_name, filename));
120 WriteMode::Overwrite => {
121 // Write text directly over original file.
122 let file = try!(File::create(filename));
123 try!(write_system_newlines(file, text, config));
125 WriteMode::Plain => {
126 let stdout = stdout();
127 let stdout = stdout.lock();
128 try!(write_system_newlines(stdout, text, config));
130 WriteMode::Display | WriteMode::Coverage => {
131 println!("{}:\n", filename);
132 let stdout = stdout();
133 let stdout = stdout.lock();
134 try!(write_system_newlines(stdout, text, config));
137 println!("Diff of {}:\n", filename);
138 if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
139 print_diff(make_diff(&ori, &fmt, 3),
140 |line_num| format!("\nDiff at line {}:", line_num));
143 WriteMode::Default => {
144 unreachable!("The WriteMode should NEVER Be default at this point!");
146 WriteMode::Checkstyle => {
147 // Generate the diff for the current file.
148 // Output the XML tags for the lines that are different.
149 // Use the new text as 'should be X'.
151 WriteMode::Return => {
152 // io::Write is not implemented for String, working around with
154 let mut v = Vec::new();
155 try!(write_system_newlines(&mut v, text, config));
156 // won't panic, we are writing correct utf8
157 return Ok(Some(String::from_utf8(v).unwrap()));