]> git.lizzy.rs Git - rust.git/blob - src/filemap.rs
Merge pull request #309 from marcusklaas/array-literals
[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 tests
13
14 use strings::string_buffer::StringBuffer;
15 use std::collections::HashMap;
16 use std::fs::{self, File};
17 use std::io::{self, Write, Read, stdout};
18 use WriteMode;
19 use NewlineStyle;
20 use config::Config;
21 use rustfmt_diff::{make_diff, print_diff};
22
23 // A map of the files of a crate, with their new content
24 pub type FileMap = HashMap<String, StringBuffer>;
25
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() {
29         s.push_str("\n");
30     }
31 }
32
33 pub fn write_all_files(file_map: &FileMap,
34                        mode: WriteMode,
35                        config: &Config)
36                        -> Result<(HashMap<String, String>), io::Error> {
37     let mut result = HashMap::new();
38     for filename in file_map.keys() {
39         let one_result = try!(write_file(&file_map[filename], filename, mode, config));
40         if let Some(r) = one_result {
41             result.insert(filename.clone(), r);
42         }
43     }
44
45     Ok(result)
46 }
47
48 fn write_file(text: &StringBuffer,
49               filename: &str,
50               mode: WriteMode,
51               config: &Config)
52               -> Result<Option<String>, io::Error> {
53
54     // prints all newlines either as `\n` or as `\r\n`
55     fn write_system_newlines<T>(mut writer: T,
56                                 text: &StringBuffer,
57                                 config: &Config)
58                                 -> Result<(), io::Error>
59         where T: Write
60     {
61         match config.newline_style {
62             NewlineStyle::Unix => write!(writer, "{}", text),
63             NewlineStyle::Windows => {
64                 for (c, _) in text.chars() {
65                     match c {
66                         '\n' => try!(write!(writer, "\r\n")),
67                         '\r' => continue,
68                         c => try!(write!(writer, "{}", c)),
69                     }
70                 }
71                 Ok(())
72             }
73         }
74     }
75
76     match mode {
77         WriteMode::Replace => {
78             // Do a little dance to make writing safer - write to a temp file
79             // rename the original to a .bk, then rename the temp file to the
80             // original.
81             let tmp_name = filename.to_owned() + ".tmp";
82             let bk_name = filename.to_owned() + ".bk";
83             {
84                 // Write text to temp file
85                 let tmp_file = try!(File::create(&tmp_name));
86                 try!(write_system_newlines(tmp_file, text, config));
87             }
88
89             try!(fs::rename(filename, bk_name));
90             try!(fs::rename(tmp_name, filename));
91         }
92         WriteMode::Overwrite => {
93             // Write text directly over original file.
94             let file = try!(File::create(filename));
95             try!(write_system_newlines(file, text, config));
96         }
97         WriteMode::NewFile(extn) => {
98             let filename = filename.to_owned() + "." + extn;
99             let file = try!(File::create(&filename));
100             try!(write_system_newlines(file, text, config));
101         }
102         WriteMode::Display => {
103             println!("{}:\n", filename);
104             let stdout = stdout();
105             let stdout_lock = stdout.lock();
106             try!(write_system_newlines(stdout_lock, text, config));
107         }
108         WriteMode::Diff => {
109             println!("Diff of {}:\n", filename);
110             let mut f = try!(File::open(filename));
111             let mut ori_text = String::new();
112             try!(f.read_to_string(&mut ori_text));
113             let mut v = Vec::new();
114             try!(write_system_newlines(&mut v, text, config));
115             let fmt_text = String::from_utf8(v).unwrap();
116             let diff = make_diff(&ori_text, &fmt_text, 3);
117             print_diff(diff, |line_num| format!("\nDiff at line {}:", line_num));
118         }
119         WriteMode::Return(_) => {
120             // io::Write is not implemented for String, working around with
121             // Vec<u8>
122             let mut v = Vec::new();
123             try!(write_system_newlines(&mut v, text, config));
124             // won't panic, we are writing correct utf8
125             return Ok(Some(String::from_utf8(v).unwrap()));
126         }
127     }
128
129     Ok(None)
130 }