]> git.lizzy.rs Git - rust.git/blob - src/changes.rs
Merge pull request #112 from marcusklaas/config-fix
[rust.git] / src / changes.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
13 // print to files
14 // tests
15
16 use strings::string_buffer::StringBuffer;
17 use std::collections::HashMap;
18 use syntax::codemap::{CodeMap, Span, BytePos};
19 use std::fmt;
20 use std::fs::File;
21 use std::io::{Write, stdout};
22 use WriteMode;
23 use NewlineStyle;
24 use config::Config;
25 use utils::round_up_to_power_of_two;
26
27 // This is basically a wrapper around a bunch of Ropes which makes it convenient
28 // to work with libsyntax. It is badly named.
29 pub struct ChangeSet<'a> {
30     file_map: HashMap<String, StringBuffer>,
31     codemap: &'a CodeMap,
32     file_spans: Vec<(u32, u32)>,
33 }
34
35 impl<'a> ChangeSet<'a> {
36     // Create a new ChangeSet for a given libsyntax CodeMap.
37     pub fn from_codemap(codemap: &'a CodeMap) -> ChangeSet<'a> {
38         let mut result = ChangeSet {
39             file_map: HashMap::new(),
40             codemap: codemap,
41             file_spans: Vec::with_capacity(codemap.files.borrow().len()),
42         };
43
44         for f in codemap.files.borrow().iter() {
45             // Use the length of the file as a heuristic for how much space we
46             // need. Round to the next power of two.
47             let buffer_cap = round_up_to_power_of_two(f.src.as_ref().unwrap().len());
48
49             result.file_map.insert(f.name.clone(), StringBuffer::with_capacity(buffer_cap));
50             result.file_spans.push((f.start_pos.0, f.end_pos.0));
51         }
52
53         result.file_spans.sort();
54
55         result
56     }
57
58     pub fn filespans_for_span(&self, start: BytePos, end: BytePos) -> Vec<(u32, u32)> {
59         assert!(start.0 <= end.0);
60
61         if self.file_spans.len() == 0 {
62             return Vec::new();
63         }
64
65         // idx is the index into file_spans which indicates the current file, we
66         // with the file start denotes.
67         let mut idx = match self.file_spans.binary_search(&(start.0, ::std::u32::MAX)) {
68             Ok(i) => i,
69             Err(0) => 0,
70             Err(i) => i - 1,
71         };
72
73         let mut result = Vec::new();
74         let mut start = start.0;
75         loop {
76             let cur_file = &self.file_spans[idx];
77             idx += 1;
78
79             if idx >= self.file_spans.len() || start >= end.0 {
80                 if start < end.0 {
81                     result.push((start, end.0));
82                 }
83                 return result;
84             }
85
86             let end = ::std::cmp::min(cur_file.1 - 1, end.0);
87             if start < end {
88                 result.push((start, end));
89             }
90             start = self.file_spans[idx].0;
91         }
92     }
93
94     pub fn push_str(&mut self, filename: &str, text: &str) {
95         let buf = self.file_map.get_mut(&*filename).unwrap();
96         buf.push_str(text)
97     }
98
99     pub fn push_str_span(&mut self, span: Span, text: &str) {
100         let file_name = self.codemap.span_to_filename(span);
101         self.push_str(&file_name, text)
102     }
103
104     pub fn get_mut(&mut self, file_name: &str) -> &mut StringBuffer {
105         self.file_map.get_mut(file_name).unwrap()
106     }
107
108     pub fn cur_offset(&mut self, filename: &str) -> usize {
109         self.file_map[&*filename].cur_offset()
110     }
111
112     pub fn cur_offset_span(&mut self, span: Span) -> usize {
113         let filename = self.codemap.span_to_filename(span);
114         self.cur_offset(&filename)
115     }
116
117     // Return an iterator over the entire changed text.
118     pub fn text<'c>(&'c self) -> FileIterator<'c, 'a> {
119         FileIterator {
120             change_set: self,
121             keys: self.file_map.keys().collect(),
122             cur_key: 0,
123         }
124     }
125
126     // Append a newline to the end of each file.
127     pub fn append_newlines(&mut self) {
128         for (_, s) in self.file_map.iter_mut() {
129             s.push_str("\n");
130         }
131     }
132
133     pub fn write_all_files(&self,
134                            mode: WriteMode,
135                            config: &Config)
136                            -> Result<(HashMap<String, String>), ::std::io::Error> {
137         let mut result = HashMap::new();
138         for filename in self.file_map.keys() {
139             let one_result = try!(self.write_file(filename, mode, config));
140             if let Some(r) = one_result {
141                 result.insert(filename.clone(), r);
142             }
143         }
144
145         Ok(result)
146     }
147
148     pub fn write_file(&self,
149                       filename: &str,
150                       mode: WriteMode,
151                       config: &Config)
152                       -> Result<Option<String>, ::std::io::Error> {
153         let text = &self.file_map[filename];
154
155         // prints all newlines either as `\n` or as `\r\n`
156         fn write_system_newlines<T>(
157             mut writer: T,
158             text: &StringBuffer,
159             config: &Config)
160             -> Result<(), ::std::io::Error>
161             where T: Write,
162         {
163             match config.newline_style {
164                 NewlineStyle::Unix => write!(writer, "{}", text),
165                 NewlineStyle::Windows => {
166                     for (c, _) in text.chars() {
167                         match c {
168                             '\n' => try!(write!(writer, "\r\n")),
169                             '\r' => continue,
170                             c => try!(write!(writer, "{}", c)),
171                         }
172                     }
173                     Ok(())
174                 },
175             }
176         }
177
178         match mode {
179             WriteMode::Overwrite => {
180                 // Do a little dance to make writing safer - write to a temp file
181                 // rename the original to a .bk, then rename the temp file to the
182                 // original.
183                 let tmp_name = filename.to_owned() + ".tmp";
184                 let bk_name = filename.to_owned() + ".bk";
185                 {
186                     // Write text to temp file
187                     let tmp_file = try!(File::create(&tmp_name));
188                     try!(write_system_newlines(tmp_file, text, config));
189                 }
190
191                 try!(::std::fs::rename(filename, bk_name));
192                 try!(::std::fs::rename(tmp_name, filename));
193             }
194             WriteMode::NewFile(extn) => {
195                 let filename = filename.to_owned() + "." + extn;
196                 let file = try!(File::create(&filename));
197                 try!(write_system_newlines(file, text, config));
198             }
199             WriteMode::Display => {
200                 println!("{}:\n", filename);
201                 let stdout = stdout();
202                 let stdout_lock = stdout.lock();
203                 try!(write_system_newlines(stdout_lock, text, config));
204             }
205             WriteMode::Return(_) => {
206                 // io::Write is not implemented for String, working around with Vec<u8>
207                 let mut v = Vec::new();
208                 try!(write_system_newlines(&mut v, text, config));
209                 // won't panic, we are writing correct utf8
210                 return Ok(Some(String::from_utf8(v).unwrap()));
211             }
212         }
213
214         Ok(None)
215     }
216 }
217
218 // Iterates over each file in the ChangSet. Yields the filename and the changed
219 // text for that file.
220 pub struct FileIterator<'c, 'a: 'c> {
221     change_set: &'c ChangeSet<'a>,
222     keys: Vec<&'c String>,
223     cur_key: usize,
224 }
225
226 impl<'c, 'a> Iterator for FileIterator<'c, 'a> {
227     type Item = (&'c str, &'c StringBuffer);
228
229     fn next(&mut self) -> Option<(&'c str, &'c StringBuffer)> {
230         if self.cur_key >= self.keys.len() {
231             return None;
232         }
233
234         let key = self.keys[self.cur_key];
235         self.cur_key += 1;
236         return Some((&key, &self.change_set.file_map[&*key]))
237     }
238 }
239
240 impl<'a> fmt::Display for ChangeSet<'a> {
241     // Prints the entire changed text.
242     fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
243         for (f, r) in self.text() {
244             try!(write!(fmt, "{}:\n", f));
245             try!(write!(fmt, "{}\n\n", r));
246         }
247         Ok(())
248     }
249 }