portable-network-archive 0.37.0

Portable-Network-Archive cli
Documentation
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use crate::{
    cli::{FileArgs, PasswordArgs},
    command::{
        Command, ExitCodeError, ask_password,
        core::{SplitArchiveReader, collect_split_archives},
    },
    utils::{BsdGlobMatcher, io::streams_equal},
};

use clap::{Parser, ValueEnum};
#[cfg(unix)]
use pna::prelude::MetadataTimeExt;
use pna::{DataKind, EntryContent, 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, 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,
    #[arg(
        long,
        default_value = "plain",
        help = "Output format [unstable: jsonl]",
        long_help = "Output format. plain: tar-style text. jsonl: one JSON Lines record per difference with fields `path`, `kind` (one of: missing, size, content, mode, mtime, uid, gid, type, symlink, hardlink) and, for kind=hardlink only, `target` (the stored link target). mode/mtime/uid/gid comparisons only occur on Unix."
    )]
    format: Format,
}

#[derive(Copy, Clone, Debug, ValueEnum)]
#[value(rename_all = "lower")]
enum Format {
    Plain,
    JsonL,
}

impl Format {
    /// Returns true if this format is unstable and requires --unstable flag
    #[inline]
    const fn is_unstable(self) -> bool {
        matches!(self, Self::JsonL)
    }
}

impl fmt::Display for Format {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.to_possible_value().unwrap().get_name())
    }
}

impl Command for DiffCommand {
    #[inline]
    fn execute(self, ctx: &crate::cli::GlobalContext) -> anyhow::Result<()> {
        match diff_archive(ctx, self) {
            Ok(0) => Ok(()),
            Ok(_) => Err(ExitCodeError::silent(1).into()),
            Err(err) => Err(ExitCodeError::with_source(2, err).into()),
        }
    }
}

#[hooq::hooq(anyhow)]
fn diff_archive(ctx: &crate::cli::GlobalContext, args: DiffCommand) -> anyhow::Result<usize> {
    if args.format.is_unstable() && !ctx.unstable() {
        anyhow::bail!(
            "The '--format {}' option is unstable and requires --unstable flag",
            args.format
        );
    }
    let password = ask_password(args.password)?;
    let archives = collect_split_archives(&args.file.archive)?;
    let options = CompareOptions {
        full_compare: args.full_compare,
        format: args.format,
    };

    let mut globs = BsdGlobMatcher::new(args.file.files.iter().map(|s| s.as_str()));
    let filter_enabled = !globs.is_empty();

    let read_options = ReadOptions::with_password(password.as_deref());
    let mut source = SplitArchiveReader::new(archives)?;
    let mut diff_count = 0usize;
    source.for_each_entry(
        &read_options,
        #[hooq::skip_all]
        |entry| {
            let entry = entry?;
            let path = entry.header().path();

            if filter_enabled && !globs.matches(path) {
                return Ok(());
            }

            diff_count += compare_entry(entry, &read_options, &options)?;
            Ok(())
        },
    )?;

    globs.ensure_all_matched()?;

    Ok(diff_count)
}

/// Difference types detected during archive-filesystem comparison.
/// Message format follows tar --diff for compatibility.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
#[serde(tag = "kind")]
enum DiffKind {
    /// File/directory does not exist on filesystem
    #[serde(rename = "missing")]
    Missing,
    /// File size differs
    #[serde(rename = "size")]
    SizeDiffers,
    /// File contents differ (same size)
    #[serde(rename = "content")]
    ContentsDiffer,
    /// Permission mode differs
    #[cfg(unix)]
    #[serde(rename = "mode")]
    ModeDiffers,
    /// Modification time differs
    #[cfg(unix)]
    #[serde(rename = "mtime")]
    MtimeDiffers,
    /// User ID differs
    #[cfg(unix)]
    #[serde(rename = "uid")]
    UidDiffers,
    /// Group ID differs
    #[cfg(unix)]
    #[serde(rename = "gid")]
    GidDiffers,
    /// File type differs (e.g., file vs directory)
    #[serde(rename = "type")]
    TypeMismatch,
    /// Symbolic link target differs
    #[serde(rename = "symlink")]
    SymlinkDiffers,
    /// Hardlink relationship broken
    #[serde(rename = "hardlink")]
    NotLinked { target: String },
}

impl DiffKind {
    /// Returns a displayable message for this difference.
    fn display<'a>(&'a self, path: &'a str) -> DiffMessage<'a> {
        DiffMessage { kind: self, path }
    }
}

#[derive(serde::Serialize)]
struct DiffRecord<'a> {
    path: &'a str,
    #[serde(flatten)]
    kind: &'a DiffKind,
}

fn report(kind: &DiffKind, path: &str, format: Format) {
    match format {
        Format::Plain => println!("{}", kind.display(path)),
        Format::JsonL => println!(
            "{}",
            serde_json::to_string(&DiffRecord { path, kind }).unwrap()
        ),
    }
}

/// 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 differs", 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)]
struct CompareOptions {
    /// Compare directory mtime and ownership (not just mode)
    #[cfg_attr(not(unix), allow(dead_code))]
    full_compare: bool,
    format: Format,
}

/// 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>,
    read_options: &ReadOptions,
    options: &CompareOptions,
) -> io::Result<usize> {
    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 => {
            report(&DiffKind::Missing, path_str, options.format);
            return Ok(1);
        }
        Err(e) => return Err(e),
    };
    let mut diff_count = 0usize;
    match data_kind {
        DataKind::FILE if meta.is_file() => {
            // Compare metadata first
            let meta_diffs = compare_file_metadata(&entry, &meta, options);
            diff_count += meta_diffs.len();
            for diff in &meta_diffs {
                report(diff, path_str, options.format);
            }

            // 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) {
                report(&DiffKind::SizeDiffers, path_str, options.format);
                diff_count += 1;
            } else {
                let fs_file = fs::File::open(path)?;
                let archive_reader = entry.reader(read_options)?;
                if !streams_equal(fs_file, archive_reader)? {
                    report(&DiffKind::ContentsDiffer, path_str, options.format);
                    diff_count += 1;
                }
            }
        }
        DataKind::DIRECTORY if meta.is_dir() => {
            let diffs = compare_directory_metadata(&entry, &meta, options);
            diff_count += diffs.len();
            for diff in &diffs {
                report(diff, path_str, options.format);
            }
        }
        DataKind::SYMBOLIC_LINK if meta.is_symlink() => {
            let link = fs::read_link(path)?;
            let EntryContent::SymbolicLink(stored) = entry.content(read_options)? else {
                unreachable!("data_kind() returned SymbolicLink");
            };
            if link.as_path() != Path::new(stored.as_str()) {
                report(&DiffKind::SymlinkDiffers, path_str, options.format);
                diff_count += 1;
            }
        }
        DataKind::HARD_LINK if meta.is_file() => {
            let EntryContent::HardLink(stored) = entry.content(read_options)? else {
                unreachable!("data_kind() returned HardLink");
            };
            match is_same_file(path, stored.as_str()) {
                Ok(true) => (),
                Ok(false) => {
                    report(
                        &DiffKind::NotLinked {
                            target: stored.to_string(),
                        },
                        path_str,
                        options.format,
                    );
                    diff_count += 1;
                }
                Err(e) if e.kind() == io::ErrorKind::NotFound => {
                    report(&DiffKind::Missing, path_str, options.format);
                    diff_count += 1;
                }
                Err(e) => return Err(e),
            }
        }
        _ => {
            report(&DiffKind::TypeMismatch, path_str, options.format);
            diff_count += 1;
        }
    }
    Ok(diff_count)
}