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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
use anyhow::{Context, Result};
use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::path::{Path, PathBuf};
use crate::query::Query;
use crate::replace;
use crate::Console;
pub struct FilePatcher {
path: PathBuf,
new_contents: String,
num_replacements: usize,
num_lines: usize,
}
impl FilePatcher {
pub fn new(console: &Console, path: &Path, query: &Query) -> Result<Option<FilePatcher>> {
let mut num_replacements = 0;
let mut num_lines = 0;
let file =
File::open(&path).with_context(|| format!("Could not open {}", path.display()))?;
let reader = BufReader::new(file);
let mut new_contents = String::new();
for (num, chunk) in LineIterator::new(b'\n', reader).enumerate() {
let chunk = chunk.with_context(|| format!("Error while reading {}", path.display()))?;
let line = std::str::from_utf8(&chunk);
if line.is_err() {
return Ok(None);
}
let line = line.unwrap();
let replacement = replace(line, query);
match replacement {
None => new_contents.push_str(line),
Some(replacement) => {
num_lines += 1;
num_replacements += replacement.num_fragments();
let lineno = num + 1;
let prefix = format!("{}:{} ", path.display(), lineno);
console.print_replacement(&prefix, &replacement);
let new_line = replacement.output();
new_contents.push_str(new_line);
}
}
}
Ok(Some(FilePatcher {
path: path.to_path_buf(),
new_contents,
num_lines,
num_replacements,
}))
}
pub(crate) fn num_replacements(&self) -> usize {
self.num_replacements
}
pub(crate) fn num_lines(&self) -> usize {
self.num_lines
}
pub fn run(&self) -> Result<()> {
std::fs::write(&self.path, &self.new_contents)
.with_context(|| format!("Could not write {}", self.path.display()))?;
Ok(())
}
}
struct LineIterator<T: BufRead> {
delimiter: u8,
reader: T,
}
impl<T: BufRead> LineIterator<T> {
fn new(delimiter: u8, reader: T) -> Self {
Self { delimiter, reader }
}
}
impl<T: BufRead> Iterator for LineIterator<T> {
type Item = io::Result<Vec<u8>>;
fn next(&mut self) -> Option<Self::Item> {
let mut buf = Vec::new();
match self.reader.read_until(self.delimiter, &mut buf) {
Ok(0) => None,
Ok(_) => Some(Ok(buf)),
Err(e) => Some(Err(e)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Query;
use std::fs;
use tempfile::TempDir;
fn temp_dir() -> TempDir {
tempfile::Builder::new()
.prefix("test-ruplacer")
.tempdir()
.unwrap()
}
#[test]
fn test_patch_file() {
let temp_dir = temp_dir();
let file_path = temp_dir.path().join("without-trailing-newline.txt");
fs::write(&file_path, "first line\nI say: old is nice\nlast line").unwrap();
let query = Query::substring("old", "new");
let console = Console::new();
let file_patcher = FilePatcher::new(&console, &file_path, &query).unwrap();
file_patcher.unwrap().run().unwrap();
let actual = fs::read_to_string(&file_path).unwrap();
let expected = "first line\nI say: new is nice\nlast line";
assert_eq!(actual, expected);
let file_path = temp_dir.path().join("with-trailing-newline.txt");
fs::write(&file_path, "first line\nI say: old is nice\nlast line\n").unwrap();
let query = Query::substring("old", "new");
let file_patcher = FilePatcher::new(&console, &file_path, &query).unwrap();
file_patcher.unwrap().run().unwrap();
let actual = fs::read_to_string(&file_path).unwrap();
let expected = "first line\nI say: new is nice\nlast line\n";
assert_eq!(actual, expected);
}
}