-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdiff.rs
More file actions
349 lines (318 loc) · 10.6 KB
/
diff.rs
File metadata and controls
349 lines (318 loc) · 10.6 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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
use crate::{
cli::{FileArgs, PasswordArgs},
command::{
Command, ask_password,
core::{SplitArchiveReader, collect_split_archives},
},
utils::{BsdGlobMatcher, io::streams_equal},
};
use clap::Parser;
#[cfg(unix)]
use pna::prelude::MetadataTimeExt;
use pna::{DataKind, NormalEntry, ReadOptions};
use same_file::is_same_file;
#[cfg(unix)]
use std::os::unix::fs::MetadataExt;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
#[cfg(unix)]
use std::time::SystemTime;
use std::{
fmt, fs,
io::{self, prelude::*},
path::Path,
};
#[derive(Parser, Clone, Debug)]
pub(crate) struct DiffCommand {
#[command(flatten)]
file: FileArgs,
#[command(flatten)]
password: PasswordArgs,
#[arg(
long,
help = "Compare directory mtime and ownership (by default, only mode is compared for directories)"
)]
full_compare: bool,
}
impl Command for DiffCommand {
#[inline]
fn execute(self, _ctx: &crate::cli::GlobalContext) -> anyhow::Result<()> {
diff_archive(self)
}
}
#[hooq::hooq(anyhow)]
fn diff_archive(args: DiffCommand) -> anyhow::Result<()> {
let password = ask_password(args.password)?;
let archives = collect_split_archives(&args.file.archive)?;
let options = CompareOptions {
full_compare: args.full_compare,
};
let mut globs = BsdGlobMatcher::new(args.file.files.iter().map(|s| s.as_str()));
let filter_enabled = !globs.is_empty();
let mut source = SplitArchiveReader::new(archives)?;
source.for_each_entry(
password.as_deref(),
#[hooq::skip_all]
|entry| {
let entry = entry?;
let path = entry.header().path();
if filter_enabled && !globs.matches(path) {
return Ok(());
}
compare_entry(entry, password.as_deref(), &options)
},
)?;
globs.ensure_all_matched()?;
Ok(())
}
/// Difference types detected during archive-filesystem comparison.
/// Message format follows tar --diff for compatibility.
#[derive(Clone, Debug, PartialEq, Eq)]
enum DiffKind {
/// File/directory does not exist on filesystem
Missing,
/// File size differs
SizeDiffers,
/// File contents differ (same size)
ContentsDiffer,
/// Permission mode differs
#[cfg(unix)]
ModeDiffers,
/// Modification time differs
#[cfg(unix)]
MtimeDiffers,
/// User ID differs
#[cfg(unix)]
UidDiffers,
/// Group ID differs
#[cfg(unix)]
GidDiffers,
/// File type mismatch (e.g., file vs directory)
TypeMismatch,
/// Symbolic link target differs
SymlinkDiffers,
/// Hardlink relationship broken
NotLinked(String),
}
impl DiffKind {
/// Returns a displayable message for this difference.
fn display<'a>(&'a self, path: &'a str) -> DiffMessage<'a> {
DiffMessage { kind: self, path }
}
}
/// A tar-compatible difference message that implements `Display`.
struct DiffMessage<'a> {
kind: &'a DiffKind,
path: &'a str,
}
impl fmt::Display for DiffMessage<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.kind {
DiffKind::Missing => {
write!(
f,
"{}: Warning: Cannot stat: No such file or directory",
self.path
)
}
DiffKind::SizeDiffers => write!(f, "{}: Size differs", self.path),
DiffKind::ContentsDiffer => write!(f, "{}: Contents differ", self.path),
#[cfg(unix)]
DiffKind::ModeDiffers => write!(f, "{}: Mode differs", self.path),
#[cfg(unix)]
DiffKind::MtimeDiffers => write!(f, "{}: Mod time differs", self.path),
#[cfg(unix)]
DiffKind::UidDiffers => write!(f, "{}: Uid differs", self.path),
#[cfg(unix)]
DiffKind::GidDiffers => write!(f, "{}: Gid differs", self.path),
DiffKind::TypeMismatch => write!(f, "{}: File type mismatch", self.path),
DiffKind::SymlinkDiffers => write!(f, "{}: Symlink differs", self.path),
DiffKind::NotLinked(target) => write!(f, "{}: Not linked to {target}", self.path),
}
}
}
/// Options controlling what aspects to compare.
#[derive(Clone, Debug, Default)]
struct CompareOptions {
/// Compare directory mtime and ownership (not just mode)
#[cfg_attr(not(unix), allow(dead_code))]
full_compare: bool,
}
/// Compare two SystemTime values with 1-second tolerance for filesystem precision.
#[cfg(unix)]
fn times_equal(a: SystemTime, b: SystemTime) -> bool {
match a.duration_since(b) {
Ok(d) => d.as_secs() == 0,
Err(e) => e.duration().as_secs() == 0,
}
}
/// Compare file metadata and return list of differences.
#[cfg(unix)]
fn compare_file_metadata<T: AsRef<[u8]>>(
entry: &NormalEntry<T>,
fs_meta: &fs::Metadata,
_options: &CompareOptions,
) -> Vec<DiffKind> {
let mut diffs = Vec::new();
let ownership = crate::ext::ResolvedOwnership::from_metadata(entry.metadata());
// Compare mode
if let Some(mode) = ownership.mode {
let archive_mode = mode & 0o7777;
let fs_mode = (fs_meta.permissions().mode() & 0o7777) as u16;
if archive_mode != fs_mode {
diffs.push(DiffKind::ModeDiffers);
}
}
// Compare mtime
if let Some(archive_mtime) = entry.metadata().saturating_modified_time()
&& let Ok(fs_mtime) = fs_meta.modified()
&& !times_equal(archive_mtime, fs_mtime)
{
diffs.push(DiffKind::MtimeDiffers);
}
// Compare uid/gid
if let Some(uid) = ownership.uid
&& uid != fs_meta.uid() as u64
{
diffs.push(DiffKind::UidDiffers);
}
if let Some(gid) = ownership.gid
&& gid != fs_meta.gid() as u64
{
diffs.push(DiffKind::GidDiffers);
}
diffs
}
#[cfg(not(unix))]
fn compare_file_metadata<T: AsRef<[u8]>>(
_entry: &NormalEntry<T>,
_fs_meta: &fs::Metadata,
_options: &CompareOptions,
) -> Vec<DiffKind> {
Vec::new()
}
/// Compare directory metadata and return list of differences.
/// By default only compares mode. With full_compare, also checks mtime and ownership.
#[cfg(unix)]
fn compare_directory_metadata<T: AsRef<[u8]>>(
entry: &NormalEntry<T>,
fs_meta: &fs::Metadata,
options: &CompareOptions,
) -> Vec<DiffKind> {
let mut diffs = Vec::new();
let ownership = crate::ext::ResolvedOwnership::from_metadata(entry.metadata());
// Always compare mode for directories
if let Some(mode) = ownership.mode {
let archive_mode = mode & 0o7777;
let fs_mode = (fs_meta.permissions().mode() & 0o7777) as u16;
if archive_mode != fs_mode {
diffs.push(DiffKind::ModeDiffers);
}
}
// Only compare mtime and ownership with --full-compare
if options.full_compare {
if let Some(archive_mtime) = entry.metadata().saturating_modified_time()
&& let Ok(fs_mtime) = fs_meta.modified()
&& !times_equal(archive_mtime, fs_mtime)
{
diffs.push(DiffKind::MtimeDiffers);
}
if let Some(uid) = ownership.uid
&& uid != fs_meta.uid() as u64
{
diffs.push(DiffKind::UidDiffers);
}
if let Some(gid) = ownership.gid
&& gid != fs_meta.gid() as u64
{
diffs.push(DiffKind::GidDiffers);
}
}
diffs
}
#[cfg(not(unix))]
fn compare_directory_metadata<T: AsRef<[u8]>>(
_entry: &NormalEntry<T>,
_fs_meta: &fs::Metadata,
_options: &CompareOptions,
) -> Vec<DiffKind> {
Vec::new()
}
fn compare_entry<T: AsRef<[u8]>>(
entry: NormalEntry<T>,
password: Option<&[u8]>,
options: &CompareOptions,
) -> io::Result<()> {
let data_kind = entry.header().data_kind();
let path = entry.header().path();
let path_str = path.as_str();
let meta = match fs::symlink_metadata(path) {
Ok(meta) => meta,
Err(e) if e.kind() == io::ErrorKind::NotFound => {
println!("{}", DiffKind::Missing.display(path_str));
return Ok(());
}
Err(e) => return Err(e),
};
match data_kind {
DataKind::File if meta.is_file() => {
// Compare metadata first
let meta_diffs = compare_file_metadata(&entry, &meta, options);
for diff in meta_diffs {
println!("{}", diff.display(path_str));
}
// Compare size first, then content
let fs_size = meta.len();
let archive_size = entry.metadata().raw_file_size();
if archive_size.is_some_and(|s| s != fs_size as u128) {
println!("{}", DiffKind::SizeDiffers.display(path_str));
} else {
let fs_file = fs::File::open(path)?;
let archive_reader = entry.reader(ReadOptions::with_password(password))?;
if !streams_equal(fs_file, archive_reader)? {
println!("{}", DiffKind::ContentsDiffer.display(path_str));
}
}
}
DataKind::Directory if meta.is_dir() => {
let diffs = compare_directory_metadata(&entry, &meta, options);
for diff in diffs {
println!("{}", diff.display(path_str));
}
}
DataKind::SymbolicLink if meta.is_symlink() => {
let link = fs::read_link(path)?;
let mut reader = entry.reader(ReadOptions::with_password(password))?;
let mut link_str = String::new();
reader.read_to_string(&mut link_str)?;
if link.as_path() != Path::new(&link_str) {
println!("{}", DiffKind::SymlinkDiffers.display(path_str));
}
}
DataKind::File | DataKind::Directory | DataKind::SymbolicLink => {
println!("{}", DiffKind::TypeMismatch.display(path_str));
}
DataKind::HardLink if meta.is_file() => {
let mut reader = entry.reader(ReadOptions::with_password(password))?;
let mut target = String::new();
reader.read_to_string(&mut target)?;
match is_same_file(path, &target) {
Ok(true) => (),
Ok(false) => {
println!("{}", DiffKind::NotLinked(target).display(path_str));
}
Err(e) if e.kind() == io::ErrorKind::NotFound => {
println!("{}", DiffKind::Missing.display(path_str));
}
Err(e) => return Err(e),
}
}
DataKind::HardLink => {
println!("{}", DiffKind::TypeMismatch.display(path_str));
}
_ => {
println!("{}", DiffKind::TypeMismatch.display(path_str));
}
}
Ok(())
}