ctb_io_csc/
args.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Command-line argument definitions for the `csc` command.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use clap::{Parser, ValueEnum};
30pub use ctb_io::file::{
31    AppleDoubleStyle, AppleReadOptions, AppleSingleExtension, AppleWriteMode,
32};
33use std::path::{Path, PathBuf};
34
35/// Policy for handling detected changes to source files during copying.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, ValueEnum)]
37pub enum SourceChangePolicy {
38    /// Abort execution with a hard error if source file changes during copy.
39    #[default]
40    Error,
41    /// Log a warning and proceed with a best-effort copy.
42    BestEffort,
43}
44
45/// Command-line arguments for `csc` (checksummed copy).
46#[derive(Parser, Debug, Clone)]
47#[command(
48    name = "csc",
49    about = "Checksummed copy with rsync-compatible path resolution, strict zero-data-loss validation, crash-safe state journaling, and post-flush verification"
50)]
51pub struct CscArgs {
52    /// Source path(s) and destination path. If resuming, paths are restored
53    /// from the state file.
54    #[arg(value_name = "PATHS")]
55    pub paths: Vec<PathBuf>,
56
57    /// Path to a state file (.cscjournal or .cscdesc) from which to resume an
58    /// interrupted run. When specified, source and destination paths should
59    /// not be passed.
60    #[arg(long, value_name = "STATE_FILE")]
61    pub resume: Option<PathBuf>,
62
63    /// Explicit path for the state journal file (.cscjournal).
64    #[arg(
65        long = "journal-path",
66        alias = "journal",
67        value_name = "JOURNAL_PATH"
68    )]
69    pub journal_path: Option<PathBuf>,
70
71    /// Directory in which to store state files (default: user's home folder).
72    #[arg(long, value_name = "DIR")]
73    pub state_dir: Option<PathBuf>,
74
75    /// Verbose output showing each file copied and verified.
76    #[arg(short = 'v', long)]
77    pub verbose: bool,
78
79    /// Display real-time progress indicators (default: enabled when standard
80    /// error is connected to an interactive terminal).
81    #[arg(long, overrides_with = "no_progress")]
82    pub progress: bool,
83
84    /// Disable progress display unconditionally.
85    #[arg(long, overrides_with = "progress")]
86    pub no_progress: bool,
87
88    /// Recalculate checksums after flushing OS caches (default: enabled).
89    #[arg(long, default_value_t = true, overrides_with = "no_verify_after")]
90    pub verify_after: bool,
91
92    /// Skip the post-flush verification pass.
93    #[arg(long, overrides_with = "verify_after")]
94    pub no_verify_after: bool,
95
96    /// Authorize replacing existing entries and restoring directory metadata.
97    /// Existing entries are refused by default, including during resume.
98    #[arg(long, default_value_t = false)]
99    pub overwrite: bool,
100
101    /// Behavior when a source file is modified during copy.
102    #[arg(long, value_enum, default_value_t = SourceChangePolicy::Error)]
103    pub on_source_change: SourceChangePolicy,
104
105    /// Recreate special files (FIFOs, device nodes) faithfully as special nodes.
106    /// Default is to skip special files.
107    #[arg(long)]
108    pub copy_specials_as_specials: bool,
109
110    /// Copy block devices by reading their data and creating regular files.
111    #[arg(long)]
112    pub copy_block_devices_as_regular_files: bool,
113
114    /// Copy FIFOs (named pipes) by reading their content and creating regular files.
115    #[arg(long)]
116    pub copy_fifos_as_regular_files: bool,
117
118    /// Stay on the current filesystem and do not cross mount boundaries.
119    #[arg(short = 'x', long = "one-file-system")]
120    pub one_file_system: bool,
121
122    /// Relax strict metadata requirements when writing to target filesystem.
123    /// Permits unprivileged copies (skips root-only chown/flags failures)
124    /// and tolerates up to 2 seconds of timestamp precision loss (e.g. FAT/SMB).
125    #[arg(long)]
126    pub best_effort_metadata: bool,
127
128    /// Allow operation even if the filesystem type cannot be detected.
129    #[arg(long)]
130    pub allow_unknown_fs: bool,
131
132    /// Explicitly check access time (atime) differences in post-copy verification.
133    #[arg(long)]
134    pub check_atime: bool,
135
136    /// Explicitly check status/metadata change time (ctime) differences in post-copy verification.
137    #[arg(long)]
138    pub check_ctime: bool,
139
140    /// Require birth-time equality even on platforms unable to restore it.
141    #[arg(long)]
142    pub check_birthtime: bool,
143
144    /// Enforce strictest verification settings, enabling --check-atime and --check-ctime in post-copy verification.
145    #[arg(long)]
146    pub strict: bool,
147
148    /// Delete state journal (.cscjournal) and descriptor (.cscdesc) upon successful completion.
149    #[arg(long)]
150    pub delete_manifest_after: bool,
151
152    /// Recursive copy (default for csc; accepted for cp compatibility).
153    #[arg(short = 'r', short_alias = 'R', long = "recursive")]
154    pub recursive: bool,
155
156    /// Archive mode (preserves metadata, symlinks, and recurses; default for csc; accepted for cp compatibility).
157    #[arg(short = 'a', long = "archive")]
158    pub archive: bool,
159
160    /// Perform a dry run without copying or modifying destination files.
161    #[arg(short = 'n', long)]
162    pub dry_run: bool,
163
164    /// Read AppleDouble companion files and join them into file entities.
165    /// Defaults to `alongside` style if passed without a style.
166    #[arg(
167        long,
168        value_name = "STYLE",
169        num_args = 0..=1,
170        default_missing_value = "alongside",
171        require_equals = false
172    )]
173    pub read_apple_double: Option<AppleDoubleStyle>,
174
175    /// Read alongside (._<filename>) AppleDouble companion files.
176    #[arg(long, overrides_with = "no_read_apple_double_alongside")]
177    pub read_apple_double_alongside: bool,
178
179    /// Disable reading alongside (._<filename>) AppleDouble companion files.
180    #[arg(long, overrides_with = "read_apple_double_alongside")]
181    pub no_read_apple_double_alongside: bool,
182
183    /// Read __MACOSX/ directory AppleDouble companion files.
184    #[arg(long)]
185    pub read_apple_double_zip: bool,
186
187    /// Read Netatalk .AppleDouble companion files.
188    #[arg(long)]
189    pub read_apple_double_netatalk: bool,
190
191    /// Read AppleSingle files and decode data fork, resource fork, and Apple metadata.
192    #[arg(long, overrides_with = "no_read_apple_single")]
193    pub read_apple_single: bool,
194
195    /// Read bare AppleSingle files without extension (alias for --read-apple-single).
196    #[arg(long, overrides_with = "no_read_apple_single")]
197    pub read_apple_single_without_extension: bool,
198
199    /// Disable reading bare AppleSingle files without extension.
200    #[arg(long, overrides_with = "read_apple_single")]
201    pub no_read_apple_single: bool,
202
203    /// Read AppleSingle files with the specified extension ('as' or 'asf'),
204    /// automatically stripping the extension upon successful decode.
205    /// May be specified multiple times to support multiple extensions.
206    #[arg(long, value_name = "EXT", action = clap::ArgAction::Append)]
207    pub read_apple_single_with_extension: Vec<AppleSingleExtension>,
208
209    /// Write AppleDouble companion files if native filesystem streams or Apple metadata cannot be preserved.
210    /// Defaults to `alongside` style if passed without a style.
211    #[arg(
212        long,
213        value_name = "STYLE",
214        num_args = 0..=1,
215        default_missing_value = "alongside",
216        require_equals = false
217    )]
218    pub maybe_write_apple_double: Option<AppleDoubleStyle>,
219
220    /// Force writing AppleDouble companion files even if native streams are supported.
221    /// Defaults to `alongside` style if passed without a style.
222    #[arg(
223        long,
224        value_name = "STYLE",
225        num_args = 0..=1,
226        default_missing_value = "alongside",
227        require_equals = false
228    )]
229    pub force_write_apple_double: Option<AppleDoubleStyle>,
230
231    /// Write AppleSingle archive files if native filesystem streams or Apple metadata cannot be preserved.
232    #[arg(long)]
233    pub maybe_write_apple_single: bool,
234
235    /// Force writing destination files as AppleSingle archives.
236    #[arg(long)]
237    pub force_write_apple_single: bool,
238
239    /// Write AppleSingle archive files with specified extension: 'as' or 'asf'.
240    #[arg(long, value_name = "EXT")]
241    pub write_apple_single_with_extension: Option<AppleSingleExtension>,
242
243    /// Write AppleSingle archive files without extension (default).
244    #[arg(long, alias = "write-apple-single")]
245    pub write_apple_single_without_extension: bool,
246
247    /// Read alongside `<filename>:<stream_name>` Windows alternate data stream companion files.
248    #[arg(long, overrides_with = "no_read_windows_ads")]
249    pub read_windows_ads: bool,
250
251    /// Disable reading alongside `<filename>:<stream_name>` Windows alternate data stream companion files.
252    #[arg(long, overrides_with = "read_windows_ads")]
253    pub no_read_windows_ads: bool,
254
255    /// Write alongside `<filename>:<stream_name>` Windows alternate data stream companion files if native streams cannot be preserved.
256    #[arg(long)]
257    pub maybe_write_windows_ads: bool,
258
259    /// Force writing attached streams as alongside `<filename>:<stream_name>` Windows alternate data stream companion files.
260    #[arg(long, alias = "write-windows-ads")]
261    pub force_write_windows_ads: bool,
262
263    /// Record full provenance environment information using slow environment detection
264    /// (e.g. network discovery for public IP addresses and server time synchronization).
265    #[arg(long)]
266    pub full_provenance: bool,
267
268    /// Continue copying remaining files when an item cannot be read, copied, or materialized.
269    /// Errors are logged into the journal and descriptor instead of aborting the operation.
270    #[arg(long, alias = "ignore-errors")]
271    pub continue_on_error: bool,
272
273    /// Allow forgiving projection when reading state journals containing syntax or schema errors.
274    #[arg(long)]
275    pub allow_journal_errors: bool,
276}
277
278impl CscArgs {
279    /// Returns the projection policy to use when decoding state journals.
280    #[must_use]
281    pub const fn journal_projection_policy(
282        &self,
283    ) -> ctb_formats_dcstring::DcProjectionPolicy {
284        if self.allow_journal_errors {
285            ctb_formats_dcstring::DcProjectionPolicy::forgiving()
286        } else {
287            ctb_formats_dcstring::DcProjectionPolicy::strict()
288        }
289    }
290
291    /// Resolves whether progress display is active.
292    ///
293    /// Respects `--no-progress` (disabled) and `--progress` (forced enabled),
294    /// falling back to whether standard error is connected to an interactive
295    /// terminal.
296    #[must_use]
297    pub fn should_show_progress(&self) -> bool {
298        should_show_progress(self.progress, self.no_progress)
299    }
300
301    /// Resolves whether post-flush verification is active.
302    #[must_use]
303    pub fn should_verify_after(&self) -> bool {
304        if self.no_verify_after {
305            false
306        } else {
307            self.verify_after
308        }
309    }
310
311    /// Resolves whether access time checking is active in post-copy verification.
312    #[must_use]
313    pub fn should_check_atime(&self) -> bool {
314        self.strict || self.check_atime
315    }
316
317    /// Resolves whether metadata change time checking is active in post-copy verification.
318    #[must_use]
319    pub fn should_check_ctime(&self) -> bool {
320        self.strict
321            || self.check_ctime
322            || (cfg!(windows) && !ctb_utilities::environment::is_wine())
323    }
324
325    /// Whether birth-time fidelity is required on the destination.
326    #[must_use]
327    pub fn should_check_birthtime(&self) -> bool {
328        self.strict || self.check_birthtime || cfg!(windows)
329    }
330
331    /// Resolves AppleSingle / AppleDouble / Windows ADS companion read options.
332    #[must_use]
333    pub fn resolve_apple_read_options(&self) -> AppleReadOptions {
334        let mut opts = resolve_apple_read_options_from_flags(
335            self.read_apple_double,
336            self.read_apple_double_alongside,
337            self.no_read_apple_double_alongside,
338            self.read_apple_double_zip,
339            self.read_apple_double_netatalk,
340            self.read_apple_single,
341            self.read_apple_single_without_extension,
342            self.no_read_apple_single,
343            &self.read_apple_single_with_extension,
344        );
345        opts.read_windows_ads_alongside =
346            self.read_windows_ads && !self.no_read_windows_ads;
347        opts
348    }
349
350    /// Resolves AppleSingle / AppleDouble / Windows ADS write mode, ensuring mutual exclusivity.
351    pub fn resolve_apple_write_mode(
352        &self,
353    ) -> Result<(AppleWriteMode, AppleSingleExtension)> {
354        resolve_apple_write_mode_from_flags(
355            self.maybe_write_apple_double,
356            self.force_write_apple_double,
357            self.maybe_write_apple_single,
358            self.force_write_apple_single,
359            self.write_apple_single_with_extension,
360            self.write_apple_single_without_extension,
361            self.maybe_write_windows_ads,
362            self.force_write_windows_ads,
363            self.best_effort_metadata,
364        )
365    }
366}
367
368/// Shared CLI flags for AppleSingle, AppleDouble, and Windows ADS companion reading.
369#[derive(clap::Args, Debug, Clone, PartialEq, Eq, Default)]
370pub struct AppleReadCliArgs {
371    /// Read AppleDouble companion files and join them into file entities.
372    /// Defaults to `alongside` style if passed without a style.
373    #[arg(
374        long,
375        value_name = "STYLE",
376        num_args = 0..=1,
377        default_missing_value = "alongside",
378        require_equals = false
379    )]
380    pub read_apple_double: Option<AppleDoubleStyle>,
381
382    /// Read alongside (._<filename>) AppleDouble companion files.
383    #[arg(long, overrides_with = "no_read_apple_double_alongside")]
384    pub read_apple_double_alongside: bool,
385
386    /// Disable reading alongside (._<filename>) AppleDouble companion files.
387    #[arg(long, overrides_with = "read_apple_double_alongside")]
388    pub no_read_apple_double_alongside: bool,
389
390    /// Read __MACOSX/ directory AppleDouble companion files.
391    #[arg(long)]
392    pub read_apple_double_zip: bool,
393
394    /// Read Netatalk .AppleDouble companion files.
395    #[arg(long)]
396    pub read_apple_double_netatalk: bool,
397
398    /// Read AppleSingle files and decode data fork, resource fork, and Apple metadata.
399    #[arg(long, overrides_with = "no_read_apple_single")]
400    pub read_apple_single: bool,
401
402    /// Read bare AppleSingle files without extension (alias for --read-apple-single).
403    #[arg(long, overrides_with = "no_read_apple_single")]
404    pub read_apple_single_without_extension: bool,
405
406    /// Disable reading bare AppleSingle files without extension.
407    #[arg(long, overrides_with = "read_apple_single")]
408    pub no_read_apple_single: bool,
409
410    /// Read AppleSingle files with the specified extension ('as' or 'asf'),
411    /// automatically stripping the extension upon successful decode.
412    #[arg(long, value_name = "EXT", action = clap::ArgAction::Append)]
413    pub read_apple_single_with_extension: Vec<AppleSingleExtension>,
414
415    /// Read alongside `<filename>:<stream_name>` Windows alternate data stream companion files.
416    #[arg(long, overrides_with = "no_read_windows_ads")]
417    pub read_windows_ads: bool,
418
419    /// Disable reading alongside `<filename>:<stream_name>` Windows alternate data stream companion files.
420    #[arg(long, overrides_with = "read_windows_ads")]
421    pub no_read_windows_ads: bool,
422}
423
424impl AppleReadCliArgs {
425    /// Resolves these CLI flags into an [`AppleReadOptions`] configuration.
426    #[must_use]
427    pub fn resolve(&self) -> AppleReadOptions {
428        let mut opts = resolve_apple_read_options_from_flags(
429            self.read_apple_double,
430            self.read_apple_double_alongside,
431            self.no_read_apple_double_alongside,
432            self.read_apple_double_zip,
433            self.read_apple_double_netatalk,
434            self.read_apple_single,
435            self.read_apple_single_without_extension,
436            self.no_read_apple_single,
437            &self.read_apple_single_with_extension,
438        );
439        opts.read_windows_ads_alongside =
440            self.read_windows_ads && !self.no_read_windows_ads;
441        opts
442    }
443}
444
445/// Shared CLI flags for AppleSingle, AppleDouble, and Windows ADS stream restoration.
446#[derive(clap::Args, Debug, Clone, PartialEq, Eq, Default)]
447pub struct AppleWriteCliArgs {
448    /// Write AppleDouble companion files if native filesystem streams or Apple metadata cannot be preserved.
449    /// Defaults to `alongside` style if passed without a style.
450    #[arg(
451        long,
452        value_name = "STYLE",
453        num_args = 0..=1,
454        default_missing_value = "alongside",
455        require_equals = false
456    )]
457    pub maybe_write_apple_double: Option<AppleDoubleStyle>,
458
459    /// Force writing AppleDouble companion files even if native streams are supported.
460    /// Defaults to `alongside` style if passed without a style.
461    #[arg(
462        long,
463        value_name = "STYLE",
464        num_args = 0..=1,
465        default_missing_value = "alongside",
466        require_equals = false
467    )]
468    pub force_write_apple_double: Option<AppleDoubleStyle>,
469
470    /// Write AppleSingle archive files if native filesystem streams or Apple metadata cannot be preserved.
471    #[arg(long)]
472    pub maybe_write_apple_single: bool,
473
474    /// Force writing destination files as AppleSingle archives.
475    #[arg(long)]
476    pub force_write_apple_single: bool,
477
478    /// Write AppleSingle archive files with specified extension: 'as' or 'asf'.
479    #[arg(long, value_name = "EXT")]
480    pub write_apple_single_with_extension: Option<AppleSingleExtension>,
481
482    /// Write AppleSingle archive files without extension (default).
483    #[arg(long, alias = "write-apple-single")]
484    pub write_apple_single_without_extension: bool,
485
486    /// Write alongside `<filename>:<stream_name>` Windows alternate data stream companion files if native streams cannot be preserved.
487    #[arg(long)]
488    pub maybe_write_windows_ads: bool,
489
490    /// Force writing attached streams as alongside `<filename>:<stream_name>` Windows alternate data stream companion files.
491    #[arg(long, alias = "write-windows-ads")]
492    pub force_write_windows_ads: bool,
493}
494
495impl AppleWriteCliArgs {
496    /// Resolves these CLI flags into an [`AppleWriteMode`] and [`AppleSingleExtension`].
497    pub fn resolve(
498        &self,
499        best_effort_fallback: bool,
500    ) -> Result<(AppleWriteMode, AppleSingleExtension)> {
501        resolve_apple_write_mode_from_flags(
502            self.maybe_write_apple_double,
503            self.force_write_apple_double,
504            self.maybe_write_apple_single,
505            self.force_write_apple_single,
506            self.write_apple_single_with_extension,
507            self.write_apple_single_without_extension,
508            self.maybe_write_windows_ads,
509            self.force_write_windows_ads,
510            best_effort_fallback,
511        )
512    }
513}
514
515/// Helper to resolve AppleSingle / AppleDouble / Windows ADS write mode from raw CLI flags.
516#[expect(
517    clippy::too_many_arguments,
518    reason = "Maps distinct CLI flags to canonical write mode"
519)]
520pub fn resolve_apple_write_mode_from_flags(
521    maybe_write_apple_double: Option<AppleDoubleStyle>,
522    force_write_apple_double: Option<AppleDoubleStyle>,
523    maybe_write_apple_single: bool,
524    force_write_apple_single: bool,
525    write_apple_single_with_extension: Option<AppleSingleExtension>,
526    write_apple_single_without_extension: bool,
527    maybe_write_windows_ads: bool,
528    force_write_windows_ads: bool,
529    best_effort_metadata: bool,
530) -> Result<(AppleWriteMode, AppleSingleExtension)> {
531    let mut count = 0_usize;
532    if maybe_write_apple_double.is_some() {
533        count = count.saturating_add(1);
534    }
535    if force_write_apple_double.is_some() {
536        count = count.saturating_add(1);
537    }
538    if maybe_write_apple_single {
539        count = count.saturating_add(1);
540    }
541    let is_explicit_force_single = force_write_apple_single
542        || write_apple_single_without_extension
543        || write_apple_single_with_extension.is_some();
544    if is_explicit_force_single {
545        count = count.saturating_add(1);
546    }
547    if maybe_write_windows_ads {
548        count = count.saturating_add(1);
549    }
550    if force_write_windows_ads {
551        count = count.saturating_add(1);
552    }
553
554    if count > 1 {
555        anyhow::bail!(
556            "Cannot specify more than one AppleDouble, AppleSingle, or Windows ADS write mode simultaneously"
557        );
558    }
559
560    // Reason for fallback: default write extension is WithoutExtension
561    let write_ext = write_apple_single_with_extension
562        .unwrap_or(AppleSingleExtension::WithoutExtension);
563
564    let mode = if let Some(style) = force_write_apple_double {
565        AppleWriteMode::ForceAppleDouble(style)
566    } else if let Some(style) = maybe_write_apple_double {
567        AppleWriteMode::MaybeAppleDouble(style)
568    } else if is_explicit_force_single {
569        AppleWriteMode::ForceAppleSingle
570    } else if maybe_write_apple_single {
571        AppleWriteMode::MaybeAppleSingle
572    } else if force_write_windows_ads {
573        AppleWriteMode::ForceWindowsAds
574    } else if maybe_write_windows_ads {
575        AppleWriteMode::MaybeWindowsAds
576    } else if best_effort_metadata {
577        AppleWriteMode::MaybeAppleDouble(AppleDoubleStyle::Alongside)
578    } else {
579        AppleWriteMode::NativeOnly
580    };
581
582    Ok((mode, write_ext))
583}
584
585/// Helper to resolve AppleSingle / AppleDouble read options from raw CLI flags.
586#[must_use]
587pub fn resolve_apple_read_options_from_flags(
588    read_apple_double: Option<AppleDoubleStyle>,
589    read_apple_double_alongside: bool,
590    no_read_apple_double_alongside: bool,
591    read_apple_double_zip: bool,
592    read_apple_double_netatalk: bool,
593    read_apple_single: bool,
594    read_apple_single_without_extension: bool,
595    no_read_apple_single: bool,
596    read_apple_single_with_extension: &[AppleSingleExtension],
597) -> AppleReadOptions {
598    let mut alongside =
599        read_apple_double_alongside && !no_read_apple_double_alongside;
600    let mut zip = read_apple_double_zip;
601    let mut netatalk = read_apple_double_netatalk;
602
603    if let Some(style) = read_apple_double {
604        match style {
605            AppleDoubleStyle::Alongside => {
606                alongside = !no_read_apple_double_alongside;
607            }
608            AppleDoubleStyle::Zip => zip = true,
609            AppleDoubleStyle::Netatalk => netatalk = true,
610        }
611    }
612
613    let read_single_bare = (read_apple_single
614        || read_apple_single_without_extension)
615        && !no_read_apple_single;
616
617    let mut read_as = false;
618    let mut read_asf = false;
619    let mut read_bare = read_single_bare;
620
621    for ext in read_apple_single_with_extension {
622        match ext {
623            AppleSingleExtension::As => read_as = true,
624            AppleSingleExtension::Asf => read_asf = true,
625            AppleSingleExtension::WithoutExtension => read_bare = true,
626        }
627    }
628
629    AppleReadOptions {
630        read_apple_double_alongside: alongside,
631        read_apple_double_zip: zip,
632        read_apple_double_netatalk: netatalk,
633        read_apple_single_without_extension: read_bare,
634        read_apple_single: read_bare,
635        read_apple_single_as: read_as,
636        read_apple_single_asf: read_asf,
637        read_windows_ads_alongside: false,
638    }
639}
640
641/// Output format for verification reporting.
642#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, ValueEnum)]
643pub enum VerifyOutputFormat {
644    /// Human-readable detailed text summary.
645    #[default]
646    Text,
647    /// JSON output for automated scripting and machine parsing.
648    Json,
649}
650
651/// Common verification and strictness criteria flags shared by `csc-verify` and `csc-diff`.
652#[derive(clap::Args, Debug, Clone, PartialEq, Eq)]
653pub struct VerificationCriteriaArgs {
654    /// Skip dropping OS kernel caches and per-file cache eviction before reading.
655    #[arg(long)]
656    pub no_drop_caches: bool,
657
658    /// Ignore access time (atime) differences during verification (defaults to
659    /// true).
660    #[arg(long, default_value_t = true)]
661    pub ignore_atime: bool,
662
663    /// Explicitly check access time (atime) differences during verification.
664    #[arg(long)]
665    pub check_atime: bool,
666
667    /// Ignore modification time (mtime) differences during verification.
668    #[arg(long)]
669    pub ignore_mtime: bool,
670
671    /// Ignore status/metadata change time (ctime) differences (defaults to true as POSIX cannot set ctime).
672    #[arg(long, default_value_t = true)]
673    pub ignore_ctime: bool,
674
675    /// Explicitly enforce status/metadata change time (ctime) verification.
676    #[arg(long)]
677    pub check_ctime: bool,
678
679    /// Require birth-time equality even on platforms unable to restore it.
680    #[arg(long)]
681    pub check_birthtime: bool,
682
683    /// Ignore ownership (UID and GID) differences.
684    #[arg(long)]
685    pub ignore_owner: bool,
686
687    /// Ignore file mode / permission differences.
688    #[arg(long)]
689    pub ignore_perms: bool,
690
691    /// Ignore semantic file flags differences.
692    #[arg(long)]
693    pub ignore_flags: bool,
694
695    /// Ignore alternate data streams and extended attribute differences.
696    #[arg(long)]
697    pub ignore_xattrs: bool,
698
699    /// Do not report untracked extra files present on disk that are absent from manifest or reference tree.
700    #[arg(long)]
701    pub ignore_untracked: bool,
702
703    /// Comma-separated list of metadata fields to ignore (e.g. atime,mtime,owner,perms,flags,xattrs,untracked).
704    #[arg(long, value_delimiter = ',')]
705    pub ignore: Vec<String>,
706
707    /// Verify in best-effort mode: tolerates timestamp precision differences
708    /// up to 2 seconds and ignores ownership mismatches if running unprivileged.
709    #[arg(long)]
710    pub best_effort: bool,
711
712    /// Enforce strictest verification settings, enabling --check-atime and --check-ctime.
713    #[arg(long)]
714    pub strict: bool,
715}
716
717impl VerificationCriteriaArgs {
718    #[must_use]
719    pub fn should_ignore_atime(&self) -> bool {
720        if self.strict || self.check_atime {
721            return false;
722        }
723        self.ignore_atime
724            || self.ignore.iter().any(|s| s.eq_ignore_ascii_case("atime"))
725    }
726
727    #[must_use]
728    pub fn should_ignore_mtime(&self) -> bool {
729        self.ignore_mtime
730            || self.ignore.iter().any(|s| s.eq_ignore_ascii_case("mtime"))
731    }
732
733    #[must_use]
734    pub fn should_ignore_ctime(&self) -> bool {
735        if self.strict || self.check_ctime {
736            return false;
737        }
738        self.ignore_ctime
739            || self.ignore.iter().any(|s| s.eq_ignore_ascii_case("ctime"))
740    }
741
742    #[must_use]
743    pub fn should_ignore_owner(&self) -> bool {
744        self.ignore_owner
745            || self.ignore.iter().any(|s| {
746                s.eq_ignore_ascii_case("owner")
747                    || s.eq_ignore_ascii_case("uid")
748                    || s.eq_ignore_ascii_case("gid")
749            })
750    }
751
752    #[must_use]
753    pub fn should_ignore_perms(&self) -> bool {
754        self.ignore_perms
755            || self.ignore.iter().any(|s| {
756                s.eq_ignore_ascii_case("perms")
757                    || s.eq_ignore_ascii_case("mode")
758                    || s.eq_ignore_ascii_case("permissions")
759            })
760    }
761
762    #[must_use]
763    pub fn should_ignore_flags(&self) -> bool {
764        self.ignore_flags
765            || self.ignore.iter().any(|s| s.eq_ignore_ascii_case("flags"))
766    }
767
768    #[must_use]
769    pub fn should_ignore_xattrs(&self) -> bool {
770        self.ignore_xattrs
771            || self.ignore.iter().any(|s| {
772                s.eq_ignore_ascii_case("xattrs")
773                    || s.eq_ignore_ascii_case("xattr")
774                    || s.eq_ignore_ascii_case("streams")
775            })
776    }
777
778    #[must_use]
779    pub fn should_ignore_untracked(&self) -> bool {
780        self.ignore_untracked
781            || self.ignore.iter().any(|s| {
782                s.eq_ignore_ascii_case("untracked")
783                    || s.eq_ignore_ascii_case("extra")
784            })
785    }
786
787    #[must_use]
788    pub fn should_drop_caches(&self) -> bool {
789        !self.no_drop_caches
790    }
791
792    /// Returns true if criteria are set to strictest possible settings.
793    #[must_use]
794    pub fn is_strict(&self) -> bool {
795        !self.should_ignore_atime()
796            && !self.should_ignore_ctime()
797            && !self.should_ignore_mtime()
798            && !self.should_ignore_owner()
799            && !self.should_ignore_perms()
800            && !self.should_ignore_flags()
801            && !self.should_ignore_xattrs()
802            && !self.should_ignore_untracked()
803            && !self.best_effort
804            && self.should_drop_caches()
805    }
806
807    /// Converts this set of criteria flags into `EntityAuditOptions`.
808    #[must_use]
809    pub fn to_audit_options(
810        &self,
811    ) -> ctb_io::file::verifier::EntityAuditOptions {
812        ctb_io::file::verifier::EntityAuditOptions {
813            ignore_atime: self.should_ignore_atime(),
814            ignore_mtime: self.should_ignore_mtime(),
815            ignore_ctime: self.should_ignore_ctime(),
816            check_birthtime: self.strict
817                || self.check_birthtime
818                || cfg!(windows),
819            ignore_owner: self.should_ignore_owner(),
820            ignore_perms: self.should_ignore_perms(),
821            ignore_flags: self.should_ignore_flags(),
822            ignore_xattrs: self.should_ignore_xattrs(),
823            check_sparse: true,
824            drop_caches: self.should_drop_caches(),
825            best_effort: if self.strict { false } else { self.best_effort },
826        }
827    }
828}
829
830/// Command-line arguments for `csc-verify`.
831#[derive(Parser, Debug, Clone)]
832#[command(
833    name = "csc-verify",
834    about = "Verifies a directory against a manifest created by csc, reporting all changed files and metadata differences"
835)]
836pub struct CscVerifyArgs {
837    /// Path to the manifest file (.cscjournal, .cscdesc, or .cscarchive) or directory containing state files.
838    #[arg(value_name = "MANIFEST")]
839    pub manifest: PathBuf,
840
841    /// Target directory to verify. If omitted, uses the destination path recorded
842    /// in the manifest. Specifying this allows verifying relocated folders or archives.
843    #[arg(value_name = "DIRECTORY")]
844    pub dir: Option<PathBuf>,
845
846    /// Target directory to verify (alias for positional DIRECTORY).
847    #[arg(long = "dir", value_name = "DIRECTORY", conflicts_with = "dir")]
848    pub dir_flag: Option<PathBuf>,
849
850    #[command(flatten)]
851    pub criteria: VerificationCriteriaArgs,
852
853    /// Output reporting format (`text` or `json`).
854    #[arg(long, value_enum, default_value_t = VerifyOutputFormat::Text)]
855    pub format: VerifyOutputFormat,
856
857    /// Only report discrepancies or errors, suppressing informational progress.
858    #[arg(short = 'q', long)]
859    pub quiet: bool,
860
861    /// Allow verifying against a manifest that failed, was aborted, or has not completed verification.
862    #[arg(
863        long = "allow-incomplete",
864        alias = "allow-failed",
865        alias = "allow-truncated",
866        default_value_t = false
867    )]
868    pub allow_incomplete: bool,
869
870    /// Record full provenance environment information using slow environment detection.
871    #[arg(long)]
872    pub full_provenance: bool,
873
874    /// Allow forgiving projection when reading state journals containing syntax or schema errors.
875    #[arg(long)]
876    pub allow_journal_errors: bool,
877}
878
879impl CscVerifyArgs {
880    /// Returns the projection policy to use when decoding state journals.
881    #[must_use]
882    pub const fn journal_projection_policy(
883        &self,
884    ) -> ctb_formats_dcstring::DcProjectionPolicy {
885        if self.allow_journal_errors {
886            ctb_formats_dcstring::DcProjectionPolicy::forgiving()
887        } else {
888            ctb_formats_dcstring::DcProjectionPolicy::strict()
889        }
890    }
891
892    #[must_use]
893    pub fn target_directory(&self) -> Option<&Path> {
894        self.dir.as_deref().or(self.dir_flag.as_deref())
895    }
896
897    #[must_use]
898    pub fn should_ignore_atime(&self) -> bool {
899        self.criteria.should_ignore_atime()
900    }
901
902    #[must_use]
903    pub fn should_ignore_mtime(&self) -> bool {
904        self.criteria.should_ignore_mtime()
905    }
906
907    #[must_use]
908    pub fn should_ignore_ctime(&self) -> bool {
909        self.criteria.should_ignore_ctime()
910    }
911
912    #[must_use]
913    pub fn should_ignore_owner(&self) -> bool {
914        self.criteria.should_ignore_owner()
915    }
916
917    #[must_use]
918    pub fn should_ignore_perms(&self) -> bool {
919        self.criteria.should_ignore_perms()
920    }
921
922    #[must_use]
923    pub fn should_ignore_flags(&self) -> bool {
924        self.criteria.should_ignore_flags()
925    }
926
927    #[must_use]
928    pub fn should_ignore_xattrs(&self) -> bool {
929        self.criteria.should_ignore_xattrs()
930    }
931
932    #[must_use]
933    pub fn should_ignore_untracked(&self) -> bool {
934        self.criteria.should_ignore_untracked()
935    }
936
937    #[must_use]
938    pub fn should_drop_caches(&self) -> bool {
939        self.criteria.should_drop_caches()
940    }
941
942    /// Returns true if verification is running in its strictest possible settings with no skipped or relaxed checks.
943    #[must_use]
944    pub fn is_strict(&self) -> bool {
945        self.criteria.is_strict()
946            && !self.allow_incomplete
947            && !self.allow_journal_errors
948    }
949
950    /// Converts this set of CLI verification flags into `EntityAuditOptions`.
951    #[must_use]
952    pub fn to_audit_options(
953        &self,
954    ) -> ctb_io::file::verifier::EntityAuditOptions {
955        self.criteria.to_audit_options()
956    }
957}
958
959impl std::ops::Deref for CscVerifyArgs {
960    type Target = VerificationCriteriaArgs;
961
962    fn deref(&self) -> &Self::Target {
963        &self.criteria
964    }
965}
966
967impl std::ops::DerefMut for CscVerifyArgs {
968    fn deref_mut(&mut self) -> &mut Self::Target {
969        &mut self.criteria
970    }
971}
972
973/// Command-line arguments for `csc-diff`.
974#[derive(Parser, Debug, Clone)]
975#[command(
976    name = "csc-diff",
977    about = "Compare two filesystem paths and report differences using the same logic and strictness as csc copy"
978)]
979pub struct CscDiffArgs {
980    /// First path to compare (reference).
981    #[arg(value_name = "PATH_A")]
982    pub path_a: PathBuf,
983
984    /// Second path to compare (target).
985    #[arg(value_name = "PATH_B")]
986    pub path_b: PathBuf,
987
988    #[command(flatten)]
989    pub criteria: VerificationCriteriaArgs,
990
991    /// Output reporting format (`text` or `json`).
992    #[arg(long, value_enum, default_value_t = VerifyOutputFormat::Text)]
993    pub format: VerifyOutputFormat,
994
995    /// Only report discrepancies or errors, suppressing informational progress.
996    #[arg(short = 'q', long)]
997    pub quiet: bool,
998
999    /// Verbose output showing each file compared.
1000    #[arg(short = 'v', long)]
1001    pub verbose: bool,
1002
1003    /// Stay on the current filesystem and do not cross mount boundaries.
1004    #[arg(short = 'x', long = "one-file-system")]
1005    pub one_file_system: bool,
1006
1007    /// Read AppleDouble companion files and join them into file entities.
1008    /// Defaults to `alongside` style if passed without a style.
1009    #[arg(
1010        long,
1011        value_name = "STYLE",
1012        num_args = 0..=1,
1013        default_missing_value = "alongside",
1014        require_equals = false
1015    )]
1016    pub read_apple_double: Option<AppleDoubleStyle>,
1017
1018    /// Read alongside (._<filename>) AppleDouble companion files.
1019    #[arg(long, overrides_with = "no_read_apple_double_alongside")]
1020    pub read_apple_double_alongside: bool,
1021
1022    /// Disable reading alongside (._<filename>) AppleDouble companion files.
1023    #[arg(long, overrides_with = "read_apple_double_alongside")]
1024    pub no_read_apple_double_alongside: bool,
1025
1026    /// Read __MACOSX/ directory AppleDouble companion files.
1027    #[arg(long)]
1028    pub read_apple_double_zip: bool,
1029
1030    /// Read Netatalk .AppleDouble companion files.
1031    #[arg(long)]
1032    pub read_apple_double_netatalk: bool,
1033
1034    /// Read AppleSingle files and decode data fork, resource fork, and Apple metadata.
1035    #[arg(long, overrides_with = "no_read_apple_single")]
1036    pub read_apple_single: bool,
1037
1038    /// Read bare AppleSingle files without extension (alias for --read-apple-single).
1039    #[arg(long, overrides_with = "no_read_apple_single")]
1040    pub read_apple_single_without_extension: bool,
1041
1042    /// Disable reading bare AppleSingle files without extension.
1043    #[arg(long, overrides_with = "read_apple_single")]
1044    pub no_read_apple_single: bool,
1045
1046    /// Read AppleSingle files with the specified extension ('as' or 'asf').
1047    #[arg(long, value_name = "EXT", action = clap::ArgAction::Append)]
1048    pub read_apple_single_with_extension: Vec<AppleSingleExtension>,
1049
1050    /// Read alongside `<filename>:<stream_name>` Windows alternate data stream companion files.
1051    #[arg(long, overrides_with = "no_read_windows_ads")]
1052    pub read_windows_ads: bool,
1053
1054    /// Disable reading alongside `<filename>:<stream_name>` Windows alternate data stream companion files.
1055    #[arg(long, overrides_with = "read_windows_ads")]
1056    pub no_read_windows_ads: bool,
1057
1058    /// Record full provenance environment information using slow environment detection.
1059    #[arg(long)]
1060    pub full_provenance: bool,
1061}
1062
1063impl CscDiffArgs {
1064    /// Resolves AppleSingle / AppleDouble / Windows ADS companion read options.
1065    #[must_use]
1066    pub fn resolve_apple_read_options(&self) -> AppleReadOptions {
1067        let mut opts = resolve_apple_read_options_from_flags(
1068            self.read_apple_double,
1069            self.read_apple_double_alongside,
1070            self.no_read_apple_double_alongside,
1071            self.read_apple_double_zip,
1072            self.read_apple_double_netatalk,
1073            self.read_apple_single,
1074            self.read_apple_single_without_extension,
1075            self.no_read_apple_single,
1076            &self.read_apple_single_with_extension,
1077        );
1078        opts.read_windows_ads_alongside =
1079            self.read_windows_ads && !self.no_read_windows_ads;
1080        opts
1081    }
1082
1083    /// Converts this set of CLI verification flags into `EntityAuditOptions`.
1084    #[must_use]
1085    pub fn to_audit_options(
1086        &self,
1087    ) -> ctb_io::file::verifier::EntityAuditOptions {
1088        self.criteria.to_audit_options()
1089    }
1090
1091    #[must_use]
1092    pub fn should_drop_caches(&self) -> bool {
1093        self.criteria.should_drop_caches()
1094    }
1095
1096    #[must_use]
1097    pub fn should_ignore_untracked(&self) -> bool {
1098        self.criteria.should_ignore_untracked()
1099    }
1100}
1101
1102impl std::ops::Deref for CscDiffArgs {
1103    type Target = VerificationCriteriaArgs;
1104
1105    fn deref(&self) -> &Self::Target {
1106        &self.criteria
1107    }
1108}
1109
1110impl std::ops::DerefMut for CscDiffArgs {
1111    fn deref_mut(&mut self) -> &mut Self::Target {
1112        &mut self.criteria
1113    }
1114}
1115
1116/// Command-line arguments for `fsindex`.
1117#[derive(Parser, Debug, Clone)]
1118#[command(
1119    name = "fsindex",
1120    about = "Indexes directories into resumable .cscjournal state files and compiles them into Turso SQLite databases"
1121)]
1122pub struct FsindexArgs {
1123    /// Target directory or .cscjournal file(s) to index.
1124    #[arg(value_name = "PATH", num_args = 0..)]
1125    pub targets: Vec<PathBuf>,
1126
1127    /// Target database path (*.cscindex.sqlite). If the database exists, new journals will be appended (appended).
1128    #[arg(short = 'd', long = "db", value_name = "DATABASE")]
1129    pub database: Option<PathBuf>,
1130
1131    /// Explicit path for the state journal file (.cscjournal).
1132    #[arg(
1133        long = "journal-path",
1134        alias = "journal",
1135        value_name = "JOURNAL_PATH"
1136    )]
1137    pub journal_path: Option<PathBuf>,
1138
1139    /// Flush deleted files that no longer exist on disk from the database index.
1140    #[arg(long = "flush-deleted")]
1141    pub flush_deleted: bool,
1142
1143    /// Override the source name tag stored in the database (default: journal basename without extension).
1144    #[arg(short = 's', long = "source-name")]
1145    pub source_name: Option<String>,
1146
1147    /// Resume an interrupted directory indexing session from an existing journal.
1148    #[arg(long)]
1149    pub resume: bool,
1150
1151    /// Explicit path to a journal file when resuming.
1152    #[arg(long, value_name = "JOURNAL")]
1153    pub resume_journal: Option<PathBuf>,
1154
1155    /// Compute cryptographic SHA-256 digests for file contents (slow on large filesystems; default is metadata-only).
1156    #[arg(long)]
1157    pub checksum: bool,
1158
1159    /// Only generate the *.cscjournal file; do not compile into SQLite database.
1160    #[arg(long)]
1161    pub journal_only: bool,
1162
1163    /// Number of entries to commit per transaction batch during traversal and ingestion.
1164    #[arg(long, default_value_t = 500)]
1165    pub batch_size: usize,
1166
1167    /// Suppress progress output.
1168    #[arg(short = 'q', long)]
1169    pub quiet: bool,
1170
1171    /// Stay on the current filesystem and do not cross mount boundaries.
1172    #[arg(short = 'x', long = "one-file-system")]
1173    pub one_file_system: bool,
1174
1175    /// Extract and index file contents for full-text search.
1176    #[arg(long = "fulltext")]
1177    pub fulltext: bool,
1178
1179    /// Maximum file size to extract for full-text indexing (e.g. "20k", "64k", "1M"). Defaults to 20k.
1180    #[arg(long = "fulltext-max", default_value = "20k", value_name = "SIZE")]
1181    pub fulltext_max: String,
1182
1183    /// Password-protect the SQLite index using Turso native page-level encryption (aegis256) and store metadata in *.cscidxmeta.
1184    #[arg(long = "encrypt", alias = "password-protect")]
1185    pub encrypt: bool,
1186
1187    /// Read password from the specified file instead of prompting.
1188    #[arg(long = "password-file", value_name = "FILE")]
1189    pub password_file: Option<PathBuf>,
1190
1191    /// Read password from standard input instead of prompting.
1192    #[arg(long = "password-stdin")]
1193    pub password_stdin: bool,
1194
1195    /// Record full provenance environment information using slow environment detection
1196    /// (e.g. network discovery for public IP addresses and server time synchronization).
1197    #[arg(long)]
1198    pub full_provenance: bool,
1199
1200    /// Allow forgiving projection when reading state journals containing syntax or schema errors.
1201    #[arg(long)]
1202    pub allow_journal_errors: bool,
1203}
1204
1205impl FsindexArgs {
1206    /// Returns the projection policy to use when decoding state journals.
1207    #[must_use]
1208    pub const fn journal_projection_policy(
1209        &self,
1210    ) -> ctb_formats_dcstring::DcProjectionPolicy {
1211        if self.allow_journal_errors {
1212            ctb_formats_dcstring::DcProjectionPolicy::forgiving()
1213        } else {
1214            ctb_formats_dcstring::DcProjectionPolicy::strict()
1215        }
1216    }
1217}
1218
1219/// Output format for search results.
1220#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, ValueEnum)]
1221pub enum SearchOutputFormat {
1222    /// Locate-style path list (one path per line).
1223    #[default]
1224    Path,
1225    /// Detailed long listing (permissions, size, mtime, source, path).
1226    Long,
1227    /// JSON output for scripting.
1228    Json,
1229}
1230
1231/// Field to sort search results by.
1232#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, ValueEnum)]
1233pub enum SearchSortField {
1234    #[default]
1235    Path,
1236    Name,
1237    Mtime,
1238    Ctime,
1239    Size,
1240}
1241
1242/// Command-line arguments for `fsearch`.
1243#[derive(Parser, Debug, Clone)]
1244#[command(
1245    name = "fsearch",
1246    about = "Performs fast indexed searches against a .cscindex.sqlite database"
1247)]
1248pub struct FsearchArgs {
1249    /// Path to the *.cscindex.sqlite database file.
1250    #[arg(value_name = "DATABASE")]
1251    pub database: PathBuf,
1252
1253    /// Search pattern or terms (matched as glob if contains '*', substring if single term, or keyword search if multiple terms).
1254    #[arg(value_name = "QUERY", num_args = 0..)]
1255    pub query: Vec<String>,
1256
1257    /// Regular expression pattern to match against path and filename (shorthand: -rp, --rp). Does not require delimiters.
1258    #[arg(
1259        long = "regex-path",
1260        visible_alias = "rp",
1261        alias = "rp",
1262        conflicts_with = "query"
1263    )]
1264    pub regex_path: Option<String>,
1265
1266    /// Regular expression pattern to match against path, filename, and full text content (shorthand: -rt, --rt). Does not require delimiters.
1267    #[arg(
1268        long = "regex-text",
1269        visible_alias = "rt",
1270        alias = "rt",
1271        conflicts_with = "query"
1272    )]
1273    pub regex_text: Option<String>,
1274
1275    /// Regular expression pattern to match against filename only (shorthand: -rn, --rn). Does not require delimiters.
1276    #[arg(
1277        long = "regex-name",
1278        visible_alias = "rn",
1279        alias = "rn",
1280        conflicts_with = "query"
1281    )]
1282    pub regex_name: Option<String>,
1283
1284    /// Glob pattern to match against relative path and filename (shorthand: -gp, --gp).
1285    #[arg(
1286        long = "glob-path",
1287        visible_alias = "gp",
1288        alias = "gp",
1289        conflicts_with = "query"
1290    )]
1291    pub glob_path: Option<String>,
1292
1293    /// Glob pattern to match against relative path, filename, and full text content (shorthand: -gt, --gt).
1294    #[arg(
1295        long = "glob-text",
1296        visible_alias = "gt",
1297        alias = "gt",
1298        conflicts_with = "query"
1299    )]
1300    pub glob_text: Option<String>,
1301
1302    /// Glob pattern to match against filename only (shorthand: -gn, --gn).
1303    #[arg(
1304        long = "glob-name",
1305        visible_alias = "gn",
1306        alias = "gn",
1307        conflicts_with = "query"
1308    )]
1309    pub glob_name: Option<String>,
1310
1311    /// Keyword match across relative path and filename (shorthand: -kp, --kp).
1312    #[arg(
1313        long = "keyword-path",
1314        visible_alias = "kp",
1315        alias = "kp",
1316        conflicts_with = "query"
1317    )]
1318    pub keyword_path: Option<String>,
1319
1320    /// Keyword match across relative path, filename, and full text content (shorthand: -kt, --kt).
1321    #[arg(
1322        long = "keyword-text",
1323        visible_alias = "kt",
1324        alias = "kt",
1325        conflicts_with = "query"
1326    )]
1327    pub keyword_text: Option<String>,
1328
1329    /// Keyword match on filename only (shorthand: -kn, --kn).
1330    #[arg(
1331        long = "keyword-name",
1332        visible_alias = "kn",
1333        alias = "kn",
1334        conflicts_with = "query"
1335    )]
1336    pub keyword_name: Option<String>,
1337
1338    /// Substring pattern to match against relative path and filename (shorthand: -sp, --sp).
1339    #[arg(
1340        long = "substring-path",
1341        visible_alias = "sp",
1342        alias = "sp",
1343        conflicts_with = "query"
1344    )]
1345    pub substring_path: Option<String>,
1346
1347    /// Substring pattern to match against relative path, filename, and full text content (shorthand: -st, --st).
1348    #[arg(
1349        long = "substring-text",
1350        visible_alias = "st",
1351        alias = "st",
1352        conflicts_with = "query"
1353    )]
1354    pub substring_text: Option<String>,
1355
1356    /// Substring pattern to match against filename only (shorthand: -sn, --sn).
1357    #[arg(
1358        long = "substring-name",
1359        visible_alias = "sn",
1360        alias = "sn",
1361        conflicts_with = "query"
1362    )]
1363    pub substring_name: Option<String>,
1364
1365    /// Print n lines around first match of full text.
1366    #[arg(short = 'C', long = "context")]
1367    pub context: Option<usize>,
1368
1369    /// Glob pattern to match against filename (e.g. "*.rs", "*test*"). Legacy alias for --glob-name.
1370    #[arg(short = 'n', long = "name", conflicts_with = "query")]
1371    pub name_glob: Option<String>,
1372
1373    /// Glob pattern to match against relative path (e.g. "src/**/tests.rs"). Alias for --glob-path.
1374    #[arg(short = 'p', long = "path", conflicts_with = "query")]
1375    pub path_glob: Option<String>,
1376
1377    /// One or more keyword terms to match in path or filename. Alias for --keyword-path.
1378    #[arg(
1379        short = 'k',
1380        long = "keyword",
1381        num_args = 1..,
1382        conflicts_with = "query"
1383    )]
1384    pub keyword: Vec<String>,
1385
1386    /// Regular expression pattern to match against path (alias for --regex-path). Does not require delimiters.
1387    #[arg(short = 'r', long = "regex", conflicts_with = "query")]
1388    pub regex: Option<String>,
1389
1390    /// Filter by source name tag.
1391    #[arg(short = 's', long = "source")]
1392    pub source: Option<String>,
1393
1394    /// Filter entries modified on or after this Unix timestamp or relative duration (e.g. "1725600000", "7d", "24h").
1395    #[arg(long = "mtime-after")]
1396    pub mtime_after: Option<String>,
1397
1398    /// Filter entries modified on or before this Unix timestamp or relative duration.
1399    #[arg(long = "mtime-before")]
1400    pub mtime_before: Option<String>,
1401
1402    /// Filter entries changed on or after this Unix timestamp or relative duration.
1403    #[arg(long = "ctime-after")]
1404    pub ctime_after: Option<String>,
1405
1406    /// Filter entries changed on or before this Unix timestamp or relative duration.
1407    #[arg(long = "ctime-before")]
1408    pub ctime_before: Option<String>,
1409
1410    /// Minimum file size in bytes (or suffix like 10k, 5M, 1G).
1411    #[arg(long = "size-min")]
1412    pub size_min: Option<String>,
1413
1414    /// Maximum file size in bytes (or suffix like 10k, 5M, 1G).
1415    #[arg(long = "size-max")]
1416    pub size_max: Option<String>,
1417
1418    /// Filter by entity type ('f' or 'file', 'd' or 'dir', 'l' or 'symlink').
1419    #[arg(short = 't', long = "type")]
1420    pub entry_type: Option<String>,
1421
1422    /// Field to sort results by.
1423    #[arg(long, value_enum, default_value_t = SearchSortField::Path)]
1424    pub sort: SearchSortField,
1425
1426    /// Sort in descending order.
1427    #[arg(long = "desc")]
1428    pub sort_desc: bool,
1429
1430    /// Maximum number of search results to return.
1431    #[arg(short = 'l', long = "limit")]
1432    pub limit: Option<usize>,
1433
1434    /// Output formatting mode (`path`, `long`, or `json`).
1435    #[arg(long, value_enum, default_value_t = SearchOutputFormat::Path)]
1436    pub format: SearchOutputFormat,
1437
1438    /// Read password from the specified file when querying an encrypted index.
1439    #[arg(long = "password-file", value_name = "FILE")]
1440    pub password_file: Option<PathBuf>,
1441
1442    /// Read password from standard input when querying an encrypted index.
1443    #[arg(long = "password-stdin")]
1444    pub password_stdin: bool,
1445}
1446
1447/// Command-line arguments for the `mv` command.
1448#[derive(Parser, Debug, Clone, Default)]
1449#[command(
1450    name = "mv",
1451    about = "Move files without copying when possible, or run verified cross-device copy",
1452    long_about = "Move files or directories. Attempts atomic O(1) rename on the same filesystem. If moving across filesystems (EXDEV), falls back to verified checksummed copying and only unlinks source files upon successful verification."
1453)]
1454pub struct MvArgs {
1455    /// Source path(s) followed by target destination path.
1456    #[arg(value_name = "PATHS", required_unless_present = "resume", num_args = 2..)]
1457    pub paths: Vec<PathBuf>,
1458
1459    /// Path to a state file (.cscjournal or .cscdesc) from which to resume an
1460    /// interrupted move.
1461    #[arg(long, value_name = "STATE_FILE")]
1462    pub resume: Option<PathBuf>,
1463
1464    /// Explicit path for the state journal file (.cscjournal).
1465    #[arg(
1466        long = "journal-path",
1467        alias = "journal",
1468        value_name = "JOURNAL_PATH"
1469    )]
1470    pub journal_path: Option<PathBuf>,
1471
1472    /// Directory in which to store state files when cross-device copy occurs.
1473    #[arg(long, value_name = "DIR")]
1474    pub state_dir: Option<PathBuf>,
1475
1476    /// Enable verbose diagnostic output.
1477    #[arg(short, long)]
1478    pub verbose: bool,
1479
1480    /// Display real-time progress indicators (default: enabled when standard
1481    /// error is connected to an interactive terminal).
1482    #[arg(long, overrides_with = "no_progress")]
1483    pub progress: bool,
1484
1485    /// Disable progress display unconditionally.
1486    #[arg(long, overrides_with = "progress")]
1487    pub no_progress: bool,
1488
1489    /// Recalculate checksums after flushing OS caches when cross-device copy occurs (default: enabled).
1490    #[arg(long, default_value_t = true, overrides_with = "no_verify_after")]
1491    pub verify_after: bool,
1492
1493    /// Skip the post-flush verification pass on cross-device moves.
1494    #[arg(long, overrides_with = "verify_after")]
1495    pub no_verify_after: bool,
1496
1497    /// Relax strict metadata requirements when cross-device copy occurs.
1498    #[arg(long)]
1499    pub best_effort_metadata: bool,
1500
1501    /// Allow operation even if the filesystem type cannot be detected.
1502    #[arg(long)]
1503    pub allow_unknown_fs: bool,
1504
1505    /// Force overwrite destination without prompt (accepted for mv compatibility).
1506    #[arg(short = 'f', long = "force")]
1507    pub force: bool,
1508
1509    /// Perform a dry run without moving or deleting files.
1510    #[arg(short = 'n', long)]
1511    pub dry_run: bool,
1512
1513    /// Record full provenance environment information using slow environment detection
1514    /// when falling back to verified copy.
1515    #[arg(long)]
1516    pub full_provenance: bool,
1517}
1518
1519impl MvArgs {
1520    /// Resolves whether progress display is active.
1521    ///
1522    /// Respects `--no-progress` (disabled) and `--progress` (forced enabled),
1523    /// falling back to whether standard error is connected to an interactive
1524    /// terminal.
1525    #[must_use]
1526    pub fn should_show_progress(&self) -> bool {
1527        should_show_progress(self.progress, self.no_progress)
1528    }
1529
1530    /// Resolves whether post-flush verification is active.
1531    #[must_use]
1532    pub fn should_verify_after(&self) -> bool {
1533        if self.no_verify_after {
1534            false
1535        } else {
1536            self.verify_after
1537        }
1538    }
1539}
1540#[cfg(test)]
1541pub(crate) fn default_test_args(
1542    paths: Vec<PathBuf>,
1543    state_dir: PathBuf,
1544) -> CscArgs {
1545    CscArgs {
1546        paths,
1547        resume: None,
1548        journal_path: None,
1549        state_dir: Some(state_dir),
1550        verbose: true,
1551        progress: false,
1552        no_progress: true,
1553        verify_after: true,
1554        no_verify_after: false,
1555        overwrite: false,
1556        on_source_change: crate::args::SourceChangePolicy::Error,
1557        copy_specials_as_specials: false,
1558        copy_block_devices_as_regular_files: false,
1559        copy_fifos_as_regular_files: false,
1560        one_file_system: false,
1561        best_effort_metadata: false,
1562        allow_unknown_fs: true,
1563        check_atime: false,
1564        check_ctime: false,
1565        check_birthtime: false,
1566        strict: false,
1567        delete_manifest_after: false,
1568        recursive: true,
1569        archive: true,
1570        dry_run: false,
1571        read_apple_double: None,
1572        read_apple_double_alongside: false,
1573        no_read_apple_double_alongside: false,
1574        read_apple_double_zip: false,
1575        read_apple_double_netatalk: false,
1576        read_apple_single: false,
1577        read_apple_single_without_extension: false,
1578        no_read_apple_single: false,
1579        read_apple_single_with_extension: Vec::new(),
1580        maybe_write_apple_double: None,
1581        force_write_apple_double: None,
1582        maybe_write_apple_single: false,
1583        force_write_apple_single: false,
1584        write_apple_single_with_extension: None,
1585        write_apple_single_without_extension: false,
1586        read_windows_ads: false,
1587        no_read_windows_ads: false,
1588        maybe_write_windows_ads: false,
1589        force_write_windows_ads: false,
1590        full_provenance: false,
1591        continue_on_error: false,
1592        allow_journal_errors: false,
1593    }
1594}
1595
1596#[cfg(test)]
1597pub(crate) fn default_verify_args(
1598    manifest: PathBuf,
1599    dir: Option<PathBuf>,
1600) -> CscVerifyArgs {
1601    CscVerifyArgs {
1602        manifest,
1603        dir,
1604        dir_flag: None,
1605        criteria: VerificationCriteriaArgs {
1606            no_drop_caches: true,
1607            ignore_atime: true,
1608            check_atime: false,
1609            ignore_mtime: false,
1610            ignore_ctime: true,
1611            check_ctime: false,
1612            check_birthtime: false,
1613            ignore_owner: true,
1614            ignore_perms: false,
1615            ignore_flags: true,
1616            ignore_xattrs: false,
1617            ignore_untracked: false,
1618            ignore: Vec::new(),
1619            best_effort: true,
1620            strict: false,
1621        },
1622        format: VerifyOutputFormat::Text,
1623        quiet: false,
1624        allow_incomplete: false,
1625        full_provenance: false,
1626        allow_journal_errors: false,
1627    }
1628}
1629
1630#[cfg(test)]
1631pub(crate) fn default_diff_args(
1632    path_a: PathBuf,
1633    path_b: PathBuf,
1634) -> CscDiffArgs {
1635    CscDiffArgs {
1636        path_a,
1637        path_b,
1638        criteria: VerificationCriteriaArgs {
1639            no_drop_caches: true,
1640            ignore_atime: true,
1641            check_atime: false,
1642            ignore_mtime: false,
1643            ignore_ctime: true,
1644            check_ctime: false,
1645            check_birthtime: false,
1646            ignore_owner: false,
1647            ignore_perms: false,
1648            ignore_flags: false,
1649            ignore_xattrs: false,
1650            ignore_untracked: false,
1651            ignore: Vec::new(),
1652            best_effort: false,
1653            strict: false,
1654        },
1655        format: VerifyOutputFormat::Text,
1656        quiet: false,
1657        verbose: false,
1658        one_file_system: false,
1659        read_apple_double: None,
1660        read_apple_double_alongside: false,
1661        no_read_apple_double_alongside: false,
1662        read_apple_double_zip: false,
1663        read_apple_double_netatalk: false,
1664        read_apple_single: false,
1665        read_apple_single_without_extension: false,
1666        no_read_apple_single: false,
1667        read_apple_single_with_extension: Vec::new(),
1668        read_windows_ads: false,
1669        no_read_windows_ads: false,
1670        full_provenance: false,
1671    }
1672}
1673
1674#[cfg(test)]
1675pub(crate) fn default_fsindex_args(
1676    targets: Vec<PathBuf>,
1677    database: Option<PathBuf>,
1678) -> crate::args::FsindexArgs {
1679    crate::args::FsindexArgs {
1680        targets,
1681        database,
1682        journal_path: None,
1683        flush_deleted: false,
1684        source_name: None,
1685        resume: false,
1686        resume_journal: None,
1687        checksum: false,
1688        journal_only: false,
1689        batch_size: 50,
1690        quiet: true,
1691        one_file_system: false,
1692        fulltext: false,
1693        fulltext_max: "20k".to_string(),
1694        encrypt: false,
1695        password_file: None,
1696        password_stdin: false,
1697        full_provenance: false,
1698        allow_journal_errors: false,
1699    }
1700}
1701
1702#[cfg(test)]
1703pub(crate) fn default_fsearch_args(
1704    database: PathBuf,
1705) -> crate::args::FsearchArgs {
1706    crate::args::FsearchArgs {
1707        database,
1708        query: Vec::new(),
1709        regex_path: None,
1710        regex_text: None,
1711        regex_name: None,
1712        glob_path: None,
1713        glob_text: None,
1714        glob_name: None,
1715        keyword_path: None,
1716        keyword_text: None,
1717        keyword_name: None,
1718        substring_path: None,
1719        substring_text: None,
1720        substring_name: None,
1721        context: None,
1722        name_glob: None,
1723        path_glob: None,
1724        keyword: Vec::new(),
1725        regex: None,
1726        source: None,
1727        mtime_after: None,
1728        mtime_before: None,
1729        ctime_after: None,
1730        ctime_before: None,
1731        size_min: None,
1732        size_max: None,
1733        entry_type: None,
1734        sort: crate::args::SearchSortField::Path,
1735        sort_desc: false,
1736        limit: None,
1737        format: crate::args::SearchOutputFormat::Path,
1738        password_file: None,
1739        password_stdin: false,
1740    }
1741}
1742
1743#[cfg(test)]
1744#[allow(
1745    clippy::panic,
1746    clippy::expect_used,
1747    clippy::unwrap_used,
1748    clippy::unwrap_in_result,
1749    clippy::panic_in_result_fn,
1750    clippy::indexing_slicing,
1751    clippy::arithmetic_side_effects,
1752    reason = "Standard repository test boilerplate"
1753)]
1754mod tests {
1755    use super::*;
1756    use crate::args::{
1757        AppleDoubleStyle, CscArgs, CscVerifyArgs, MvArgs, default_test_args,
1758    };
1759    use crate::cli::run_csc;
1760    use std::fs;
1761    use std::path::PathBuf;
1762    use tempfile::tempdir;
1763
1764    #[crate::ctb_test]
1765    fn test_csc_overwrite_argument() {
1766        use clap::Parser;
1767
1768        assert!(
1769            !CscArgs::try_parse_from(["csc", "src", "dest"])
1770                .unwrap()
1771                .overwrite
1772        );
1773        assert!(
1774            CscArgs::try_parse_from(["csc", "--overwrite", "src", "dest"])
1775                .unwrap()
1776                .overwrite
1777        );
1778        assert!(
1779            CscArgs::try_parse_from([
1780                "csc",
1781                "--always-overwrite",
1782                "src",
1783                "dest"
1784            ])
1785            .is_err()
1786        );
1787    }
1788
1789    #[crate::ctb_test]
1790    fn test_strict_error_on_altered_filename() {
1791        use ctb_io::file::verify_filename_exact_bytes;
1792
1793        let temp = tempdir().expect("create tempdir");
1794        let test_file = temp.path().join("original_name.txt");
1795        fs::write(&test_file, b"data").expect("write test file");
1796
1797        // Verify that matching bytes succeed
1798        assert!(
1799            verify_filename_exact_bytes(temp.path(), b"original_name.txt")
1800                .is_ok()
1801        );
1802
1803        // Verify that altered, stripped, or normalized bytes fail with error
1804        let err =
1805            verify_filename_exact_bytes(temp.path(), b"Original_Name.txt");
1806        assert!(
1807            err.is_err(),
1808            "Expected error when filename bytes do not match exactly"
1809        );
1810    }
1811
1812    #[crate::ctb_test]
1813    fn test_csc_and_mv_progress_resolution() {
1814        use clap::Parser;
1815
1816        // Default without flags: neither progress nor no_progress
1817        let args = CscArgs::try_parse_from(["csc", "src", "dest"]).unwrap();
1818        assert!(!args.progress);
1819        assert!(!args.no_progress);
1820        // Fallback matches stderr interactivity
1821        assert_eq!(
1822            args.should_show_progress(),
1823            ctb_utilities::cli::is_stderr_interactive()
1824        );
1825
1826        // Explicit --progress
1827        let args =
1828            CscArgs::try_parse_from(["csc", "--progress", "src", "dest"])
1829                .unwrap();
1830        assert!(args.progress);
1831        assert!(!args.no_progress);
1832        assert!(args.should_show_progress());
1833
1834        // Explicit --no-progress
1835        let args =
1836            CscArgs::try_parse_from(["csc", "--no-progress", "src", "dest"])
1837                .unwrap();
1838        assert!(!args.progress);
1839        assert!(args.no_progress);
1840        assert!(!args.should_show_progress());
1841
1842        // Overrides: later flag wins
1843        let args = CscArgs::try_parse_from([
1844            "csc",
1845            "--progress",
1846            "--no-progress",
1847            "src",
1848            "dest",
1849        ])
1850        .unwrap();
1851        assert!(!args.progress);
1852        assert!(args.no_progress);
1853        assert!(!args.should_show_progress());
1854
1855        let args = CscArgs::try_parse_from([
1856            "csc",
1857            "--no-progress",
1858            "--progress",
1859            "src",
1860            "dest",
1861        ])
1862        .unwrap();
1863        assert!(args.progress);
1864        assert!(!args.no_progress);
1865        assert!(args.should_show_progress());
1866
1867        // Same verification for MvArgs
1868        let mv_args = MvArgs::try_parse_from(["mv", "src", "dest"]).unwrap();
1869        assert!(!mv_args.progress);
1870        assert!(!mv_args.no_progress);
1871        assert_eq!(
1872            mv_args.should_show_progress(),
1873            ctb_utilities::cli::is_stderr_interactive()
1874        );
1875
1876        let mv_args =
1877            MvArgs::try_parse_from(["mv", "--progress", "src", "dest"])
1878                .unwrap();
1879        assert!(mv_args.should_show_progress());
1880
1881        let mv_args =
1882            MvArgs::try_parse_from(["mv", "--no-progress", "src", "dest"])
1883                .unwrap();
1884        assert!(!mv_args.should_show_progress());
1885    }
1886
1887    #[crate::ctb_test]
1888    fn test_strict_flags_parsing() {
1889        use clap::Parser;
1890
1891        let verify_args = CscVerifyArgs::try_parse_from([
1892            "csc-verify",
1893            "--strict",
1894            "manifest.cscjournal",
1895        ])
1896        .unwrap();
1897        assert!(verify_args.strict);
1898        assert!(!verify_args.should_ignore_atime());
1899        assert!(!verify_args.should_ignore_ctime());
1900        assert!(verify_args.is_strict());
1901
1902        let csc_args =
1903            CscArgs::try_parse_from(["csc", "--strict", "src", "dest"])
1904                .unwrap();
1905        assert!(csc_args.strict);
1906        assert!(csc_args.should_check_atime());
1907        assert!(csc_args.should_check_ctime());
1908        assert!(csc_args.should_check_birthtime());
1909        assert!(verify_args.to_audit_options().check_birthtime);
1910
1911        let csc_args_ctime =
1912            CscArgs::try_parse_from(["csc", "--check-ctime", "src", "dest"])
1913                .unwrap();
1914        assert!(csc_args_ctime.check_ctime);
1915        assert!(csc_args_ctime.should_check_ctime());
1916        assert!(!csc_args_ctime.should_check_atime());
1917
1918        let normal = CscArgs::try_parse_from(["csc", "src", "dest"]).unwrap();
1919        assert!(!normal.best_effort_metadata);
1920        assert!(!normal.strict);
1921        assert_eq!(
1922            normal.resolve_apple_read_options(),
1923            ctb_io::file::AppleReadOptions::default(),
1924            "All read-apple* and read-windows-ads options must be off by default"
1925        );
1926        assert!(
1927            !normal
1928                .resolve_apple_read_options()
1929                .read_apple_double_alongside
1930        );
1931        assert!(
1932            !normal
1933                .resolve_apple_read_options()
1934                .read_windows_ads_alongside
1935        );
1936        assert_eq!(normal.should_check_birthtime(), cfg!(windows));
1937        let birthtime = CscArgs::try_parse_from([
1938            "csc",
1939            "--check-birthtime",
1940            "src",
1941            "dest",
1942        ])
1943        .unwrap();
1944        assert!(birthtime.should_check_birthtime());
1945        assert!(!birthtime.should_check_atime());
1946        let permissive = CscVerifyArgs::try_parse_from([
1947            "csc-verify",
1948            "--strict",
1949            "--best-effort",
1950            "manifest.cscjournal",
1951        ])
1952        .unwrap();
1953        let audit = permissive.to_audit_options();
1954        assert!(!audit.best_effort);
1955        assert!(
1956            !audit.ignore_atime && !audit.ignore_ctime && audit.check_birthtime
1957        );
1958    }
1959
1960    #[crate::ctb_test]
1961    fn test_csc_apple_write_mode_mutual_exclusion() {
1962        let temp = tempdir().expect("tempdir");
1963        let src = temp.path().join("src");
1964        let dest = temp.path().join("dest");
1965        let state = temp.path().join("state");
1966        fs::create_dir_all(&src).unwrap();
1967        fs::write(src.join("a.txt"), b"data").unwrap();
1968
1969        let mut args = default_test_args(vec![src, dest], state);
1970        args.force_write_apple_double = Some(AppleDoubleStyle::Alongside);
1971        args.force_write_apple_single = true;
1972
1973        let res = run_csc(args);
1974        assert!(
1975            res.is_err(),
1976            "Expected mutual exclusion error when multiple write modes specified"
1977        );
1978    }
1979
1980    #[crate::ctb_test]
1981    fn test_csc_best_effort_metadata_enables_maybe_apple_double() {
1982        let temp = tempdir().expect("tempdir");
1983        let src = temp.path().join("src");
1984        let dest = temp.path().join("dest");
1985        let state = temp.path().join("state");
1986
1987        let mut args = default_test_args(vec![src, dest], state);
1988        args.best_effort_metadata = true;
1989        let (mode, _ext) =
1990            args.resolve_apple_write_mode().expect("resolve mode");
1991        assert_eq!(
1992            mode,
1993            ctb_io::file::AppleWriteMode::MaybeAppleDouble(
1994                AppleDoubleStyle::Alongside
1995            )
1996        );
1997    }
1998
1999    #[crate::ctb_test]
2000    fn test_csc_write_apple_single_with_extension_as() {
2001        let temp = tempdir().expect("tempdir");
2002        let src = temp.path().join("src");
2003        let dest = temp.path().join("dest");
2004        let state = temp.path().join("state");
2005        fs::create_dir_all(&src).unwrap();
2006        fs::create_dir_all(&state).unwrap();
2007        fs::write(src.join("sample.txt"), b"AppleSingle with .as").unwrap();
2008
2009        let mut args = default_test_args(
2010            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
2011            state,
2012        );
2013        args.force_write_apple_single = true;
2014        args.write_apple_single_with_extension =
2015            Some(ctb_io::file::AppleSingleExtension::As);
2016
2017        let res = run_csc(args).expect("run csc");
2018        match res {
2019            ctb_utilities::cli::ToolResult::Immediate { exit_code, .. } => {
2020                assert_eq!(exit_code, 0);
2021            }
2022            _ => panic!("Expected immediate result"),
2023        }
2024
2025        assert!(
2026            dest.join("sample.txt.as").exists(),
2027            "sample.txt.as must exist"
2028        );
2029        assert!(
2030            !dest.join("sample.txt").exists(),
2031            "bare sample.txt must not exist"
2032        );
2033
2034        let data = fs::read(dest.join("sample.txt.as")).unwrap();
2035        let archive = ctb_io::file::read_apple_single_double(&data)
2036            .expect("parse AppleSingle");
2037        assert_eq!(archive.format, ctb_io::file::AppleFormat::AppleSingle);
2038        assert_eq!(
2039            archive.data_fork.as_deref(),
2040            Some(&b"AppleSingle with .as"[..])
2041        );
2042    }
2043
2044    #[crate::ctb_test]
2045    fn test_csc_write_apple_single_with_extension_asf() {
2046        let temp = tempdir().expect("tempdir");
2047        let src = temp.path().join("src");
2048        let dest = temp.path().join("dest");
2049        let state = temp.path().join("state");
2050        fs::create_dir_all(&src).unwrap();
2051        fs::create_dir_all(&state).unwrap();
2052        fs::write(src.join("sample.txt"), b"AppleSingle with .asf").unwrap();
2053
2054        let mut args = default_test_args(
2055            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
2056            state,
2057        );
2058        args.force_write_apple_single = true;
2059        args.write_apple_single_with_extension =
2060            Some(ctb_io::file::AppleSingleExtension::Asf);
2061
2062        let res = run_csc(args).expect("run csc");
2063        match res {
2064            ctb_utilities::cli::ToolResult::Immediate { exit_code, .. } => {
2065                assert_eq!(exit_code, 0);
2066            }
2067            _ => panic!("Expected immediate result"),
2068        }
2069
2070        assert!(
2071            dest.join("sample.txt.asf").exists(),
2072            "sample.txt.asf must exist"
2073        );
2074        assert!(
2075            !dest.join("sample.txt").exists(),
2076            "bare sample.txt must not exist"
2077        );
2078
2079        let data = fs::read(dest.join("sample.txt.asf")).unwrap();
2080        let archive = ctb_io::file::read_apple_single_double(&data)
2081            .expect("parse AppleSingle");
2082        assert_eq!(archive.format, ctb_io::file::AppleFormat::AppleSingle);
2083        assert_eq!(
2084            archive.data_fork.as_deref(),
2085            Some(&b"AppleSingle with .asf"[..])
2086        );
2087    }
2088
2089    #[crate::ctb_test]
2090    fn test_csc_continue_on_error_args_parsing() {
2091        use clap::Parser;
2092        let parsed = CscArgs::try_parse_from([
2093            "csc",
2094            "src",
2095            "dest",
2096            "--continue-on-error",
2097        ])
2098        .unwrap();
2099        assert!(parsed.continue_on_error);
2100
2101        let parsed_alias =
2102            CscArgs::try_parse_from(["csc", "src", "dest", "--ignore-errors"])
2103                .unwrap();
2104        assert!(parsed_alias.continue_on_error);
2105
2106        let default_parsed =
2107            CscArgs::try_parse_from(["csc", "src", "dest"]).unwrap();
2108        assert!(!default_parsed.continue_on_error);
2109    }
2110}