-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathfile_data.rs
executable file
·114 lines (93 loc) · 2.68 KB
/
file_data.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
use std::{
fs::File,
io::{self, BufReader, Read},
path::PathBuf,
time::SystemTime,
};
use super::{change::Change, constants::COULD_NOT_UNWRAP_FILENAME};
pub struct FileData {
path: PathBuf,
lines: Vec<String>,
changes: Vec<Change>,
modified: SystemTime,
ends_with_newline: bool,
}
impl FileData {
pub fn ends_with_newline(&self) -> bool {
self.ends_with_newline
}
pub fn get_file(path: PathBuf) -> io::Result<Self> {
let file = File::open(path.clone())?;
let modified = file.metadata()?.modified()?;
let mut buf_reader = BufReader::new(file);
let mut content = String::new();
buf_reader.read_to_string(&mut content)?;
let mut lines = content
.lines()
.map(|line| line.to_string())
.collect::<Vec<String>>();
let ends_with_newline = content.ends_with("\n");
if ends_with_newline {
lines.push(String::from(""));
}
let changes = vec![Change::None; lines.len()];
let result = Self {
path,
lines,
changes,
modified,
ends_with_newline,
};
Ok(result)
}
pub fn get_context_identifier(&self, change_index: usize) -> &str {
match self.changes[change_index] {
Change::None => " ",
Change::Unchanged(_) => " ",
Change::Insert(_) => "+",
Change::Delete(_) => "-",
Change::Substitute(_) => "!",
}
}
pub fn lines(&self) -> &Vec<String> {
&self.lines
}
pub fn line(&self, index: usize) -> &String {
&self.lines[index]
}
pub fn modified(&self) -> SystemTime {
self.modified
}
pub fn name(&self) -> &str {
if let Some(os_str) = self.path.file_name() {
if let Some(str_slice) = os_str.to_str() {
return str_slice;
}
}
return COULD_NOT_UNWRAP_FILENAME;
}
pub fn set_change(&mut self, change: Change, index: usize) {
self.changes[index] = change;
}
pub fn expected_changed_in_range(
&self,
start: usize,
end: usize,
expected_changes: &Vec<fn(&Change) -> bool>,
) -> bool {
for i in start..=end {
for expected_change in expected_changes {
if expected_change(&self.changes[i]) {
return true;
}
}
}
return false;
}
pub fn change(&self, index: usize) -> &Change {
&self.changes[index]
}
pub fn path(&self) -> &str {
self.path.to_str().unwrap_or(&COULD_NOT_UNWRAP_FILENAME)
}
}