forked from assert-rs/dir-diff
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
273 lines (235 loc) · 8.42 KB
/
lib.rs
File metadata and controls
273 lines (235 loc) · 8.42 KB
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
//! Determine if two directories have different contents.
//!
//! For now, only one function exists: are they different, or not? In the future,
//! more functionality to actually determine the difference may be added.
//!
//! # Examples
//!
//! ```no_run
//! extern crate dir_diff;
//!
//! assert!(dir_diff::is_different("dir/a", "dir/b").unwrap());
//! ```
extern crate term_table;
extern crate walkdir;
use std::cmp::Ordering;
use std::fs::File;
use std::io::prelude::*;
use std::io::{BufRead, BufReader};
use std::path::Path;
use term_table::{
cell::{Alignment, Cell}, row::Row, Table, TableStyle,
};
use walkdir::{DirEntry, WalkDir};
/// The various errors that can happen when diffing two directories
#[derive(Debug)]
pub enum Error {
Io(std::io::Error),
StripPrefix(std::path::StripPrefixError),
WalkDir(walkdir::Error),
}
/// Are the contents of two directories different?
///
/// # Examples
///
/// ```no_run
/// extern crate dir_diff;
///
/// assert!(dir_diff::is_different("dir/a", "dir/b").unwrap());
/// ```
pub fn is_different<A: AsRef<Path>, B: AsRef<Path>>(a_base: A, b_base: B) -> Result<bool, Error> {
let mut a_walker = walk_dir(a_base);
let mut b_walker = walk_dir(b_base);
for (a, b) in (&mut a_walker).zip(&mut b_walker) {
let a = a?;
let b = b?;
if a.depth() != b.depth()
|| a.file_type() != b.file_type()
|| a.file_name() != b.file_name()
|| (a.file_type().is_file() && read_to_vec(a.path())? != read_to_vec(b.path())?)
{
return Ok(true);
}
}
Ok(!a_walker.next().is_none() || !b_walker.next().is_none())
}
macro_rules! add_row {
($table:expr, $file_name:expr, $line_one:expr, $line_two:expr) => {
$table.add_row(Row::new(vec![
Cell::new($file_name, 1),
Cell::new($line_one, 1),
Cell::new($line_two, 1),
]));
};
}
/// Prints any differences between content of two directories to stdout.
///
/// # Examples
///
/// ```no_run
/// extern crate dir_diff;
///
/// assert_eq!(dir_diff::see_difference("main/dir1", "main/dir1").unwrap(), ());
/// ```
pub fn see_difference<A: AsRef<Path>, B: AsRef<Path>>(a_base: A, b_base: B) -> Result<(), Error> {
let mut table = Table::new();
table.max_column_width = 400;
table.style = TableStyle::extended();
let filename_a = &a_base.as_ref().to_string_lossy();
let filename_b = &b_base.as_ref().to_string_lossy();
table.add_row(Row::new(vec![Cell::new_with_alignment(
"DIFFERENCES",
3,
Alignment::Center,
)]));
table.add_row(Row::new(vec![
Cell::new("Filename", 1),
Cell::new(filename_a, 1),
Cell::new(filename_b, 1),
]));
let zipped_file_names = pair_files_to_same_name(
&walk_dir_and_get_only_files(&a_base),
&mut walk_dir_and_get_only_files(&b_base),
);
for (a, b) in zipped_file_names.into_iter() {
match (a, b) {
(Some(i), None) => {
add_row!(table, i, "FILE EXISTS", "DOESN'T EXIST");
}
(None, Some(i)) => {
add_row!(table, i, "DOESN'T EXIST", "FILE EXISTS");
}
(Some(file_1), Some(file_2)) => {
let mut buffreader_a =
BufReader::new(File::open(format!("{}/{}", filename_a, &file_1))?).lines();
let mut buffreader_b =
BufReader::new(File::open(format!("{}/{}", filename_b, &file_2))?).lines();
let mut line_number = 1;
loop {
match (&buffreader_a.next(), &buffreader_b.next()) {
(None, None) => break,
(Some(line_a), Some(line_b)) => {
match (line_a, line_b) {
(Ok(content_a), Ok(content_b)) => if content_a != content_b {
add_row!(
table,
format!("\"{}\":{}", &file_1, line_number),
&content_a,
&content_b
);
},
(Ok(content_a), Err(_)) => {
add_row!(
table,
format!("\"{}\":{}", &file_1, line_number),
&content_a,
""
);
}
(Err(_), Ok(content_b)) => {
add_row!(
table,
format!("\"{}\":{}", &file_1, line_number),
"",
&content_b
);
}
_ => {}
};
}
(Some(line_a), None) => match line_a {
Ok(line_content) => add_row!(
table,
format!("\"{}\":{}", &file_1, line_number),
&line_content,
""
),
Err(_) => {
add_row!(table, format!("\"{}\":{}", &file_1, line_number), "", "")
}
},
(None, Some(line_b)) => match line_b {
Ok(line_content) => add_row!(
table,
format!("\"{}\":{}", &file_2, line_number),
"",
&line_content
),
Err(_) => {
add_row!(table, format!("\"{}\":{}", &file_2, line_number), "", "")
}
},
};
line_number += 1;
}
}
_ => {}
}
}
println!("{}", table.as_string());
Ok(())
}
fn walk_dir<P: AsRef<Path>>(path: P) -> std::iter::Skip<walkdir::IntoIter> {
WalkDir::new(path)
.sort_by(compare_by_file_name)
.into_iter()
.skip(1)
}
/// Iterated through a directory, and collects only the file paths (excluding dir path).
fn walk_dir_and_get_only_files<P: AsRef<Path>>(path: P) -> Vec<String> {
let base_path: &str = &path.as_ref().to_string_lossy().to_string();
WalkDir::new(&path)
.into_iter()
.filter_map(Result::ok)
.filter(|a| a.file_type().is_file())
.into_iter()
.map(|e| {
let file_path = e.path().to_string_lossy().to_string();
String::from(file_path).replace(base_path, "")
})
.collect()
}
fn compare_by_file_name(a: &DirEntry, b: &DirEntry) -> Ordering {
a.file_name().cmp(b.file_name())
}
fn pair_files_to_same_name<'a>(
dir1: &[String],
dir2: &mut Vec<String>,
) -> Vec<(Option<String>, Option<String>)> {
let matched_data = dir1.iter().fold(
Vec::<(Option<String>, Option<String>)>::new(),
|mut previous, current| {
match dir2.into_iter().position(|x| x == current) {
Some(i) => previous.push((Some(current.to_string()), Some(dir2.remove(i)))),
None => previous.push((Some(current.to_string()), None)),
};
return previous;
},
);
dir2.into_iter()
.fold(matched_data, |mut previous, current| {
previous.push((None, Some(current.to_string())));
previous
})
}
fn read_to_vec<P: AsRef<Path>>(file: P) -> Result<Vec<u8>, std::io::Error> {
let mut data = Vec::new();
let mut file = File::open(file.as_ref())?;
file.read_to_end(&mut data)?;
Ok(data)
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Error {
Error::Io(e)
}
}
impl From<std::path::StripPrefixError> for Error {
fn from(e: std::path::StripPrefixError) -> Error {
Error::StripPrefix(e)
}
}
impl From<walkdir::Error> for Error {
fn from(e: walkdir::Error) -> Error {
Error::WalkDir(e)
}
}