]> git.lizzy.rs Git - rust.git/blob - src/changes.rs
Merge pull request #49 from oli-obk/gitignore
[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;
22 use WriteMode;
23
24 // This is basically a wrapper around a bunch of Ropes which makes it convenient
25 // to work with libsyntax. It is badly named.
26 pub struct ChangeSet<'a> {
27     file_map: HashMap<String, StringBuffer>,
28     codemap: &'a CodeMap,
29     file_spans: Vec<(u32, u32)>,
30 }
31
32 impl<'a> ChangeSet<'a> {
33     // Create a new ChangeSet for a given libsyntax CodeMap.
34     pub fn from_codemap(codemap: &'a CodeMap) -> ChangeSet<'a> {
35         let mut result = ChangeSet {
36             file_map: HashMap::new(),
37             codemap: codemap,
38             file_spans: Vec::with_capacity(codemap.files.borrow().len()),
39         };
40
41         for f in codemap.files.borrow().iter() {
42             // Use the length of the file as a heuristic for how much space we
43             // need. I hope that at some stage someone rounds this up to the next
44             // power of two. TODO check that or do it here.
45             result.file_map.insert(f.name.clone(),
46                                    StringBuffer::with_capacity(f.src.as_ref().unwrap().len()));
47
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 {
118             change_set: self,
119             keys: self.file_map.keys().collect(),
120             cur_key: 0,
121         }
122     }
123
124     // Append a newline to the end of each file.
125     pub fn append_newlines(&mut self) {
126         for (_, s) in self.file_map.iter_mut() {
127             s.push_str("\n");
128         }
129     }
130
131     pub fn write_all_files(&self,
132                            mode: WriteMode)
133                            -> Result<(HashMap<String, String>), ::std::io::Error> {
134         let mut result = HashMap::new();
135         for filename in self.file_map.keys() {
136             let one_result = try!(self.write_file(filename, mode));
137             if let Some(r) = one_result {
138                 result.insert(filename.clone(), r);
139             }
140         }
141
142         Ok(result)
143     }
144
145     pub fn write_file(&self,
146                       filename: &str,
147                       mode: WriteMode)
148                       -> Result<Option<String>, ::std::io::Error> {
149         let text = &self.file_map[filename];
150
151         match mode {
152             WriteMode::Overwrite => {
153                 // Do a little dance to make writing safer - write to a temp file
154                 // rename the original to a .bk, then rename the temp file to the
155                 // original.
156                 let tmp_name = filename.to_owned() + ".tmp";
157                 let bk_name = filename.to_owned() + ".bk";
158                 {
159                     // Write text to temp file
160                     let mut tmp_file = try!(File::create(&tmp_name));
161                     try!(write!(tmp_file, "{}", text));
162                 }
163
164                 try!(::std::fs::rename(filename, bk_name));
165                 try!(::std::fs::rename(tmp_name, filename));
166             }
167             WriteMode::NewFile(extn) => {
168                 let filename = filename.to_owned() + "." + extn;
169                 let mut file = try!(File::create(&filename));
170                 try!(write!(file, "{}", text));
171             }
172             WriteMode::Display => {
173                 println!("{}:\n", filename);
174                 println!("{}", text);
175             }
176             WriteMode::Return(_) => {
177                 return Ok(Some(text.to_string()));
178             }
179         }
180
181         Ok(None)
182     }
183 }
184
185 // Iterates over each file in the ChangSet. Yields the filename and the changed
186 // text for that file.
187 pub struct FileIterator<'c, 'a: 'c> {
188     change_set: &'c ChangeSet<'a>,
189     keys: Vec<&'c String>,
190     cur_key: usize,
191 }
192
193 impl<'c, 'a> Iterator for FileIterator<'c, 'a> {
194     type Item = (&'c str, &'c StringBuffer);
195
196     fn next(&mut self) -> Option<(&'c str, &'c StringBuffer)> {
197         if self.cur_key >= self.keys.len() {
198             return None;
199         }
200
201         let key = self.keys[self.cur_key];
202         self.cur_key += 1;
203         return Some((&key, &self.change_set.file_map[&*key]))
204     }
205 }
206
207 impl<'a> fmt::Display for ChangeSet<'a> {
208     // Prints the entire changed text.
209     fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
210         for (f, r) in self.text() {
211             try!(write!(fmt, "{}:\n", f));
212             try!(write!(fmt, "{}\n\n", r));
213         }
214         Ok(())
215     }
216 }