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