ctb_io_csc/
copy_engine.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//! Core file copying engine with sparse support, atomic temp writes, and strict verification.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use crate::args::{CscArgs, SourceChangePolicy};
30use crate::journal::capture::{
31    CapturedPayload, CapturedSource, CommittedHardlinks, hash_primary,
32    open_payload,
33};
34use crate::journal::{JournalErrorRecord, JournalErrorStage, StateJournal};
35use crate::path_resolution::ResolvedCopyTask;
36use ctb_io::file::entity::{FileEntity, FileEntityKind};
37use ctb_io::file::link_path::LinkPath;
38use ctb_io::file::materializer::{
39    MaterializeOptions, apply_entity_metadata_ext, materialize_entity,
40};
41use ctb_io::file::path_policy::{PathTraversalPolicy, SymlinkValidationPolicy};
42use ctb_io::file::payload::{Extent, PayloadSource};
43use ctb_io::file::sandboxable_dir::SandboxableDir;
44use ctb_io::file::streams::write_streams;
45use ctb_io::file::verifier::{
46    try_drop_system_caches, verify_materialized_entity_ext,
47};
48use ctb_io::file::{query_block_device_size, verify_directory_filenames_exact};
49use std::io::{Read, Seek, SeekFrom};
50#[cfg(unix)]
51use std::os::unix::fs::{FileTypeExt, MetadataExt};
52use std::path::{Path, PathBuf};
53use std::time::Instant;
54use std::time::{SystemTime, UNIX_EPOCH};
55
56/// Summary stats from a copy run.
57#[derive(Debug, Clone, Default)]
58pub struct CopyStats {
59    pub files_copied: u64,
60    pub files_failed: u64,
61    pub files_skipped_identical: u64,
62    pub bytes_copied: u64,
63    pub dirs_created: u64,
64    pub symlinks_created: u64,
65    pub hardlinks_created: u64,
66    pub special_files_created: u64,
67    pub special_files_skipped: u64,
68    pub files_verified: u64,
69    pub(crate) copied_entities: Vec<(PathBuf, PathBuf, FileEntity)>,
70}
71
72/// Deferred symlink to materialize in Pass 2.
73struct DeferredSymlink {
74    src_path: PathBuf,
75    dest_path: PathBuf,
76    entity: FileEntity,
77    sandbox: std::sync::Arc<SandboxableDir>,
78    snapshot: ctb_io::file::payload::SourceSnapshot,
79}
80
81/// Deferred directory metadata fixup item for Pass 3.
82struct DeferredDirFixup {
83    src_path: PathBuf,
84    dest_path: PathBuf,
85    sandbox: std::sync::Arc<SandboxableDir>,
86    dir_entity: FileEntity,
87    expected_filenames: Vec<Vec<u8>>,
88    snapshot: ctb_io::file::payload::SourceSnapshot,
89}
90
91/// Records an item failure and either swallows it under `--continue-on-error` or
92/// marks the journal failed and aborts.
93fn handle_item_error(
94    src_path: &Path,
95    stage: JournalErrorStage,
96    err: anyhow::Error,
97    args: &CscArgs,
98    journal: &mut StateJournal,
99    stats: &mut CopyStats,
100) -> Result<Option<PathBuf>> {
101    let err_record = JournalErrorRecord::from_error(src_path, stage, &err);
102    let error_message = &err_record.error_message;
103    journal.record_error(&err_record).with_context(|| {
104        format!("Failed to journal copy failure: {error_message}")
105    })?;
106    if args.continue_on_error {
107        warn_fmt!("Failed to copy {}: {}", src_path.display(), error_message);
108        stats.files_failed = stats.files_failed.saturating_add(1);
109        Ok(None)
110    } else {
111        journal.mark_failed(error_message).with_context(|| {
112            format!("Failed to mark failed copy: {error_message}")
113        })?;
114        Err(err)
115    }
116}
117
118fn record_entity_warnings(
119    entity: &FileEntity,
120    journal: &mut StateJournal,
121) -> Result<()> {
122    crate::journal::capture::visit_warnings(entity, &mut |entity, warning| {
123        journal.record_warning("FileReadWarning", warning)?;
124        warn_fmt!("{}: {}", entity.identity.display_path(), warning);
125        Ok(())
126    })
127}
128
129/// Runs the complete copy pipeline across all tasks using descriptor-safe, multi-pass copying.
130fn validate_filesystem_known(
131    path: &Path,
132    fs_type: Option<&str>,
133    args: &CscArgs,
134) -> Result<()> {
135    if !args.best_effort_metadata && !args.allow_unknown_fs {
136        if let Some(fs) = fs_type {
137            if fs == "unknown" {
138                anyhow::bail!(
139                    "Cannot detect filesystem type for '{}'. Pass --best-effort-metadata or --allow-unknown-fs to proceed.",
140                    path.display()
141                );
142            }
143        } else {
144            anyhow::bail!(
145                "Cannot detect filesystem type for '{}'. Pass --best-effort-metadata or --allow-unknown-fs to proceed.",
146                path.display()
147            );
148        }
149    }
150    Ok(())
151}
152
153pub fn execute_copy_pipeline(
154    tasks: &[ResolvedCopyTask],
155    args: &CscArgs,
156    journal: &mut StateJournal,
157    progress: &Progress,
158) -> Result<CopyStats> {
159    crate::path_resolution::validate_task_overlap(tasks)?;
160    let mut stats = CopyStats::default();
161    let mut hardlink_map = CommittedHardlinks::default();
162    let mut captured_tree = crate::journal::capture::CapturedTree::default();
163    let mut deferred_dirs: Vec<DeferredDirFixup> = Vec::new();
164    let mut deferred_symlinks: Vec<DeferredSymlink> = Vec::new();
165    let mut files_to_verify: Vec<(PathBuf, PathBuf, FileEntity)> = Vec::new();
166
167    if !args.copy_specials_as_specials
168        && !args.copy_block_devices_as_regular_files
169        && !args.copy_fifos_as_regular_files
170    {
171        progress.message(
172            "Notice: Special files (FIFOs, device nodes, sockets) will be skipped by default. Pass --copy-specials-as-specials to preserve them.",
173        );
174        journal.record_warning(
175            "SpecialFilesSkippedByDefault",
176            "Special files (FIFOs, device nodes, sockets) are skipped by default. Pass --copy-specials-as-specials to preserve them.",
177        )?;
178    }
179    if args.best_effort_metadata {
180        journal.record_warning(
181            "BestEffortMetadata",
182            "Best-effort metadata enabled: non-fatal metadata write errors or timestamp precision differences may be tolerated.",
183        )?;
184    }
185
186    let mut uncommitted_count: usize = 0;
187    let copy_task = progress.start_files_task("Copying", None, None);
188
189    let strict_lossless = args.strict || !args.best_effort_metadata;
190    let (apple_write_mode, apple_single_write_extension) =
191        args.resolve_apple_write_mode()?;
192    let apple_read_options = args.resolve_apple_read_options();
193    let options = MaterializeOptions {
194        dry_run: args.dry_run,
195        strict_lossless,
196        check_atime: args.should_check_atime(),
197        check_ctime: args.should_check_ctime(),
198        check_birthtime: args.should_check_birthtime(),
199        symlink_policy: SymlinkValidationPolicy::PreserveVerbatim,
200        path_policy: PathTraversalPolicy::StrictSandboxed,
201        copy_specials: args.copy_specials_as_specials,
202        existing_entry_policy: if args.overwrite {
203            ctb_io::file::ExistingEntryPolicy::Replace
204        } else {
205            ctb_io::file::ExistingEntryPolicy::Refuse
206        },
207        force_overwrite: args.overwrite,
208        apple_write_mode,
209        apple_single_write_extension,
210    };
211
212    if !args.dry_run && !args.overwrite {
213        for task in tasks {
214            if !std::fs::symlink_metadata(&task.source_root)?.is_dir() {
215                continue;
216            }
217            let traversal_options = ctb_io::file::TraversalOptions::new()
218                .yield_root(true)
219                .one_file_system(args.one_file_system)
220                .apple_read_options(apple_read_options);
221            for entry in ctb_io::file::traverse_dir(
222                &task.source_root,
223                traversal_options,
224            )? {
225                let entry = entry?;
226                ensure!(
227                    entry.errors.is_empty(),
228                    "Source traversal errors: {}",
229                    entry.errors.join("; ")
230                );
231                if !entry.is_dir {
232                    continue;
233                }
234                let destination = task.target_root.join(&entry.relative_path);
235                match std::fs::symlink_metadata(&destination) {
236                    Ok(_) => {
237                        let is_resumed_and_authorized = if let Some(snap) =
238                            journal.snapshot()
239                        {
240                            if let Ok(rel) = compute_journal_relative_path(
241                                journal.destination(),
242                                &destination,
243                            ) {
244                                if let Some(expected_id) =
245                                    snap.applied_directories.get(&rel)
246                                {
247                                    ctb_io::file::identity::query_file_identity(
248                                        &destination,
249                                    )
250                                    .is_ok_and(|actual_id| {
251                                        actual_id == *expected_id
252                                    })
253                                } else {
254                                    false
255                                }
256                            } else {
257                                false
258                            }
259                        } else {
260                            false
261                        };
262                        if !is_resumed_and_authorized {
263                            anyhow::bail!(
264                                "Restoring directory metadata requires --overwrite for existing destination {}; resume does not grant permission",
265                                destination.display()
266                            );
267                        }
268                    }
269                    Err(error)
270                        if error.kind() == std::io::ErrorKind::NotFound => {}
271                    Err(error) => return Err(error.into()),
272                }
273            }
274        }
275    }
276
277    // =========================================================================
278    // PASS 1: Directory traversal & copying regular files, special nodes, hardlinks
279    // =========================================================================
280    for task in tasks {
281        let src_root = &task.source_root;
282        let tgt_root = &task.target_root;
283
284        let src_meta = match std::fs::symlink_metadata(src_root) {
285            Ok(m) => m,
286            Err(e) => {
287                anyhow::bail!(
288                    "Source path does not exist: {}: {e}",
289                    src_root.display()
290                );
291            }
292        };
293
294        let src_fs = ctb_io::file::query_filesystem_info(src_root, &src_meta);
295        validate_filesystem_known(src_root, Some(&src_fs.fs_type), args)?;
296
297        let tgt_existing = if tgt_root.exists() {
298            tgt_root.clone()
299        } else {
300            match ctb_io::file::resolve_existing_ancestors(tgt_root) {
301                Ok(ancestor) => ancestor,
302                Err(_) => PathBuf::from("."),
303            }
304        };
305        if let Ok(tgt_meta) = std::fs::symlink_metadata(&tgt_existing) {
306            let tgt_fs =
307                ctb_io::file::query_filesystem_info(&tgt_existing, &tgt_meta);
308            validate_filesystem_known(tgt_root, Some(&tgt_fs.fs_type), args)?;
309        }
310
311        if src_meta.is_dir() {
312            let dest_dir = std::sync::Arc::new(if args.dry_run {
313                SandboxableDir::open(".")
314                    .context("Failed to open current directory in dry run")?
315            } else {
316                SandboxableDir::create_or_open(journal.destination())?
317            });
318
319            if let Some(snap) = journal.snapshot() {
320                let mut applied_dirs: Vec<_> =
321                    snap.applied_directories.iter().collect();
322                applied_dirs.sort_by(|a, b| a.0.cmp(b.0));
323                for (rel_dir, expected_identity) in applied_dirs {
324                    dest_dir.restore_applied_directory_ownership(
325                        rel_dir,
326                        expected_identity,
327                    )?;
328                }
329            }
330            if let Ok(root_id) =
331                dest_dir.query_owned_directory_identity(Path::new(""))
332            {
333                journal.record_applied_directory(PathBuf::new(), root_id);
334            }
335
336            let traversal_opts = ctb_io::file::TraversalOptions::new()
337                .order(ctb_io::file::TraversalOrder::PreOrderDepthFirst)
338                .one_file_system(args.one_file_system)
339                .error_policy(ctb_io::file::OnTraversalError::Capture)
340                .apple_read_options(apple_read_options);
341            let mut directories =
342                ctb_io::file::traverse_dir(src_root, traversal_opts)?
343                    .directories()?;
344
345            while let Some(directory) = directories.next() {
346                let directory = directory?;
347                let curr_src = directory.path.clone();
348                let curr_tgt = tgt_root.join(&directory.relative_path);
349                if !directory.errors.is_empty() {
350                    let error = anyhow::anyhow!(
351                        "Source traversal errors: {}",
352                        directory.errors.join("; ")
353                    );
354                    let _ = handle_item_error(
355                        &curr_src,
356                        JournalErrorStage::Traversal,
357                        error,
358                        args,
359                        journal,
360                        &mut stats,
361                    )?;
362                    continue;
363                }
364                let CapturedSource {
365                    entity: mut dir_entity,
366                    snapshot: dir_snapshot,
367                } = match CapturedSource::capture(
368                    &curr_src,
369                    Some(src_root),
370                    &apple_read_options,
371                    args.on_source_change == SourceChangePolicy::BestEffort,
372                ) {
373                    Ok(source) => {
374                        record_entity_warnings(&source.entity, journal)?;
375                        source
376                    }
377                    Err(e) => {
378                        let _ = handle_item_error(
379                            &curr_src,
380                            JournalErrorStage::MetadataRead,
381                            e,
382                            args,
383                            journal,
384                            &mut stats,
385                        )?;
386                        continue;
387                    }
388                };
389                if let Err(e) = validate_filesystem_known(
390                    &curr_src,
391                    dir_entity.metadata.filesystem_type.as_deref(),
392                    args,
393                ) {
394                    let _ = handle_item_error(
395                        &curr_src,
396                        JournalErrorStage::MetadataRead,
397                        e,
398                        args,
399                        journal,
400                        &mut stats,
401                    )?;
402                    continue;
403                }
404
405                let orig_rel = compute_journal_relative_path(
406                    journal.destination(),
407                    &curr_tgt,
408                )?;
409                captured_tree.retain(&dir_snapshot);
410                let (rel, dir_adapt_warnings) = if strict_lossless
411                    || orig_rel.as_os_str().is_empty()
412                    || orig_rel == Path::new(".")
413                {
414                    (orig_rel.clone(), Vec::new())
415                } else {
416                    ctb_io::file::adapt_relative_path_for_materialization(
417                        &orig_rel,
418                        cfg!(windows),
419                    )
420                };
421                if rel != orig_rel {
422                    dir_entity
423                        .metadata
424                        .set_materialized_relative_path(&orig_rel, &rel);
425                }
426                let curr_tgt = if rel == orig_rel {
427                    curr_tgt
428                } else {
429                    dest_dir.root_path().join(&rel)
430                };
431                dir_entity.identity.relative_path = Some(rel.clone());
432                record_materialization_warnings(
433                    journal,
434                    &mut dir_entity,
435                    dir_adapt_warnings,
436                )?;
437
438                if !args.dry_run {
439                    // Reason for fallback: absent relative path defaults to current directory "." as destination root
440                    let rel_dir = if rel.as_os_str().is_empty() {
441                        Path::new(".")
442                    } else {
443                        &rel
444                    };
445                    if let Err(e) = validate_copy_source(
446                        &dir_snapshot,
447                        &mut dir_entity,
448                        journal,
449                    )
450                    .and_then(|()| {
451                        dest_dir.ensure_dir_all(rel_dir, options.path_policy)
452                    })
453                    .and_then(|_| {
454                        dest_dir.authorize_metadata(
455                            rel_dir,
456                            options.existing_entry_policy,
457                        )
458                    }) {
459                        record_materialization_failure(
460                            journal,
461                            &dest_dir.root_path().join(rel_dir),
462                            &dir_entity,
463                            &e,
464                        )?;
465                        let _ = handle_item_error(
466                            &curr_src,
467                            JournalErrorStage::Materialize,
468                            e,
469                            args,
470                            journal,
471                            &mut stats,
472                        )?;
473                        continue;
474                    }
475                    if let Ok(identity) =
476                        dest_dir.query_owned_directory_identity(rel_dir)
477                    {
478                        journal.record_applied_directory(rel.clone(), identity);
479                    }
480                }
481                stats.dirs_created = stats.dirs_created.saturating_add(1);
482
483                journal.record_entity(&dir_entity);
484                if !args.dry_run {
485                    journal.commit_batch()?;
486                }
487
488                // Reason for fallback: absent relative path defaults to current directory "." as destination root
489                let dir_rel = dir_entity
490                    .identity
491                    .relative_path
492                    .as_deref()
493                    .unwrap_or(Path::new("."));
494                let mut traversal_errors = Vec::new();
495                let entries_result =
496                    directories.read_directory(&directory, |entries| {
497                        let mut discovered = Vec::new();
498                        for item in entries {
499                            if item.errors.is_empty() {
500                                discovered.push(item);
501                            } else {
502                                let error = anyhow::anyhow!(
503                                    "Source traversal errors: {}",
504                                    item.errors.join("; ")
505                                );
506                                traversal_errors.push((item.path, error));
507                            }
508                        }
509                        ctb_io::file::validate_and_order_directory_entries(
510                            discovered,
511                            &curr_src,
512                            &curr_tgt,
513                            tgt_root,
514                            dir_rel,
515                            &apple_read_options,
516                            apple_write_mode,
517                            apple_single_write_extension,
518                        )
519                    });
520                for (path, error) in traversal_errors {
521                    let _ = handle_item_error(
522                        &path,
523                        JournalErrorStage::Traversal,
524                        error,
525                        args,
526                        journal,
527                        &mut stats,
528                    )?;
529                }
530                let dir_entries = match entries_result {
531                    Ok(entries) => entries,
532                    Err(e) => {
533                        let _ = handle_item_error(
534                            &curr_src,
535                            JournalErrorStage::Traversal,
536                            e,
537                            args,
538                            journal,
539                            &mut stats,
540                        )?;
541                        continue;
542                    }
543                };
544
545                let mut expected_filenames: Vec<Vec<u8>> = Vec::new();
546
547                for item in dir_entries {
548                    let entry_src = item.path;
549                    let entry_name = item.file_name;
550                    let entry_tgt = curr_tgt.join(&entry_name);
551
552                    let entry_rel = match &dir_entity.identity.relative_path {
553                        Some(p) if !p.as_os_str().is_empty() => {
554                            p.join(&entry_name)
555                        }
556                        _ => PathBuf::from(&entry_name),
557                    };
558
559                    if item.is_dir {
560                        let expected_name = if strict_lossless {
561                            entry_name.clone()
562                        } else {
563                            ctb_io::file::adapt_component_for_materialization(
564                                &entry_name,
565                                cfg!(windows),
566                            )
567                            .0
568                        };
569                        expected_filenames
570                            .push(expected_name.as_encoded_bytes().to_vec());
571                    } else if item.is_symlink {
572                        let CapturedSource {
573                            entity: sym_entity,
574                            snapshot,
575                        } = match CapturedSource::capture(
576                            &entry_src,
577                            Some(src_root),
578                            &apple_read_options,
579                            args.on_source_change
580                                == SourceChangePolicy::BestEffort,
581                        ) {
582                            Ok(source) => {
583                                record_entity_warnings(
584                                    &source.entity,
585                                    journal,
586                                )?;
587                                source
588                            }
589                            Err(e) => {
590                                let _ = handle_item_error(
591                                    &entry_src,
592                                    JournalErrorStage::MetadataRead,
593                                    e,
594                                    args,
595                                    journal,
596                                    &mut stats,
597                                )?;
598                                continue;
599                            }
600                        };
601                        if let Err(e) = validate_filesystem_known(
602                            &entry_src,
603                            sym_entity.metadata.filesystem_type.as_deref(),
604                            args,
605                        ) {
606                            let _ = handle_item_error(
607                                &entry_src,
608                                JournalErrorStage::MetadataRead,
609                                e,
610                                args,
611                                journal,
612                                &mut stats,
613                            )?;
614                            continue;
615                        }
616                        let expected_name = if strict_lossless {
617                            entry_name.clone()
618                        } else {
619                            ctb_io::file::adapt_component_for_materialization(
620                                &entry_name,
621                                cfg!(windows),
622                            )
623                            .0
624                        };
625                        expected_filenames
626                            .push(expected_name.as_encoded_bytes().to_vec());
627                        let mut sym_entity = sym_entity;
628                        sym_entity.identity.relative_path = Some(entry_rel);
629                        deferred_symlinks.push(DeferredSymlink {
630                            src_path: entry_src,
631                            dest_path: entry_tgt,
632                            entity: sym_entity,
633                            sandbox: std::sync::Arc::clone(&dest_dir),
634                            snapshot,
635                        });
636                    } else {
637                        let created_path = copy_single_item(
638                            &entry_src,
639                            &entry_tgt,
640                            &entry_rel,
641                            &dest_dir,
642                            &options,
643                            args,
644                            journal,
645                            &mut hardlink_map,
646                            &mut stats,
647                            &mut files_to_verify,
648                            progress,
649                            copy_task,
650                        )?;
651                        if let Some(dest) = created_path {
652                            if let Some(fname) = dest.file_name() {
653                                expected_filenames
654                                    .push(fname.as_encoded_bytes().to_vec());
655                            }
656                        }
657
658                        uncommitted_count = uncommitted_count.saturating_add(1);
659                        if uncommitted_count >= 500 && !args.dry_run {
660                            journal.commit_batch()?;
661                            uncommitted_count = 0;
662                        }
663
664                        if progress.is_enabled() {
665                            progress.update_task_files_and_bytes(
666                                copy_task,
667                                stats.files_copied,
668                                stats.bytes_copied,
669                                None,
670                            );
671                        }
672                    }
673                }
674
675                deferred_dirs.push(DeferredDirFixup {
676                    src_path: curr_src,
677                    dest_path: curr_tgt.clone(),
678                    sandbox: std::sync::Arc::clone(&dest_dir),
679                    dir_entity: dir_entity.clone(),
680                    expected_filenames,
681                    snapshot: dir_snapshot,
682                });
683            }
684        } else {
685            // Reason for fallback: A single-component relative destination (e.g. "output.bin") has no parent path or an empty parent path (""); falling back to current working directory "." correctly targets the local directory.
686            let parent_dest = match tgt_root.parent() {
687                Some(p) if !p.as_os_str().is_empty() => p,
688                _ => Path::new("."),
689            };
690            let target_file_name = tgt_root
691                .file_name()
692                .context("Target path has no file name component")?;
693
694            let dest_dir = std::sync::Arc::new(if args.dry_run {
695                SandboxableDir::open(".")
696                    .context("Failed to open current directory in dry run")?
697            } else {
698                SandboxableDir::create_or_open(parent_dest)?
699            });
700
701            let target_rel_path = Path::new(target_file_name);
702
703            if src_meta.is_symlink() {
704                let CapturedSource {
705                    entity: mut sym_entity,
706                    snapshot,
707                } = match CapturedSource::capture(
708                    src_root,
709                    None,
710                    &apple_read_options,
711                    args.on_source_change == SourceChangePolicy::BestEffort,
712                ) {
713                    Ok(source) => {
714                        record_entity_warnings(&source.entity, journal)?;
715                        source
716                    }
717                    Err(e) => {
718                        let _ = handle_item_error(
719                            src_root,
720                            JournalErrorStage::MetadataRead,
721                            e,
722                            args,
723                            journal,
724                            &mut stats,
725                        )?;
726                        continue;
727                    }
728                };
729                if let Err(e) = validate_filesystem_known(
730                    src_root,
731                    sym_entity.metadata.filesystem_type.as_deref(),
732                    args,
733                ) {
734                    let _ = handle_item_error(
735                        src_root,
736                        JournalErrorStage::MetadataRead,
737                        e,
738                        args,
739                        journal,
740                        &mut stats,
741                    )?;
742                    continue;
743                }
744                sym_entity.identity.relative_path =
745                    Some(target_rel_path.to_path_buf());
746                deferred_symlinks.push(DeferredSymlink {
747                    src_path: src_root.clone(),
748                    dest_path: tgt_root.clone(),
749                    entity: sym_entity,
750                    sandbox: std::sync::Arc::clone(&dest_dir),
751                    snapshot,
752                });
753            } else {
754                let skipped_before = stats.special_files_skipped;
755                let created = copy_single_item(
756                    src_root,
757                    tgt_root,
758                    target_rel_path,
759                    &dest_dir,
760                    &options,
761                    args,
762                    journal,
763                    &mut hardlink_map,
764                    &mut stats,
765                    &mut files_to_verify,
766                    progress,
767                    copy_task,
768                )?;
769                if created.is_none()
770                    && stats.special_files_skipped > skipped_before
771                {
772                    let err = anyhow::anyhow!(
773                        "Refusing to copy special file '{}' without an explicit special-file policy (pass --copy-specials-as-specials or --copy-fifos-as-regular-files / --copy-block-devices-as-regular-files)",
774                        src_root.display()
775                    );
776                    let _ = handle_item_error(
777                        src_root,
778                        JournalErrorStage::Materialize,
779                        err,
780                        args,
781                        journal,
782                        &mut stats,
783                    )?;
784                }
785                if progress.is_enabled() {
786                    progress.update_task_files_and_bytes(
787                        copy_task,
788                        stats.files_copied,
789                        stats.bytes_copied,
790                        None,
791                    );
792                }
793            }
794        }
795    }
796
797    // =========================================================================
798    // PASS 2: Defer symlink creation until all regular files & dirs are on disk
799    // =========================================================================
800    for symlink_item in deferred_symlinks {
801        let dest_path = &symlink_item.dest_path;
802        let mut entity = symlink_item.entity;
803        if let Err(error) =
804            validate_copy_source(&symlink_item.snapshot, &mut entity, journal)
805        {
806            let _ = handle_item_error(
807                &symlink_item.src_path,
808                JournalErrorStage::PostCheck,
809                error,
810                args,
811                journal,
812                &mut stats,
813            )?;
814            continue;
815        }
816        let dest_dir = &symlink_item.sandbox;
817        // Reason for fallback: entity at root of destination sandbox has no explicit relative path, defaulting to empty path
818        let symlink_rel =
819            entity.identity.relative_path.clone().unwrap_or_default();
820        if is_verified_resumed_destination_entry(
821            &symlink_rel,
822            dest_path,
823            &entity,
824            dest_dir,
825            &options,
826            args,
827            journal,
828        ) {
829            record_journal_entry(journal, dest_path, &entity)?;
830            files_to_verify.push((
831                symlink_item.src_path,
832                dest_path.clone(),
833                entity,
834            ));
835            continue;
836        }
837        if !args.dry_run
838            && !(options.existing_entry_policy
839                == ctb_io::file::ExistingEntryPolicy::Refuse
840                && std::fs::symlink_metadata(dest_path).is_ok())
841        {
842            record_journal_entry(journal, dest_path, &entity)?;
843            journal.commit_batch()?;
844        }
845
846        let receipt =
847            match materialize_entity(&entity, None, dest_dir, &options) {
848                Ok(receipt) => receipt,
849                Err(e) => {
850                    record_materialization_failure(
851                        journal, dest_path, &entity, &e,
852                    )?;
853                    let _ = handle_item_error(
854                        &symlink_item.src_path,
855                        JournalErrorStage::Materialize,
856                        e,
857                        args,
858                        journal,
859                        &mut stats,
860                    )?;
861                    continue;
862                }
863            };
864        receipt.apply_stream_adaptations(&mut entity);
865        record_materialization_warnings(
866            journal,
867            &mut entity,
868            receipt.warnings,
869        )?;
870        let actual_dest_path = &receipt.destination_path;
871        if actual_dest_path != dest_path {
872            if let (Ok(orig_rel), Ok(actual_rel)) = (
873                compute_journal_relative_path(journal.destination(), dest_path),
874                compute_journal_relative_path(
875                    journal.destination(),
876                    actual_dest_path,
877                ),
878            ) {
879                let source_rel = if orig_rel.as_os_str().is_empty() {
880                    entity.identity.relative_path.clone().unwrap_or(orig_rel) // Reason for fallback: single-file copy uses filename relative to parent dir
881                } else {
882                    orig_rel
883                };
884                let mat_rel = if actual_rel.as_os_str().is_empty() {
885                    // Reason for fallback: single-file copy uses destination filename when relative path is empty, falling back to empty path if no filename
886                    actual_dest_path
887                        .file_name()
888                        .map_or(actual_rel.clone(), PathBuf::from)
889                } else {
890                    actual_rel.clone()
891                };
892                if source_rel != mat_rel {
893                    entity
894                        .metadata
895                        .set_materialized_relative_path(&source_rel, &mat_rel);
896                }
897                if !actual_rel.as_os_str().is_empty() {
898                    entity.identity.relative_path = Some(actual_rel);
899                }
900            }
901        }
902
903        if !args.dry_run {
904            let dest_target = match std::fs::symlink_metadata(actual_dest_path)
905                .map_err(anyhow::Error::new)
906                .and_then(|observed| {
907                    ctb_io::file::metadata::read_symlink_target(
908                        actual_dest_path,
909                        &observed,
910                    )
911                }) {
912                Ok(t) => t,
913                Err(e) => {
914                    let error = e;
915                    record_materialization_failure(
916                        journal,
917                        actual_dest_path,
918                        &entity,
919                        &error,
920                    )?;
921                    let _ = handle_item_error(
922                        &symlink_item.src_path,
923                        JournalErrorStage::Materialize,
924                        error,
925                        args,
926                        journal,
927                        &mut stats,
928                    )?;
929                    continue;
930                }
931            };
932            if let FileEntityKind::Symlink { target } = &entity.kind {
933                let expected_target =
934                    target.to_path_buf_for_materialization(strict_lossless)?;
935                let exact = dest_target.as_os_str().as_encoded_bytes()
936                    == expected_target.as_os_str().as_encoded_bytes();
937                let adapted = !strict_lossless
938                    && dest_target.as_os_str().as_encoded_bytes()
939                        == expected_target.to_string_lossy().as_bytes();
940                if !exact && !adapted {
941                    let err = anyhow::anyhow!(
942                        "Target filesystem altered or normalized symlink target for {}",
943                        actual_dest_path.display()
944                    );
945                    record_materialization_failure(
946                        journal,
947                        actual_dest_path,
948                        &entity,
949                        &err,
950                    )?;
951                    let _ = handle_item_error(
952                        &symlink_item.src_path,
953                        JournalErrorStage::Materialize,
954                        err,
955                        args,
956                        journal,
957                        &mut stats,
958                    )?;
959                    continue;
960                }
961            }
962        }
963
964        stats.symlinks_created = stats.symlinks_created.saturating_add(1);
965        record_journal_entry(journal, actual_dest_path, &entity)?;
966        files_to_verify.push((
967            symlink_item.src_path,
968            actual_dest_path.clone(),
969            entity,
970        ));
971    }
972
973    // =========================================================================
974    // PASS 3: Apply directory metadata in reverse traversal order (leaf-first)
975    // =========================================================================
976    if !args.dry_run {
977        while let Some(mut fixup) = deferred_dirs.pop() {
978            if let Err(error) = validate_copy_source(
979                &fixup.snapshot,
980                &mut fixup.dir_entity,
981                journal,
982            ) {
983                let _ = handle_item_error(
984                    &fixup.src_path,
985                    JournalErrorStage::PostCheck,
986                    error,
987                    args,
988                    journal,
989                    &mut stats,
990                )?;
991                continue;
992            }
993            if fixup.dest_path.exists() {
994                let expected_refs: Vec<&[u8]> = fixup
995                    .expected_filenames
996                    .iter()
997                    .map(Vec::as_slice)
998                    .collect();
999                if let Err(e) = verify_directory_filenames_exact(
1000                    &fixup.dest_path,
1001                    &expected_refs,
1002                ) {
1003                    record_materialization_failure(
1004                        journal,
1005                        &fixup.dest_path,
1006                        &fixup.dir_entity,
1007                        &e,
1008                    )?;
1009                    let _ = handle_item_error(
1010                        &fixup.src_path,
1011                        JournalErrorStage::Materialize,
1012                        e,
1013                        args,
1014                        journal,
1015                        &mut stats,
1016                    )?;
1017                    continue;
1018                }
1019
1020                let relative = fixup
1021                    .dir_entity
1022                    .identity
1023                    .relative_path
1024                    .as_deref()
1025                    .context("Missing deferred directory relative path")?;
1026                let (stream_adaptations, stream_warnings) = match fixup
1027                    .sandbox
1028                    .authorize_metadata(relative, options.existing_entry_policy)
1029                    .and_then(|()| {
1030                        ctb_io::file::materialize_directory_streams_and_companions(
1031                            &fixup.dir_entity,
1032                            &fixup.dest_path,
1033                            &fixup.sandbox,
1034                            &options,
1035                            &ctb_io::file::streams::FilesystemStreamSource,
1036                        )
1037                    }) {
1038                    Ok(res) => res,
1039                    Err(e) => {
1040                        record_materialization_failure(journal, &fixup.dest_path, &fixup.dir_entity, &e)?;
1041                        let _ = handle_item_error(
1042                            &fixup.src_path,
1043                            JournalErrorStage::Materialize,
1044                            e,
1045                            args,
1046                            journal,
1047                            &mut stats,
1048                        )?;
1049                        continue;
1050                    }
1051                };
1052                for adapt in &stream_adaptations {
1053                    if let Some(stream) =
1054                        fixup.dir_entity.streams.get_mut(adapt.stream_index)
1055                    {
1056                        if adapt.source_stream_name
1057                            != adapt.materialized_stream_name
1058                        {
1059                            stream
1060                                .entity
1061                                .metadata
1062                                .set_materialized_stream_name(
1063                                    &adapt.source_stream_name,
1064                                    &adapt.materialized_stream_name,
1065                                );
1066                        }
1067                        if let (Some(src_rel), Some(mat_rel)) = (
1068                            adapt.source_relative_path.as_deref(),
1069                            adapt.materialized_relative_path.as_deref(),
1070                        ) {
1071                            if src_rel != mat_rel {
1072                                stream
1073                                    .entity
1074                                    .metadata
1075                                    .set_materialized_relative_path(
1076                                        src_rel, mat_rel,
1077                                    );
1078                            }
1079                            stream.entity.identity.relative_path =
1080                                Some(mat_rel.to_path_buf());
1081                        }
1082                    }
1083                }
1084                record_materialization_warnings(
1085                    journal,
1086                    &mut fixup.dir_entity,
1087                    stream_warnings,
1088                )?;
1089                let warnings = match apply_entity_metadata_ext(
1090                    &fixup.dest_path,
1091                    None,
1092                    &fixup.dir_entity.metadata,
1093                    false,
1094                    true,
1095                    strict_lossless,
1096                    options.check_ctime,
1097                    options.check_birthtime,
1098                ) {
1099                    Ok(warnings) => warnings,
1100                    Err(e) => {
1101                        record_materialization_failure(
1102                            journal,
1103                            &fixup.dest_path,
1104                            &fixup.dir_entity,
1105                            &e,
1106                        )?;
1107                        let _ = handle_item_error(
1108                            &fixup.src_path,
1109                            JournalErrorStage::Materialize,
1110                            e,
1111                            args,
1112                            journal,
1113                            &mut stats,
1114                        )?;
1115                        continue;
1116                    }
1117                };
1118                record_materialization_warnings(
1119                    journal,
1120                    &mut fixup.dir_entity,
1121                    warnings,
1122                )?;
1123                record_journal_entry(
1124                    journal,
1125                    &fixup.dest_path,
1126                    &fixup.dir_entity,
1127                )?;
1128                if let Err(e) = verify_materialized_entity_ext(
1129                    &fixup.dest_path,
1130                    &fixup.dir_entity,
1131                    strict_lossless,
1132                    args.should_check_atime(),
1133                    args.should_check_ctime(),
1134                    options.check_birthtime,
1135                ) {
1136                    record_materialization_failure(
1137                        journal,
1138                        &fixup.dest_path,
1139                        &fixup.dir_entity,
1140                        &e,
1141                    )?;
1142                    let _ = handle_item_error(
1143                        &fixup.src_path,
1144                        JournalErrorStage::Materialize,
1145                        e,
1146                        args,
1147                        journal,
1148                        &mut stats,
1149                    )?;
1150                    continue;
1151                }
1152                files_to_verify.push((
1153                    fixup.src_path,
1154                    fixup.dest_path,
1155                    fixup.dir_entity,
1156                ));
1157            } else {
1158                let err = anyhow::anyhow!(
1159                    "Destination directory disappeared: {}",
1160                    fixup.dest_path.display()
1161                );
1162                record_materialization_failure(
1163                    journal,
1164                    &fixup.dest_path,
1165                    &fixup.dir_entity,
1166                    &err,
1167                )?;
1168                let _ = handle_item_error(
1169                    &fixup.src_path,
1170                    JournalErrorStage::Materialize,
1171                    err,
1172                    args,
1173                    journal,
1174                    &mut stats,
1175                )?;
1176                continue;
1177            }
1178        }
1179        journal.commit_batch()?;
1180    }
1181
1182    if progress.is_enabled() && stats.files_copied > 0 {
1183        let detail = format!(
1184            "{} files ({})",
1185            stats.files_copied,
1186            format_bytes_decimal(stats.bytes_copied)
1187        );
1188        progress.finish_task(copy_task, Some(&detail));
1189    }
1190
1191    // =========================================================================
1192    // PASS 4: Post-flush independent verification pass
1193    // =========================================================================
1194    if args.should_verify_after() && !args.dry_run {
1195        progress
1196            .message("[Verifying] Flushing caches and verifying checksums...");
1197        try_drop_system_caches();
1198
1199        let total_to_verify = u64::try_from(files_to_verify.len())?;
1200        let total_bytes_to_verify: u64 = files_to_verify
1201            .iter()
1202            .filter_map(|(_, _, e)| match &e.kind {
1203                FileEntityKind::Regular { size, .. } => Some(*size),
1204                _ => None,
1205            })
1206            .fold(0_u64, u64::saturating_add);
1207        let verify_task = progress.start_files_task(
1208            "Verifying",
1209            Some(total_to_verify),
1210            Some(total_bytes_to_verify),
1211        );
1212        let mut verified_bytes = 0_u64;
1213
1214        for (src_path, dest_path, entity) in &files_to_verify {
1215            if progress.is_enabled() {
1216                // Reason for fallback: root or empty path without a filename defaults to empty detail string
1217                let detail =
1218                    src_path.file_name().map_or_else(String::new, |f| {
1219                        f.to_string_lossy().into_owned()
1220                    });
1221                progress.update_task_files_and_bytes(
1222                    verify_task,
1223                    stats.files_verified,
1224                    verified_bytes,
1225                    Some(&detail),
1226                );
1227            }
1228            let check_atime = args.should_check_atime()
1229                || (entity.is_regular()
1230                    && entity.metadata.used_noatime()
1231                    && !args.best_effort_metadata);
1232            #[cfg(unix)]
1233            // Reason for fallback: failed metadata read treats path as not being a special device file
1234            let is_special_as_regular = (args
1235                .copy_block_devices_as_regular_files
1236                || args.copy_fifos_as_regular_files)
1237                && std::fs::symlink_metadata(src_path).is_ok_and(|m| {
1238                    m.file_type().is_block_device() || m.file_type().is_fifo()
1239                });
1240            #[cfg(not(unix))]
1241            let is_special_as_regular = false;
1242
1243            if !is_special_as_regular {
1244                if let Err(e) = verify_materialized_entity_ext(
1245                    src_path,
1246                    entity,
1247                    strict_lossless,
1248                    check_atime,
1249                    args.should_check_ctime(),
1250                    options.check_birthtime,
1251                ) {
1252                    let _ = handle_item_error(
1253                        src_path,
1254                        JournalErrorStage::PostCheck,
1255                        e,
1256                        args,
1257                        journal,
1258                        &mut stats,
1259                    )?;
1260                    continue;
1261                }
1262            }
1263            if let Err(e) = verify_materialized_entity_ext(
1264                dest_path,
1265                entity,
1266                strict_lossless,
1267                check_atime,
1268                args.should_check_ctime(),
1269                options.check_birthtime,
1270            ) {
1271                let _ = handle_item_error(
1272                    dest_path,
1273                    JournalErrorStage::PostCheck,
1274                    e,
1275                    args,
1276                    journal,
1277                    &mut stats,
1278                )?;
1279                continue;
1280            }
1281            if let FileEntityKind::Regular { size, .. } = &entity.kind {
1282                stats.files_verified = stats.files_verified.saturating_add(1);
1283                verified_bytes = verified_bytes.saturating_add(*size);
1284            }
1285
1286            if progress.is_enabled() {
1287                progress.update_task_files_and_bytes(
1288                    verify_task,
1289                    stats.files_verified,
1290                    verified_bytes,
1291                    None,
1292                );
1293            }
1294        }
1295
1296        if progress.is_enabled() {
1297            progress.finish_task(verify_task, Some("Verification complete"));
1298        }
1299    }
1300
1301    stats.copied_entities = files_to_verify;
1302    finalize_copy_pipeline(&captured_tree, args, journal, &mut stats)?;
1303    Ok(stats)
1304}
1305
1306fn finalize_copy_pipeline(
1307    captured_tree: &crate::journal::capture::CapturedTree,
1308    args: &CscArgs,
1309    journal: &mut StateJournal,
1310    stats: &mut CopyStats,
1311) -> Result<()> {
1312    if let Err(error) = captured_tree.validate() {
1313        let path = journal.destination().to_path_buf();
1314        let _ = handle_item_error(
1315            &path,
1316            JournalErrorStage::PostCheck,
1317            error,
1318            args,
1319            journal,
1320            stats,
1321        )?;
1322    }
1323    captured_tree.visit_pending_warnings(&mut |code, warning| {
1324        if !journal
1325            .warnings()
1326            .iter()
1327            .any(|record| record.message == warning)
1328        {
1329            journal.record_warning(code, warning)?;
1330            warn_fmt!("{warning}");
1331        }
1332        Ok(())
1333    })?;
1334    if args.should_verify_after() && !args.dry_run {
1335        if journal.defer_completion() {
1336            journal.commit_batch()?;
1337        } else {
1338            journal.mark_completed()?;
1339        }
1340    }
1341    Ok(())
1342}
1343
1344#[expect(
1345    clippy::too_many_arguments,
1346    reason = "Internal worker separating pipeline state from configuration"
1347)]
1348fn copy_single_item(
1349    src_path: &Path,
1350    dest_path: &Path,
1351    dest_rel_path: &Path,
1352    dest_dir: &SandboxableDir,
1353    options: &MaterializeOptions,
1354    args: &CscArgs,
1355    journal: &mut StateJournal,
1356    hardlink_map: &mut CommittedHardlinks,
1357    stats: &mut CopyStats,
1358    files_to_verify: &mut Vec<(PathBuf, PathBuf, FileEntity)>,
1359    progress: &Progress,
1360    copy_task: TaskId,
1361) -> Result<Option<PathBuf>> {
1362    // 2. Discover metadata-only entity from filesystem (avoiding full payload hash when unnecessary)
1363    let apple_read_options = args.resolve_apple_read_options();
1364    let entity_res = CapturedSource::capture(
1365        src_path,
1366        None,
1367        &apple_read_options,
1368        args.on_source_change == SourceChangePolicy::BestEffort,
1369    );
1370    let CapturedSource {
1371        mut entity,
1372        snapshot,
1373    } = match entity_res {
1374        Ok(source) => {
1375            record_entity_warnings(&source.entity, journal)?;
1376            source
1377        }
1378        Err(err) => {
1379            return handle_item_error(
1380                src_path,
1381                JournalErrorStage::MetadataRead,
1382                err,
1383                args,
1384                journal,
1385                stats,
1386            );
1387        }
1388    };
1389    if let Err(err) = validate_filesystem_known(
1390        src_path,
1391        entity.metadata.filesystem_type.as_deref(),
1392        args,
1393    ) {
1394        return handle_item_error(
1395            src_path,
1396            JournalErrorStage::MetadataRead,
1397            err,
1398            args,
1399            journal,
1400            stats,
1401        );
1402    }
1403
1404    // If an AppleSingle extension was stripped on read, update destination relative path
1405    let mut effective_dest_rel = dest_rel_path.to_path_buf();
1406    if let Some(name) = dest_rel_path.file_name() {
1407        for (enabled, extension) in [
1408            (
1409                apple_read_options.read_apple_single_as,
1410                ctb_io::file::apple_double::AppleSingleExtension::As,
1411            ),
1412            (
1413                apple_read_options.read_apple_single_asf,
1414                ctb_io::file::apple_double::AppleSingleExtension::Asf,
1415            ),
1416        ] {
1417            if enabled {
1418                if let Some(stem) = extension.strip_from_name(name) {
1419                    if entity.identity.filename_bytes()
1420                        == Some(stem.as_encoded_bytes())
1421                    {
1422                        effective_dest_rel = dest_rel_path.with_file_name(stem);
1423                        break;
1424                    }
1425                }
1426            }
1427        }
1428    }
1429    // Reason for fallback: parent path defaults to current directory
1430    let parent_path = dest_path.parent().unwrap_or(Path::new("."));
1431    // Reason for fallback: file name defaults to verbatim OsStr
1432    let file_name = effective_dest_rel
1433        .file_name()
1434        .unwrap_or(effective_dest_rel.as_os_str());
1435    let effective_dest_path = parent_path.join(file_name);
1436
1437    if effective_dest_rel != dest_rel_path {
1438        entity
1439            .metadata
1440            .set_materialized_relative_path(dest_rel_path, &effective_dest_rel);
1441    }
1442    entity.identity.relative_path = Some(effective_dest_rel);
1443
1444    if let FileEntityKind::Regular { size, sha256, .. } = &entity.kind {
1445        if *sha256 == [0_u8; 32] {
1446            let size = *size;
1447            let payload = match open_payload(src_path, &snapshot) {
1448                Ok(payload) => payload,
1449                Err(error) => {
1450                    return handle_item_error(
1451                        src_path,
1452                        JournalErrorStage::PayloadOpen,
1453                        error.context("Failed to open source for checksumming"),
1454                        args,
1455                        journal,
1456                        stats,
1457                    );
1458                }
1459            };
1460            let mut p_stream = ProgressStream::new(
1461                payload,
1462                progress,
1463                copy_task,
1464                stats.files_copied,
1465                stats.bytes_copied,
1466                size,
1467                "Checksumming",
1468            );
1469            if let Err(error) =
1470                hash_primary(&mut entity, &mut p_stream, src_path)
1471            {
1472                return handle_item_error(
1473                    src_path,
1474                    JournalErrorStage::PayloadRead,
1475                    error.context("Failed to checksum source payload"),
1476                    args,
1477                    journal,
1478                    stats,
1479                );
1480            }
1481            match p_stream.finish() {
1482                Ok(warnings) => {
1483                    for warning in warnings {
1484                        eprintln!("WARNING: {warning}");
1485                        journal.record_warning("FileReadWarning", &warning)?;
1486                        entity.metadata.push_warning(warning);
1487                    }
1488                }
1489                Err(error) => {
1490                    return handle_item_error(
1491                        src_path,
1492                        JournalErrorStage::PayloadRead,
1493                        error.context("Failed to complete source checksumming"),
1494                        args,
1495                        journal,
1496                        stats,
1497                    );
1498                }
1499            }
1500        }
1501    }
1502
1503    let record_pre_materialization = match &entity.kind {
1504        FileEntityKind::Fifo => {
1505            args.copy_specials_as_specials && !args.copy_fifos_as_regular_files
1506        }
1507        FileEntityKind::BlockDevice { .. } => {
1508            args.copy_specials_as_specials
1509                && !args.copy_block_devices_as_regular_files
1510        }
1511        FileEntityKind::CharDevice { .. } => args.copy_specials_as_specials,
1512        FileEntityKind::Socket | FileEntityKind::Door => false,
1513        _ => true,
1514    };
1515
1516    if !args.dry_run
1517        && record_pre_materialization
1518        && !(options.existing_entry_policy
1519            == ctb_io::file::ExistingEntryPolicy::Refuse
1520            && std::fs::symlink_metadata(&effective_dest_path).is_ok())
1521    {
1522        record_journal_entry(journal, &effective_dest_path, &entity)?;
1523        journal.commit_batch()?;
1524    }
1525
1526    // 3. Hardlink detection (nlink > 1)
1527    if entity.identity.nlink > 1 && entity.is_regular() {
1528        let first_target = match hardlink_map.lookup(&entity, dest_rel_path) {
1529            Ok(target) => target,
1530            Err(error) => {
1531                return handle_item_error(
1532                    src_path,
1533                    JournalErrorStage::PostCheck,
1534                    error,
1535                    args,
1536                    journal,
1537                    stats,
1538                );
1539            }
1540        };
1541
1542        if let Some(first_target_rel) = first_target {
1543            let this_full_path = match &entity.identity.relative_path {
1544                Some(p) => dest_dir.root_path().join(p),
1545                None => dest_dir.root_path().to_path_buf(),
1546            };
1547            let first_full_path = dest_dir.root_path().join(first_target_rel);
1548            let is_self = effective_dest_path == first_full_path
1549                || this_full_path == first_full_path
1550                || std::fs::canonicalize(&effective_dest_path)
1551                    .ok()
1552                    .as_deref()
1553                    .is_some_and(|path| {
1554                        std::fs::canonicalize(&first_full_path)
1555                            .is_ok_and(|first| path == first)
1556                    });
1557            if !is_self {
1558                if let Err(error) =
1559                    validate_copy_source(&snapshot, &mut entity, journal)
1560                {
1561                    return handle_item_error(
1562                        src_path,
1563                        JournalErrorStage::PostCheck,
1564                        error,
1565                        args,
1566                        journal,
1567                        stats,
1568                    );
1569                }
1570                let original_entity = entity.clone();
1571                entity.kind = FileEntityKind::Hardlink {
1572                    target_relative_path: LinkPath::from_relative_path(
1573                        first_target_rel,
1574                    )?,
1575                };
1576                if is_verified_resumed_destination_entry(
1577                    dest_rel_path,
1578                    &effective_dest_path,
1579                    &entity,
1580                    dest_dir,
1581                    options,
1582                    args,
1583                    journal,
1584                ) {
1585                    record_journal_entry(
1586                        journal,
1587                        &effective_dest_path,
1588                        &entity,
1589                    )?;
1590                    files_to_verify.push((
1591                        src_path.to_path_buf(),
1592                        effective_dest_path.clone(),
1593                        original_entity,
1594                    ));
1595                    return Ok(Some(effective_dest_path));
1596                }
1597                let receipt = match materialize_entity(
1598                    &entity, None, dest_dir, options,
1599                ) {
1600                    Ok(receipt) => receipt,
1601                    Err(err) => {
1602                        record_materialization_failure(
1603                            journal,
1604                            &effective_dest_path,
1605                            &original_entity,
1606                            &err,
1607                        )?;
1608                        return handle_item_error(
1609                            src_path,
1610                            JournalErrorStage::Materialize,
1611                            err,
1612                            args,
1613                            journal,
1614                            stats,
1615                        );
1616                    }
1617                };
1618                receipt.apply_stream_adaptations(&mut entity);
1619                record_materialization_warnings(
1620                    journal,
1621                    &mut entity,
1622                    receipt.warnings,
1623                )?;
1624                let final_dest = receipt.destination_path;
1625                if final_dest != dest_path {
1626                    if let Ok(actual_rel) = compute_journal_relative_path(
1627                        journal.destination(),
1628                        &final_dest,
1629                    ) {
1630                        if !actual_rel.as_os_str().is_empty()
1631                            && actual_rel != dest_rel_path
1632                        {
1633                            entity.metadata.set_materialized_relative_path(
1634                                dest_rel_path,
1635                                &actual_rel,
1636                            );
1637                            entity.identity.relative_path = Some(actual_rel);
1638                        }
1639                    }
1640                }
1641                stats.hardlinks_created =
1642                    stats.hardlinks_created.saturating_add(1);
1643                record_journal_entry(journal, &final_dest, &entity)?;
1644                files_to_verify.push((
1645                    src_path.to_path_buf(),
1646                    final_dest.clone(),
1647                    original_entity,
1648                ));
1649                return Ok(Some(final_dest));
1650            }
1651        }
1652    }
1653
1654    if is_verified_resumed_destination_entry(
1655        dest_rel_path,
1656        &effective_dest_path,
1657        &entity,
1658        dest_dir,
1659        options,
1660        args,
1661        journal,
1662    ) {
1663        if let Err(error) =
1664            validate_copy_source(&snapshot, &mut entity, journal)
1665        {
1666            return handle_item_error(
1667                src_path,
1668                JournalErrorStage::PostCheck,
1669                error,
1670                args,
1671                journal,
1672                stats,
1673            );
1674        }
1675        if let Some(snap) = journal.snapshot() {
1676            if let Some(committed) = entity
1677                .identity
1678                .path_bytes()
1679                .and_then(|b| snap.committed_entities.get(b))
1680            {
1681                if committed.metadata.used_noatime() {
1682                    entity.metadata.set_used_noatime(true);
1683                    journal.record_noatime_used(true);
1684                }
1685            }
1686        }
1687        if entity.is_regular() {
1688            stats.files_skipped_identical =
1689                stats.files_skipped_identical.saturating_add(1);
1690        }
1691        if entity.identity.nlink > 1 && entity.is_regular() {
1692            if let Some(ref rel) = entity.identity.relative_path {
1693                hardlink_map.commit(&entity, rel, Some(&snapshot));
1694            }
1695        }
1696        record_journal_entry(journal, &effective_dest_path, &entity)?;
1697        files_to_verify.push((
1698            src_path.to_path_buf(),
1699            effective_dest_path.clone(),
1700            entity,
1701        ));
1702        return Ok(Some(effective_dest_path));
1703    }
1704
1705    // 4. Special files (FIFOs, device nodes, sockets, doors)
1706    let mut fifo_payload_data: Option<Vec<u8>> = None;
1707    match &entity.kind {
1708        FileEntityKind::Fifo
1709        | FileEntityKind::CharDevice { .. }
1710        | FileEntityKind::BlockDevice { .. }
1711        | FileEntityKind::Socket
1712        | FileEntityKind::Door => {
1713            if args.copy_fifos_as_regular_files
1714                && matches!(entity.kind, FileEntityKind::Fifo)
1715            {
1716                #[cfg(unix)]
1717                {
1718                    if args.dry_run {
1719                        entity.kind = FileEntityKind::Regular {
1720                            size: 0,
1721                            sha256: [0_u8; 32],
1722                            is_sparse: false,
1723                            extents: Vec::new(),
1724                        };
1725                    } else {
1726                        let mut fifo_file = match std::fs::File::open(src_path)
1727                            .with_context(|| {
1728                                format!(
1729                                    "Failed to open FIFO: {}",
1730                                    src_path.display()
1731                                )
1732                            }) {
1733                            Ok(f) => f,
1734                            Err(err) => {
1735                                return handle_item_error(
1736                                    src_path,
1737                                    JournalErrorStage::PayloadOpen,
1738                                    err,
1739                                    args,
1740                                    journal,
1741                                    stats,
1742                                );
1743                            }
1744                        };
1745                        let mut data = Vec::new();
1746                        use std::io::Read;
1747                        if let Err(err) = fifo_file
1748                            .read_to_end(&mut data)
1749                            .with_context(|| {
1750                                format!(
1751                                    "Failed to read FIFO: {}",
1752                                    src_path.display()
1753                                )
1754                            })
1755                        {
1756                            return handle_item_error(
1757                                src_path,
1758                                JournalErrorStage::PayloadRead,
1759                                err,
1760                                args,
1761                                journal,
1762                                stats,
1763                            );
1764                        }
1765                        let Ok(size) = u64::try_from(data.len()) else {
1766                            let err = anyhow::anyhow!(
1767                                "FIFO data length exceeds u64::MAX: {}",
1768                                src_path.display()
1769                            );
1770                            return handle_item_error(
1771                                src_path,
1772                                JournalErrorStage::PayloadRead,
1773                                err,
1774                                args,
1775                                journal,
1776                                stats,
1777                            );
1778                        };
1779                        let extents = if size > 0 {
1780                            vec![ctb_io::file::payload::Extent::Data {
1781                                offset: 0,
1782                                length: size,
1783                            }]
1784                        } else {
1785                            Vec::new()
1786                        };
1787                        entity.kind = FileEntityKind::Regular {
1788                            size,
1789                            sha256: [0_u8; 32],
1790                            is_sparse: false,
1791                            extents,
1792                        };
1793                        fifo_payload_data = Some(data);
1794                    }
1795                }
1796                #[cfg(not(unix))]
1797                {
1798                    stats.special_files_skipped =
1799                        stats.special_files_skipped.saturating_add(1);
1800                    return Ok(None);
1801                }
1802            } else if args.copy_block_devices_as_regular_files
1803                && matches!(entity.kind, FileEntityKind::BlockDevice { .. })
1804            {
1805                let dev_file =
1806                    match std::fs::File::open(src_path).with_context(|| {
1807                        format!(
1808                            "Failed to open block device: {}",
1809                            src_path.display()
1810                        )
1811                    }) {
1812                        Ok(f) => f,
1813                        Err(err) => {
1814                            return handle_item_error(
1815                                src_path,
1816                                JournalErrorStage::PayloadOpen,
1817                                err,
1818                                args,
1819                                journal,
1820                                stats,
1821                            );
1822                        }
1823                    };
1824                let size = match query_block_device_size(&dev_file)
1825                    .with_context(|| {
1826                        format!(
1827                            "Failed to determine size of block device: {}",
1828                            src_path.display()
1829                        )
1830                    }) {
1831                    Ok(s) => s,
1832                    Err(err) => {
1833                        return handle_item_error(
1834                            src_path,
1835                            JournalErrorStage::MetadataRead,
1836                            err,
1837                            args,
1838                            journal,
1839                            stats,
1840                        );
1841                    }
1842                };
1843                entity.kind = FileEntityKind::Regular {
1844                    size,
1845                    sha256: [0_u8; 32],
1846                    is_sparse: false,
1847                    extents: vec![ctb_io::file::payload::Extent::Data {
1848                        offset: 0,
1849                        length: size,
1850                    }],
1851                };
1852            } else if args.copy_specials_as_specials
1853                && !matches!(
1854                    entity.kind,
1855                    FileEntityKind::Socket | FileEntityKind::Door
1856                )
1857            {
1858                if let Err(error) =
1859                    validate_copy_source(&snapshot, &mut entity, journal)
1860                {
1861                    return handle_item_error(
1862                        src_path,
1863                        JournalErrorStage::PostCheck,
1864                        error,
1865                        args,
1866                        journal,
1867                        stats,
1868                    );
1869                }
1870                let receipt = match materialize_entity(
1871                    &entity, None, dest_dir, options,
1872                ) {
1873                    Ok(receipt) => receipt,
1874                    Err(err) => {
1875                        record_materialization_failure(
1876                            journal, dest_path, &entity, &err,
1877                        )?;
1878                        return handle_item_error(
1879                            src_path,
1880                            JournalErrorStage::Materialize,
1881                            err,
1882                            args,
1883                            journal,
1884                            stats,
1885                        );
1886                    }
1887                };
1888                receipt.apply_stream_adaptations(&mut entity);
1889                record_materialization_warnings(
1890                    journal,
1891                    &mut entity,
1892                    receipt.warnings,
1893                )?;
1894                let final_dest = receipt.destination_path;
1895                if final_dest != dest_path {
1896                    if let Ok(actual_rel) = compute_journal_relative_path(
1897                        journal.destination(),
1898                        &final_dest,
1899                    ) {
1900                        if !actual_rel.as_os_str().is_empty()
1901                            && actual_rel != dest_rel_path
1902                        {
1903                            entity.metadata.set_materialized_relative_path(
1904                                dest_rel_path,
1905                                &actual_rel,
1906                            );
1907                            entity.identity.relative_path = Some(actual_rel);
1908                        }
1909                    }
1910                }
1911                stats.special_files_created =
1912                    stats.special_files_created.saturating_add(1);
1913                record_journal_entry(journal, &final_dest, &entity)?;
1914                files_to_verify.push((
1915                    src_path.to_path_buf(),
1916                    final_dest.clone(),
1917                    entity,
1918                ));
1919                return Ok(Some(final_dest));
1920            } else if matches!(
1921                entity.kind,
1922                FileEntityKind::Socket | FileEntityKind::Door
1923            ) && args.copy_specials_as_specials
1924            {
1925                let err = anyhow::anyhow!(
1926                    "Unsupported special file cannot be copied as a special node: {}",
1927                    src_path.display()
1928                );
1929                return handle_item_error(
1930                    src_path,
1931                    JournalErrorStage::Materialize,
1932                    err,
1933                    args,
1934                    journal,
1935                    stats,
1936                );
1937            } else {
1938                stats.special_files_skipped =
1939                    stats.special_files_skipped.saturating_add(1);
1940                return Ok(None);
1941            }
1942        }
1943        _ => {}
1944    }
1945
1946    // 5. Regular files: Sparse support, in-flight SHA-256, atomic rename
1947    let initial_size = match &entity.kind {
1948        FileEntityKind::Regular { size, .. } => *size,
1949        _ => 0,
1950    };
1951
1952    // Materialize payload
1953    let apple_single_data = snapshot.interpreted_payload()?;
1954
1955    let memory_payload_data = apple_single_data.or(fifo_payload_data);
1956
1957    let mut entity = entity;
1958    let (receipt, file_used_noatime) = if args.dry_run {
1959        (materialize_entity(&entity, None, dest_dir, options), false)
1960    } else if let Some(mem_bytes) = memory_payload_data.as_ref() {
1961        let mut mem_payload =
1962            match ctb_io::file::MemoryPayloadSource::new(mem_bytes.clone())
1963                .and_then(|payload| CapturedPayload::new(payload, &snapshot))
1964            {
1965                Ok(p) => p,
1966                Err(err) => {
1967                    return handle_item_error(
1968                        src_path,
1969                        JournalErrorStage::PayloadOpen,
1970                        err,
1971                        args,
1972                        journal,
1973                        stats,
1974                    );
1975                }
1976            };
1977        (
1978            materialize_entity(
1979                &entity,
1980                Some(&mut mem_payload),
1981                dest_dir,
1982                options,
1983            ),
1984            false,
1985        )
1986    } else if matches!(entity.kind, FileEntityKind::Regular { .. }) {
1987        let payload = match open_payload(src_path, &snapshot) {
1988            Ok(p) => p,
1989            Err(err) => {
1990                return handle_item_error(
1991                    src_path,
1992                    JournalErrorStage::PayloadOpen,
1993                    err,
1994                    args,
1995                    journal,
1996                    stats,
1997                );
1998            }
1999        };
2000        let noatime = payload.opened_with_noatime();
2001        let mut progress_payload = ProgressStream::new(
2002            payload,
2003            progress,
2004            copy_task,
2005            stats.files_copied,
2006            stats.bytes_copied,
2007            initial_size,
2008            "Writing",
2009        );
2010        (
2011            materialize_entity(
2012                &entity,
2013                Some(&mut progress_payload),
2014                dest_dir,
2015                options,
2016            ),
2017            noatime,
2018        )
2019    } else {
2020        (materialize_entity(&entity, None, dest_dir, options), false)
2021    };
2022    let receipt = match receipt.with_context(|| {
2023        format!(
2024            "copying '{}' -> '{}'",
2025            src_path.display(),
2026            effective_dest_path.display()
2027        )
2028    }) {
2029        Ok(r) => r,
2030        Err(err) => {
2031            record_materialization_failure(
2032                journal,
2033                &effective_dest_path,
2034                &entity,
2035                &err,
2036            )?;
2037            return handle_item_error(
2038                src_path,
2039                JournalErrorStage::Materialize,
2040                err,
2041                args,
2042                journal,
2043                stats,
2044            );
2045        }
2046    };
2047    receipt.apply_stream_adaptations(&mut entity);
2048    record_materialization_warnings(journal, &mut entity, receipt.warnings)?;
2049
2050    if file_used_noatime {
2051        entity.metadata.set_used_noatime(true);
2052        journal.record_noatime_used(true);
2053    }
2054
2055    if let Err(error) = validate_copy_source(&snapshot, &mut entity, journal) {
2056        return handle_item_error(
2057            src_path,
2058            JournalErrorStage::PostCheck,
2059            error,
2060            args,
2061            journal,
2062            stats,
2063        );
2064    }
2065
2066    if receipt.skipped_identical {
2067        stats.files_skipped_identical =
2068            stats.files_skipped_identical.saturating_add(1);
2069    } else {
2070        stats.files_copied = stats.files_copied.saturating_add(1);
2071    }
2072    stats.bytes_copied =
2073        stats.bytes_copied.saturating_add(receipt.bytes_written);
2074
2075    if receipt.destination_path != dest_path {
2076        if let Ok(actual_rel) = compute_journal_relative_path(
2077            journal.destination(),
2078            &receipt.destination_path,
2079        ) {
2080            if !actual_rel.as_os_str().is_empty() {
2081                if actual_rel != dest_rel_path {
2082                    entity.metadata.set_materialized_relative_path(
2083                        dest_rel_path,
2084                        &actual_rel,
2085                    );
2086                }
2087                entity.identity.relative_path = Some(actual_rel);
2088            }
2089        }
2090    }
2091
2092    if entity.identity.nlink > 1 && entity.is_regular() {
2093        if let Some(ref rel) = entity.identity.relative_path {
2094            journal.commit_batch()?;
2095            hardlink_map.commit(&entity, rel, Some(&snapshot));
2096        }
2097    }
2098
2099    if let FileEntityKind::Regular { ref mut sha256, .. } = entity.kind {
2100        if *sha256 == [0_u8; 32] {
2101            if let Some(h) = receipt.sha256 {
2102                *sha256 = h;
2103            }
2104        }
2105    }
2106
2107    record_journal_entry(journal, &receipt.destination_path, &entity)?;
2108    let final_dest = receipt.destination_path;
2109    files_to_verify.push((src_path.to_path_buf(), final_dest.clone(), entity));
2110
2111    Ok(Some(final_dest))
2112}
2113
2114fn is_verified_resumed_destination_entry(
2115    dest_rel_path: &Path,
2116    effective_dest_path: &Path,
2117    entity: &FileEntity,
2118    dest_dir: &SandboxableDir,
2119    options: &MaterializeOptions,
2120    args: &CscArgs,
2121    journal: &StateJournal,
2122) -> bool {
2123    if args.dry_run
2124        || options.existing_entry_policy
2125            != ctb_io::file::ExistingEntryPolicy::Refuse
2126        || std::fs::symlink_metadata(effective_dest_path).is_err()
2127    {
2128        return false;
2129    }
2130    let Some(snap) = journal.snapshot() else {
2131        return false;
2132    };
2133    let rel_bytes = entity.identity.path_bytes();
2134    let Some(committed_entity) = rel_bytes
2135        .and_then(|bytes| snap.committed_entities.get(bytes))
2136        .or_else(|| {
2137            snap.materialized_path_for(dest_rel_path)
2138                .and_then(|mat_rel| {
2139                    snap.committed_entities
2140                        .get(mat_rel.as_os_str().as_encoded_bytes())
2141                })
2142        })
2143    else {
2144        return false;
2145    };
2146    if !committed_entity.metadata.errors.is_empty() || committed_entity.is_dir()
2147    {
2148        return false;
2149    }
2150    if !snap.applied_directories.is_empty() {
2151        // Reason for fallback: top-level relative paths without a parent directory reside in the destination root "."
2152        let parent_rel = entity
2153            .identity
2154            .relative_path
2155            .as_deref()
2156            .and_then(Path::parent)
2157            .filter(|p| !p.as_os_str().is_empty())
2158            .unwrap_or_else(|| Path::new("."));
2159        if dest_dir
2160            .authorize_metadata(parent_rel, options.existing_entry_policy)
2161            .is_err()
2162        {
2163            return false;
2164        }
2165    }
2166    match (&entity.kind, &committed_entity.kind) {
2167        (
2168            FileEntityKind::Regular { size, sha256, .. },
2169            FileEntityKind::Regular {
2170                size: committed_size,
2171                sha256: committed_sha256,
2172                ..
2173            },
2174        ) => {
2175            if size != committed_size
2176                || *sha256 == [0_u8; 32]
2177                || (*committed_sha256 != [0_u8; 32]
2178                    && sha256 != committed_sha256)
2179            {
2180                return false;
2181            }
2182        }
2183        (
2184            FileEntityKind::Hardlink {
2185                target_relative_path,
2186            },
2187            FileEntityKind::Hardlink {
2188                target_relative_path: committed_target,
2189            },
2190        ) => {
2191            if target_relative_path != committed_target {
2192                return false;
2193            }
2194        }
2195        (FileEntityKind::Hardlink { .. }, FileEntityKind::Regular { .. }) => {}
2196        (
2197            FileEntityKind::Symlink { target },
2198            FileEntityKind::Symlink {
2199                target: committed_target,
2200            },
2201        ) => {
2202            if target != committed_target {
2203                return false;
2204            }
2205        }
2206        (a, b) if a != b => return false,
2207        _ => {}
2208    }
2209    let check_atime = args.should_check_atime()
2210        || (entity.is_regular()
2211            && committed_entity.metadata.used_noatime()
2212            && !args.best_effort_metadata);
2213    verify_materialized_entity_ext(
2214        effective_dest_path,
2215        entity,
2216        options.strict_lossless,
2217        check_atime,
2218        args.should_check_ctime(),
2219        options.check_birthtime,
2220    )
2221    .is_ok()
2222}
2223
2224pub(crate) fn compute_journal_relative_path(
2225    journal_dest: &Path,
2226    dest_path: &Path,
2227) -> Result<PathBuf> {
2228    // Reason for fallback: path not prefixed with "./" retains original path unchanged
2229    let norm_dest = dest_path.strip_prefix("./").unwrap_or(dest_path);
2230    // Reason for fallback: path not prefixed with "./" retains original path unchanged
2231    let norm_journal = journal_dest.strip_prefix("./").unwrap_or(journal_dest);
2232
2233    if norm_journal.as_os_str().is_empty() || norm_journal == Path::new(".") {
2234        return Ok(norm_dest.to_path_buf());
2235    }
2236
2237    if let Ok(rel) = norm_dest.strip_prefix(norm_journal) {
2238        // Reason for fallback: path not prefixed with "./" retains original path unchanged
2239        return Ok(rel.strip_prefix("./").unwrap_or(rel).to_path_buf());
2240    }
2241    if let Ok(rel) = dest_path.strip_prefix(journal_dest) {
2242        return Ok(rel.to_path_buf());
2243    }
2244
2245    let canonical_root =
2246        std::fs::canonicalize(journal_dest).with_context(|| {
2247            format!(
2248                "Failed to resolve journal destination {}",
2249                journal_dest.display()
2250            )
2251        })?;
2252    let relative =
2253        dest_path.strip_prefix(&canonical_root).with_context(|| {
2254            format!(
2255                "Journal entry {} is outside destination {}",
2256                dest_path.display(),
2257                canonical_root.display()
2258            )
2259        })?;
2260    Ok(relative.to_path_buf())
2261}
2262
2263fn validate_copy_source(
2264    snapshot: &ctb_io::file::payload::SourceSnapshot,
2265    entity: &mut FileEntity,
2266    journal: &mut StateJournal,
2267) -> Result<()> {
2268    snapshot.retain_changes(snapshot.validate()?)?;
2269    crate::journal::capture::finalize_warnings(
2270        snapshot,
2271        entity,
2272        &mut |code, warning| journal.record_warning(code, warning),
2273    )
2274}
2275
2276fn record_materialization_warnings(
2277    journal: &mut StateJournal,
2278    entity: &mut FileEntity,
2279    warnings: Vec<String>,
2280) -> Result<()> {
2281    for warning in warnings {
2282        entity.metadata.push_warning(warning.clone());
2283        journal.record_warning("FileMaterializationWarning", &warning)?;
2284        warn_fmt!("{}: {}", entity.identity.display_path(), warning);
2285    }
2286    Ok(())
2287}
2288
2289fn record_materialization_failure(
2290    journal: &mut StateJournal,
2291    dest_path: &Path,
2292    entity: &FileEntity,
2293    error: &anyhow::Error,
2294) -> Result<()> {
2295    let mut failed_entity = entity.clone();
2296    failed_entity
2297        .metadata
2298        .push_error(format!("Materialization failed: {error:#}"));
2299    record_journal_entry(journal, dest_path, &failed_entity)?;
2300    journal.commit_batch()
2301}
2302
2303fn record_journal_entry(
2304    journal: &mut StateJournal,
2305    dest_path: &Path,
2306    entity: &FileEntity,
2307) -> Result<()> {
2308    let mut journal_entity = entity.clone();
2309    let rel = compute_journal_relative_path(journal.destination(), dest_path)?;
2310    if !rel.as_os_str().is_empty() && rel != Path::new(".") {
2311        if let Some(orig_rel) = journal_entity
2312            .metadata
2313            .source_relative_path()
2314            .or_else(|| journal_entity.identity.relative_path.clone())
2315        {
2316            if !orig_rel.as_os_str().is_empty()
2317                && orig_rel != Path::new(".")
2318                && orig_rel != rel
2319            {
2320                journal_entity
2321                    .metadata
2322                    .set_materialized_relative_path(&orig_rel, &rel);
2323            }
2324        }
2325    }
2326    journal_entity.identity.relative_path = Some(rel);
2327    journal.record_entity(&journal_entity);
2328    Ok(())
2329}
2330#[cfg(test)]
2331#[allow(
2332    clippy::panic,
2333    clippy::expect_used,
2334    clippy::unwrap_used,
2335    clippy::unwrap_in_result,
2336    clippy::panic_in_result_fn,
2337    clippy::indexing_slicing,
2338    clippy::arithmetic_side_effects,
2339    reason = "Standard repository test boilerplate"
2340)]
2341mod fidelity_tests {
2342    use super::*;
2343    use crate::args::default_test_args;
2344    use crate::journal::read_journal_snapshot;
2345
2346    #[cfg(unix)]
2347    #[crate::ctb_test]
2348    fn test_final_tree_best_effort_late_warnings_persist_before_completion()
2349    -> Result<()> {
2350        use std::os::unix::fs::PermissionsExt;
2351        for fail_persistence in [false, true] {
2352            let temporary = tempfile::tempdir()?;
2353            let source = temporary.path().join("source");
2354            let destination = temporary.path().join("destination");
2355            std::fs::create_dir(&source)?;
2356            std::fs::create_dir(&destination)?;
2357            let journal_path = temporary.path().join("copy.cscjournal");
2358            let descriptor_path = temporary.path().join("copy.cscdesc");
2359            let mut journal = StateJournal::create_at_path(
2360                &journal_path,
2361                &descriptor_path,
2362                std::slice::from_ref(&source),
2363                &destination,
2364            )?;
2365            let mut args = default_test_args(
2366                vec![source.clone(), destination.clone()],
2367                temporary.path().to_path_buf(),
2368            );
2369            args.on_source_change = SourceChangePolicy::BestEffort;
2370            args.continue_on_error = true;
2371            let mut captured = CapturedSource::capture(
2372                &source,
2373                Some(&source),
2374                &Default::default(),
2375                args.on_source_change == SourceChangePolicy::BestEffort,
2376            )?;
2377            let mut tree = crate::journal::capture::CapturedTree::default();
2378            tree.retain(&captured.snapshot);
2379            let early_warning =
2380                format!("early cleanup warning: {}", source.display());
2381            captured
2382                .snapshot
2383                .retain_cleanup_warnings(vec![early_warning.clone()])?;
2384            validate_copy_source(
2385                &captured.snapshot,
2386                &mut captured.entity,
2387                &mut journal,
2388            )?;
2389            record_journal_entry(&mut journal, &destination, &captured.entity)?;
2390            journal.commit_batch()?;
2391            tree.validate()?;
2392
2393            let mode = std::fs::metadata(&source)?.permissions().mode() ^ 0o100;
2394            std::fs::set_permissions(
2395                &source,
2396                std::fs::Permissions::from_mode(mode),
2397            )?;
2398            let late_cleanup =
2399                format!("late cleanup warning: {}", source.display());
2400            captured
2401                .snapshot
2402                .retain_cleanup_warnings(vec![late_cleanup.clone()])?;
2403            if fail_persistence {
2404                std::fs::remove_file(&descriptor_path)?;
2405                std::fs::create_dir(&descriptor_path)?;
2406            }
2407            let mut stats = CopyStats::default();
2408            let result =
2409                finalize_copy_pipeline(&tree, &args, &mut journal, &mut stats);
2410            assert_eq!(result.is_err(), fail_persistence, "{result:?}");
2411            let recorded = read_journal_snapshot(&journal_path)?;
2412            assert_eq!(recorded.is_completed, !fail_persistence);
2413            assert!(recorded.errors.is_empty());
2414            assert_eq!(
2415                recorded
2416                    .warnings
2417                    .iter()
2418                    .filter(|record| record.message == early_warning)
2419                    .count(),
2420                1
2421            );
2422            let changed = recorded
2423                .warnings
2424                .iter()
2425                .find(|record| record.code == "SourceModifiedDuringCopy")
2426                .context("Missing late source change warning")?;
2427            assert!(changed.message.contains(&source.display().to_string()));
2428            assert!(
2429                changed
2430                    .message
2431                    .contains("changed during copy; proceeding best-effort")
2432            );
2433            if fail_persistence {
2434                assert!(
2435                    format!("{:#}", result.unwrap_err())
2436                        .contains("operation is durable")
2437                );
2438                assert!(journal.pending_descriptor_status().is_some());
2439            } else {
2440                assert_eq!(
2441                    recorded
2442                        .warnings
2443                        .iter()
2444                        .filter(|record| record.message == late_cleanup)
2445                        .count(),
2446                    1
2447                );
2448                let descriptor = std::fs::read_to_string(&descriptor_path)?;
2449                assert!(
2450                    descriptor
2451                        .contains("Status: Completed with 3 warning(s)\n")
2452                );
2453                assert!(!descriptor.contains("Status: Completed\n"));
2454                tree.validate()?;
2455                let mut repeated = Vec::new();
2456                tree.visit_pending_warnings(&mut |code, warning| {
2457                    repeated.push((code.to_owned(), warning.to_owned()));
2458                    Ok(())
2459                })?;
2460                assert!(repeated.is_empty());
2461                assert_eq!(
2462                    read_journal_snapshot(&journal_path)?.warnings,
2463                    recorded.warnings
2464                );
2465            }
2466        }
2467        Ok(())
2468    }
2469
2470    #[crate::ctb_test]
2471    fn test_final_tree_change_after_validated_fixup_is_journaled_before_completion()
2472    -> Result<()> {
2473        for continue_on_error in [false, true] {
2474            let temporary = tempfile::tempdir()?;
2475            let source = temporary.path().join("source");
2476            let destination = temporary.path().join("destination");
2477            std::fs::create_dir(&source)?;
2478            std::fs::create_dir(&destination)?;
2479            let journal_path = temporary.path().join("copy.cscjournal");
2480            let descriptor_path = temporary.path().join("copy.cscdesc");
2481            let mut journal = StateJournal::create_at_path(
2482                &journal_path,
2483                &descriptor_path,
2484                std::slice::from_ref(&source),
2485                &destination,
2486            )?;
2487            let mut captured = CapturedSource::capture(
2488                &source,
2489                Some(&source),
2490                &Default::default(),
2491                false,
2492            )?;
2493            let mut captured_tree =
2494                crate::journal::capture::CapturedTree::default();
2495            captured_tree.retain(&captured.snapshot);
2496            validate_copy_source(
2497                &captured.snapshot,
2498                &mut captured.entity,
2499                &mut journal,
2500            )?;
2501            record_journal_entry(&mut journal, &destination, &captured.entity)?;
2502            journal.commit_batch()?;
2503            captured_tree.validate()?;
2504
2505            std::fs::rename(&source, temporary.path().join("original-source"))?;
2506            std::fs::create_dir(&source)?;
2507            let mut args = default_test_args(
2508                vec![source, destination],
2509                temporary.path().to_path_buf(),
2510            );
2511            args.continue_on_error = continue_on_error;
2512            let mut stats = CopyStats {
2513                dirs_created: 1,
2514                ..Default::default()
2515            };
2516            let result = finalize_copy_pipeline(
2517                &captured_tree,
2518                &args,
2519                &mut journal,
2520                &mut stats,
2521            );
2522            assert_eq!(result.is_ok(), continue_on_error, "{result:?}");
2523            let snapshot = read_journal_snapshot(&journal_path)?;
2524            assert_eq!(snapshot.errors.len(), 1);
2525            assert!(matches!(
2526                snapshot.errors[0].stage,
2527                JournalErrorStage::PostCheck
2528            ));
2529            assert_eq!(snapshot.errors[0].path, journal.destination());
2530            assert_eq!(snapshot.is_completed, continue_on_error);
2531            assert!(!snapshot.is_completed || !snapshot.errors.is_empty());
2532            assert_eq!(snapshot.committed_entities.len(), 1);
2533            assert_eq!(stats.files_failed, u64::from(continue_on_error));
2534            assert_eq!(stats.dirs_created, 1);
2535            let descriptor = std::fs::read_to_string(&descriptor_path)?;
2536            assert!(descriptor.contains("ErrorsCount: 1\n"));
2537            assert!(!descriptor.contains("Status: Completed\n"));
2538            if continue_on_error {
2539                assert!(
2540                    descriptor.contains("Status: Completed with 1 error(s)\n")
2541                );
2542            } else {
2543                let error = result.unwrap_err();
2544                assert!(
2545                    format!("{error:#}")
2546                        .contains(&snapshot.errors[0].error_message)
2547                );
2548                assert!(descriptor.contains("Status: Failed: "));
2549            }
2550            assert!(journal.pending_descriptor_status().is_none());
2551        }
2552        Ok(())
2553    }
2554
2555    #[cfg(unix)]
2556    #[crate::ctb_test]
2557    fn capture_copy_retains_snapshot_cleanup_warning_once() -> Result<()> {
2558        let temporary = tempfile::tempdir()?;
2559        let path = temporary.path().join("link");
2560        std::os::unix::fs::symlink("target", &path)?;
2561        let mut source =
2562            CapturedSource::capture(&path, None, &Default::default(), false)?;
2563        let destination = temporary.path().join("destination");
2564        let journal_path = temporary.path().join("copy.cscjournal");
2565        let mut journal = StateJournal::create_at_path(
2566            &journal_path,
2567            &temporary.path().join("copy.cscdesc"),
2568            std::slice::from_ref(&path),
2569            &destination,
2570        )?;
2571        record_entity_warnings(&source.entity, &mut journal)?;
2572        let warning = "injected symlink cleanup warning".to_owned();
2573        source
2574            .snapshot
2575            .retain_cleanup_warnings(vec![warning.clone()])?;
2576        validate_copy_source(
2577            &source.snapshot,
2578            &mut source.entity,
2579            &mut journal,
2580        )?;
2581        validate_copy_source(
2582            &source.snapshot,
2583            &mut source.entity,
2584            &mut journal,
2585        )?;
2586        record_journal_entry(
2587            &mut journal,
2588            &destination.join("link"),
2589            &source.entity,
2590        )?;
2591        journal.commit_batch()?;
2592        let recorded = read_journal_snapshot(&journal_path)?;
2593        ensure!(
2594            recorded
2595                .warnings
2596                .iter()
2597                .filter(|record| record.message == warning)
2598                .count()
2599                == 1
2600        );
2601        ensure!(
2602            recorded
2603                .committed_entities
2604                .values()
2605                .any(|entity| entity.metadata.warnings.contains(&warning))
2606        );
2607        ensure!(source.snapshot.cleanup_warnings()?.contains(&warning));
2608        Ok(())
2609    }
2610
2611    #[crate::ctb_test]
2612    fn test_materialization_fidelity_warnings_are_journaled() {
2613        let temp = tempfile::tempdir().unwrap();
2614        let source = temp.path().join("source");
2615        std::fs::write(&source, b"payload").unwrap();
2616        let destination = temp.path().join("destination");
2617        let root = SandboxableDir::create_or_open(&destination).unwrap();
2618        let mut entity =
2619            FileEntity::from_filesystem(&source, Some(temp.path())).unwrap();
2620        entity.metadata.native.as_mut().unwrap().values.insert(
2621            "future.attribute".to_owned(),
2622            ctb_io::file::metadata::NativeMetadataValue::Bytes(vec![
2623                0, 255, 128,
2624            ]),
2625        );
2626        let journal_path = temp.path().join("copy.cscjournal");
2627        let mut journal = StateJournal::create_at_path(
2628            &journal_path,
2629            &temp.path().join("copy.cscdesc"),
2630            std::slice::from_ref(&source),
2631            &destination,
2632        )
2633        .unwrap();
2634        let mut strict_payload =
2635            ctb_io::file::MemoryPayloadSource::new(b"payload".to_vec())
2636                .unwrap();
2637        assert!(
2638            materialize_entity(
2639                &entity,
2640                Some(&mut strict_payload),
2641                &root,
2642                &MaterializeOptions::default()
2643            )
2644            .is_err()
2645        );
2646        assert!(!destination.join("source").exists());
2647        let mut options = MaterializeOptions {
2648            strict_lossless: false,
2649            ..Default::default()
2650        };
2651        for expected_identical in [false, true] {
2652            if expected_identical {
2653                options.existing_entry_policy =
2654                    ctb_io::file::ExistingEntryPolicy::Replace;
2655            }
2656            let mut payload =
2657                ctb_io::file::MemoryPayloadSource::new(b"payload".to_vec())
2658                    .unwrap();
2659            let receipt = materialize_entity(
2660                &entity,
2661                Some(&mut payload),
2662                &root,
2663                &options,
2664            )
2665            .unwrap();
2666            assert_eq!(
2667                receipt.skipped_identical,
2668                expected_identical && cfg!(unix)
2669            );
2670            assert!(
2671                receipt
2672                    .warnings
2673                    .iter()
2674                    .any(|warning| warning.contains("future.attribute"))
2675            );
2676            record_materialization_warnings(
2677                &mut journal,
2678                &mut entity,
2679                receipt.warnings,
2680            )
2681            .unwrap();
2682            record_journal_entry(
2683                &mut journal,
2684                &receipt.destination_path,
2685                &entity,
2686            )
2687            .unwrap();
2688            journal.commit_batch().unwrap();
2689            let snapshot = read_journal_snapshot(&journal_path).unwrap();
2690            assert!(
2691                snapshot.warnings.iter().any(|warning| warning.code
2692                    == "FileMaterializationWarning"
2693                    && warning.message.contains("future.attribute"))
2694            );
2695            let recorded = snapshot.committed_entities.values().next().unwrap();
2696            assert_eq!(recorded.metadata.warnings, entity.metadata.warnings);
2697            assert_eq!(recorded.metadata.native, entity.metadata.native);
2698            ctb_formats_dcstring::assert_dc_roundtrip(&recorded.metadata)
2699                .unwrap();
2700            assert_eq!(
2701                std::fs::read(&receipt.destination_path).unwrap(),
2702                b"payload"
2703            );
2704        }
2705    }
2706
2707    #[cfg(windows)]
2708    #[crate::ctb_test]
2709    fn test_windows_journal_paths_preserve_native_prefixes() {
2710        use ctb_io::file::identity::resolve_relative_path_for_os;
2711        let temp = tempfile::tempdir().unwrap();
2712        let sources = vec![
2713            PathBuf::from(r"C:\source"),
2714            PathBuf::from(r"\\server\share\source"),
2715        ];
2716        let destination = PathBuf::from(r"\\?\D:\destination");
2717        let journal_path = temp.path().join("copy.cscjournal");
2718        let journal = StateJournal::create_at_path(
2719            &journal_path,
2720            &temp.path().join("copy.cscdesc"),
2721            &sources,
2722            &destination,
2723        )
2724        .unwrap();
2725        let snapshot = read_journal_snapshot(journal.journal_path()).unwrap();
2726        assert_eq!(snapshot.sources, sources);
2727        assert_eq!(snapshot.destination, destination);
2728        assert!(resolve_relative_path_for_os(br"C:\source", false).is_err());
2729        assert!(
2730            resolve_relative_path_for_os(br"C:\source:stream", true).is_err()
2731        );
2732    }
2733
2734    #[crate::ctb_test]
2735    fn test_native_fidelity_errors_and_warnings_are_journaled() {
2736        for continue_on_error in [false, true] {
2737            let temp = tempfile::tempdir().unwrap();
2738            let source = temp.path().join("source");
2739            let destination = temp.path().join("destination");
2740            let journal_path = temp.path().join("copy.cscjournal");
2741            let desc_path = temp.path().join("copy.cscdesc");
2742            let mut journal = StateJournal::create_at_path(
2743                &journal_path,
2744                &desc_path,
2745                std::slice::from_ref(&source),
2746                &destination,
2747            )
2748            .unwrap();
2749            let mut entity =
2750                FileEntity::inaccessible(&source, None, "read failure");
2751            entity
2752                .metadata
2753                .push_warning("Native stream enumeration is unsupported");
2754            entity.metadata.push_warning("Failed to query file extents: sparse layout fidelity is unknown");
2755            entity.streams.push(
2756                ctb_io::file::AttachedStream::from_data(
2757                    Some(ctb_io::file::StreamName::from_windows_utf16(&[
2758                        58, 55296, 58, 36, 68, 65, 84, 65,
2759                    ])),
2760                    ctb_io::file::StreamKind::NtfsAlternateDataStream,
2761                    b"stream payload".to_vec(),
2762                )
2763                .unwrap(),
2764            );
2765            record_entity_warnings(&entity, &mut journal).unwrap();
2766            let native_error = std::io::Error::from_raw_os_error(2);
2767            let native_message = native_error.to_string();
2768            let error = anyhow::Error::new(native_error)
2769                .context("Failed to write Windows alternate data stream WindowsUtf16([58, 55296])")
2770                .context("copying source -> destination");
2771            record_materialization_failure(
2772                &mut journal,
2773                &destination,
2774                &entity,
2775                &error,
2776            )
2777            .unwrap();
2778            let mut args = default_test_args(
2779                vec![source.clone(), destination],
2780                temp.path().to_path_buf(),
2781            );
2782            args.continue_on_error = continue_on_error;
2783            let mut stats = CopyStats::default();
2784            let result = handle_item_error(
2785                &source,
2786                JournalErrorStage::Materialize,
2787                error,
2788                &args,
2789                &mut journal,
2790                &mut stats,
2791            );
2792            assert_eq!(result.is_ok(), continue_on_error);
2793            let snapshot = read_journal_snapshot(&journal_path).unwrap();
2794            assert_eq!(snapshot.errors.len(), 1);
2795            assert_eq!(snapshot.errors[0].os_error, Some(2));
2796            assert!(
2797                snapshot.errors[0]
2798                    .error_message
2799                    .contains("copying source -> destination")
2800            );
2801            assert!(
2802                snapshot.errors[0]
2803                    .error_message
2804                    .contains("WindowsUtf16([58, 55296])")
2805            );
2806            assert!(snapshot.errors[0].error_message.contains(&native_message));
2807            assert_eq!(snapshot.warnings.len(), entity.metadata.warnings.len());
2808            for (recorded, expected) in
2809                snapshot.warnings.iter().zip(&entity.metadata.warnings)
2810            {
2811                assert_eq!(recorded.code, "FileReadWarning");
2812                assert_eq!(&recorded.message, expected);
2813            }
2814            let recorded = snapshot.committed_entities.values().next().unwrap();
2815            assert_eq!(recorded.metadata.warnings, entity.metadata.warnings);
2816            assert!(
2817                recorded.metadata.errors.iter().any(
2818                    |message| message.contains("WindowsUtf16([58, 55296])")
2819                )
2820            );
2821            assert_eq!(recorded.streams[0].name, entity.streams[0].name);
2822            assert_eq!(recorded.streams[0].kind, entity.streams[0].kind);
2823            assert_eq!(recorded.streams[0].data, None);
2824            assert_eq!(
2825                recorded.streams[0].entity.kind,
2826                entity.streams[0].entity.kind
2827            );
2828        }
2829    }
2830
2831    #[crate::ctb_test]
2832    fn test_continue_on_error_cannot_discard_journal_failure() {
2833        let temp = tempfile::tempdir().unwrap();
2834        let source = temp.path().join("source");
2835        let destination = temp.path().join("destination");
2836        let desc_path = temp.path().join("copy.cscdesc");
2837        let mut journal = StateJournal::create_at_path(
2838            &temp.path().join("copy.cscjournal"),
2839            &desc_path,
2840            std::slice::from_ref(&source),
2841            &destination,
2842        )
2843        .unwrap();
2844        std::fs::remove_file(&desc_path).unwrap();
2845        std::fs::create_dir(&desc_path).unwrap();
2846        let mut args = default_test_args(
2847            vec![source.clone(), destination],
2848            temp.path().to_path_buf(),
2849        );
2850        args.continue_on_error = true;
2851        let mut stats = CopyStats::default();
2852        let error = handle_item_error(
2853            &source,
2854            JournalErrorStage::Materialize,
2855            anyhow::anyhow!("Native stream could not be preserved"),
2856            &args,
2857            &mut journal,
2858            &mut stats,
2859        )
2860        .unwrap_err();
2861        assert!(
2862            error
2863                .to_string()
2864                .contains("Native stream could not be preserved")
2865        );
2866        assert_eq!(stats.files_failed, 0);
2867    }
2868}
2869
2870#[cfg(test)]
2871#[allow(
2872    clippy::panic,
2873    clippy::expect_used,
2874    clippy::unwrap_used,
2875    clippy::unwrap_in_result,
2876    clippy::panic_in_result_fn,
2877    clippy::indexing_slicing,
2878    clippy::arithmetic_side_effects,
2879    reason = "Standard repository test boilerplate"
2880)]
2881mod tests {
2882    use super::*;
2883    use crate::args::{
2884        AppleDoubleStyle, default_test_args, default_verify_args,
2885    };
2886    use crate::cli::run_csc;
2887    use crate::journal::find_cscjournal;
2888    use crate::verifier::run_csc_verify;
2889    use ctb_utilities::cli::ToolResult;
2890    use std::fs;
2891    #[cfg(unix)]
2892    use std::os::unix::fs::PermissionsExt;
2893    use std::path::PathBuf;
2894    use tempfile::tempdir;
2895
2896    #[crate::ctb_test]
2897    fn test_copy_tree_with_verify() {
2898        let temp = tempdir().expect("create tempdir");
2899        let src = temp.path().join("src_dir");
2900        let dest = temp.path().join("dest_dir");
2901        let state = temp.path().join("state_dir");
2902        fs::create_dir_all(src.join("sub")).expect("create src sub");
2903        fs::create_dir_all(&state).expect("create state dir");
2904
2905        fs::write(src.join("file1.txt"), b"Hello, World!")
2906            .expect("write file1");
2907        fs::write(src.join("sub").join("file2.bin"), vec![42_u8; 1000])
2908            .expect("write file2");
2909
2910        let args = default_test_args(
2911            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
2912            state,
2913        );
2914
2915        let res = run_csc(args).expect("run csc");
2916        match res {
2917            ctb_utilities::cli::ToolResult::Immediate {
2918                stdout,
2919                exit_code,
2920                ..
2921            } => {
2922                assert_eq!(exit_code, 0);
2923                let out = String::from_utf8_lossy(&stdout);
2924                assert!(out.contains("Files copied:             2"));
2925                assert!(out.contains("Files verified:           2"));
2926            }
2927            _ => panic!("Expected Immediate ToolResult"),
2928        }
2929
2930        assert_eq!(
2931            fs::read(dest.join("file1.txt")).expect("read file1"),
2932            b"Hello, World!"
2933        );
2934        assert_eq!(
2935            fs::read(dest.join("sub").join("file2.bin")).expect("read file2"),
2936            vec![42_u8; 1000]
2937        );
2938    }
2939
2940    #[crate::ctb_test]
2941    fn test_hardlinks_preserved() {
2942        let temp = tempdir().expect("create tempdir");
2943        let src = temp.path().join("src_links");
2944        let dest = temp.path().join("dest_links");
2945        let state = temp.path().join("state_dir");
2946        fs::create_dir_all(&src).expect("create src");
2947        fs::create_dir_all(&state).expect("create state");
2948
2949        let f1 = src.join("orig.txt");
2950        fs::write(&f1, b"Shared content across hardlinks").expect("write orig");
2951
2952        let f2 = src.join("link.txt");
2953        fs::hard_link(&f1, &f2).expect("create hardlink");
2954
2955        let args = default_test_args(
2956            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
2957            state,
2958        );
2959
2960        run_csc(args).expect("run csc");
2961
2962        let dest_f1 = dest.join("orig.txt");
2963        let dest_f2 = dest.join("link.txt");
2964
2965        let m1 = fs::metadata(&dest_f1).expect("meta1");
2966        let m2 = fs::metadata(&dest_f2).expect("meta2");
2967
2968        #[cfg(unix)]
2969        {
2970            assert_eq!(m1.ino(), m2.ino());
2971            assert_eq!(m1.dev(), m2.dev());
2972            assert_eq!(m1.nlink(), 2);
2973        }
2974        #[cfg(windows)]
2975        {
2976            let id1 = ctb_io::file::identity::query_file_identity(&dest_f1)
2977                .expect("id1");
2978            let id2 = ctb_io::file::identity::query_file_identity(&dest_f2)
2979                .expect("id2");
2980            assert_eq!(id1, id2);
2981        }
2982    }
2983
2984    #[cfg(unix)]
2985    #[crate::ctb_test]
2986    fn test_symlinks_preserved() {
2987        let temp = tempdir().expect("create tempdir");
2988        let src = temp.path().join("src_sym");
2989        let dest = temp.path().join("dest_sym");
2990        let state = temp.path().join("state_dir");
2991        fs::create_dir_all(&src).expect("create src");
2992        fs::create_dir_all(&state).expect("create state");
2993
2994        let target_file = src.join("target.txt");
2995        fs::write(&target_file, b"Symlink target data").expect("write target");
2996
2997        let sym = src.join("sym.txt");
2998        std::os::unix::fs::symlink("target.txt", &sym).expect("create symlink");
2999
3000        let args = default_test_args(
3001            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
3002            state,
3003        );
3004
3005        run_csc(args).expect("run csc");
3006
3007        let dest_sym = dest.join("sym.txt");
3008        assert!(dest_sym.is_symlink());
3009        let read = fs::read_link(&dest_sym).expect("read symlink");
3010        assert_eq!(read, PathBuf::from("target.txt"));
3011    }
3012
3013    #[crate::ctb_test]
3014    fn test_hardlinks_across_destination_roots() {
3015        let temp = tempdir().unwrap();
3016        let first = temp.path().join("first");
3017        let second = temp.path().join("second");
3018        let dest = temp.path().join("dest");
3019        let state = temp.path().join("state");
3020        fs::create_dir(&first).unwrap();
3021        fs::create_dir(&second).unwrap();
3022        fs::create_dir(&state).unwrap();
3023        fs::write(first.join("shared"), b"shared data").unwrap();
3024        fs::write(second.join("shared"), b"unrelated data").unwrap();
3025        fs::hard_link(first.join("shared"), second.join("linked")).unwrap();
3026        run_csc(default_test_args(
3027            vec![first, second, dest.clone()],
3028            state.clone(),
3029        ))
3030        .unwrap();
3031        assert_eq!(
3032            fs::read(dest.join("second/linked")).unwrap(),
3033            b"shared data"
3034        );
3035        assert_eq!(
3036            fs::read(dest.join("second/shared")).unwrap(),
3037            b"unrelated data"
3038        );
3039        #[cfg(unix)]
3040        assert_eq!(
3041            fs::metadata(dest.join("first/shared")).unwrap().ino(),
3042            fs::metadata(dest.join("second/linked")).unwrap().ino()
3043        );
3044        #[cfg(windows)]
3045        assert_eq!(
3046            ctb_io::file::identity::query_file_identity(
3047                &dest.join("first/shared")
3048            )
3049            .unwrap(),
3050            ctb_io::file::identity::query_file_identity(
3051                &dest.join("second/linked")
3052            )
3053            .unwrap()
3054        );
3055        let result = run_csc_verify(&default_verify_args(
3056            find_cscjournal(&state),
3057            Some(dest),
3058        ))
3059        .unwrap();
3060        match result {
3061            ToolResult::Immediate { exit_code, .. } => assert_eq!(exit_code, 0),
3062            _ => panic!("Expected immediate verification result"),
3063        }
3064    }
3065
3066    #[cfg(unix)]
3067    #[crate::ctb_test]
3068    fn test_relative_destination_preserves_hardlinks_and_exact_symlink_bytes()
3069    -> Result<()> {
3070        use crate::journal::read_journal_snapshot;
3071        use std::os::unix::ffi::OsStrExt;
3072
3073        let cwd = std::env::current_dir()?;
3074        let temp = tempfile::tempdir_in(&cwd)?;
3075        let source = temp.path().join("source");
3076        let destination = temp.path().strip_prefix(&cwd)?.join("destination");
3077        let state = temp.path().join("state");
3078        fs::create_dir(&source)?;
3079        fs::create_dir(&state)?;
3080        fs::write(source.join("first"), b"shared data")?;
3081        fs::hard_link(source.join("first"), source.join("second"))?;
3082        let target = std::ffi::OsStr::from_bytes(b"./first//../\xff/");
3083        std::os::unix::fs::symlink(target, source.join("link"))?;
3084
3085        run_csc(default_test_args(
3086            vec![source.join(""), destination.clone()],
3087            state.clone(),
3088        ))?;
3089        assert_eq!(
3090            fs::metadata(destination.join("first"))?.ino(),
3091            fs::metadata(destination.join("second"))?.ino()
3092        );
3093        assert_eq!(
3094            fs::read_link(destination.join("link"))?
3095                .as_os_str()
3096                .as_encoded_bytes(),
3097            target.as_bytes()
3098        );
3099        let journal_path = find_cscjournal(&state);
3100        let snapshot = read_journal_snapshot(&journal_path)?;
3101        assert!(snapshot.committed_entities.values().any(|entity|
3102            matches!(&entity.kind, FileEntityKind::Hardlink { target_relative_path }
3103                if !target_relative_path.to_bytes().starts_with(b"/"))));
3104        let result = run_csc_verify(&default_verify_args(
3105            journal_path,
3106            Some(destination),
3107        ))?;
3108        match result {
3109            ToolResult::Immediate { exit_code, .. } => assert_eq!(exit_code, 0),
3110            _ => panic!("Expected immediate verification result"),
3111        }
3112        Ok(())
3113    }
3114
3115    #[cfg(unix)]
3116    #[crate::ctb_test]
3117    fn test_copy_preserves_raw_apple_single_stems() -> Result<()> {
3118        use ctb_io::file::apple_double::{
3119            AppleFormat, AppleSingleExtension,
3120            create_apple_archive_from_entity, write_apple_single_double,
3121        };
3122        use std::os::unix::ffi::OsStringExt;
3123
3124        let temp = tempfile::tempdir()?;
3125        let source = temp.path().join("source");
3126        let destination = temp.path().join("destination");
3127        let state = temp.path().join("state");
3128        std::fs::create_dir(&source)?;
3129        std::fs::create_dir(&state)?;
3130        let names = [
3131            std::ffi::OsString::from_vec(b"name\xff".to_vec()),
3132            std::ffi::OsString::from_vec(b"name\xfe".to_vec()),
3133            std::ffi::OsString::from("caf\u{e9}"),
3134            std::ffi::OsString::from("cafe\u{301}"),
3135        ];
3136        for name in &names {
3137            let data = name.as_encoded_bytes().to_vec();
3138            let entity = FileEntity::from_vec(data.clone());
3139            let archive = create_apple_archive_from_entity(
3140                &entity,
3141                AppleFormat::AppleSingle,
3142                Some(data),
3143            )?;
3144            let mut encoded = name.clone();
3145            encoded.push(".As");
3146            std::fs::write(
3147                source.join(encoded),
3148                write_apple_single_double(&archive)?,
3149            )?;
3150        }
3151        let mut args = default_test_args(
3152            vec![source.join(""), destination.clone()],
3153            state.clone(),
3154        );
3155        args.read_apple_single_with_extension = vec![AppleSingleExtension::As];
3156        run_csc(args)?;
3157        let journal_path = find_cscjournal(&state);
3158        let snapshot = crate::journal::read_journal_snapshot(&journal_path)?;
3159        for name in &names {
3160            ensure!(
3161                std::fs::read(destination.join(name))?
3162                    == name.as_encoded_bytes()
3163            );
3164            ensure!(
3165                snapshot.committed_entities.values().any(|entity| entity
3166                    .identity
3167                    .relative_path
3168                    .as_deref()
3169                    == Some(Path::new(name)))
3170            );
3171        }
3172        ensure!(std::fs::read_dir(destination)?.count() == names.len());
3173        Ok(())
3174    }
3175
3176    #[cfg(unix)]
3177    #[crate::ctb_test]
3178    fn test_identical_checksum_does_not_authorize_metadata() {
3179        let temp = tempdir().expect("create tempdir");
3180        let src = temp.path().join("src_skip");
3181        let dest = temp.path().join("dest_skip");
3182        let state = temp.path().join("state_dir");
3183        fs::create_dir_all(&src).expect("create src");
3184        fs::create_dir_all(&dest).expect("create dest");
3185        fs::create_dir_all(&state).expect("create state");
3186
3187        fs::write(src.join("file.txt"), b"Same data").expect("write src");
3188        fs::write(dest.join("file.txt"), b"Same data").expect("write dest");
3189
3190        let args = default_test_args(
3191            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
3192            state,
3193        );
3194
3195        let original_mode = fs::metadata(dest.join("file.txt"))
3196            .unwrap()
3197            .permissions()
3198            .mode();
3199        assert!(run_csc(args).is_err());
3200        assert_eq!(fs::read(dest.join("file.txt")).unwrap(), b"Same data");
3201        assert_eq!(
3202            fs::metadata(dest.join("file.txt"))
3203                .unwrap()
3204                .permissions()
3205                .mode(),
3206            original_mode
3207        );
3208    }
3209
3210    #[crate::ctb_test]
3211    fn test_resume_mode() {
3212        let temp = tempdir().expect("create tempdir");
3213        let src = temp.path().join("src_res");
3214        let dest = temp.path().join("dest_res");
3215        let state = temp.path().join("state_res");
3216        fs::create_dir_all(&src).expect("create src");
3217        fs::create_dir_all(&state).expect("create state");
3218
3219        fs::write(src.join("first.txt"), b"First payload")
3220            .expect("write first");
3221
3222        let args1 = default_test_args(
3223            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
3224            state.clone(),
3225        );
3226
3227        run_csc(args1).expect("run initial csc");
3228
3229        // Locate created journal
3230        let mut journal_file = None;
3231        for entry in fs::read_dir(&state).expect("read state dir") {
3232            let entry = entry.expect("entry");
3233            if entry.path().extension().and_then(|e| e.to_str())
3234                == Some("cscjournal")
3235            {
3236                journal_file = Some(entry.path());
3237                break;
3238            }
3239        }
3240        let journal_path = journal_file.expect("found journal");
3241
3242        // Now resume without specifying source or dest!
3243        let mut resume_args = default_test_args(Vec::new(), state.clone());
3244        resume_args.resume = Some(journal_path);
3245        resume_args.overwrite = true;
3246
3247        let res = run_csc(resume_args).expect("run resume csc");
3248        match res {
3249            ctb_utilities::cli::ToolResult::Immediate { stdout, .. } => {
3250                let out = String::from_utf8_lossy(&stdout);
3251                assert!(
3252                    out.contains("already marked Completed")
3253                        || out.contains("Summary")
3254                );
3255            }
3256            _ => panic!("Expected Immediate ToolResult"),
3257        }
3258    }
3259
3260    #[cfg(unix)]
3261    #[crate::ctb_test]
3262    fn test_xattrs_and_streams_preserved() {
3263        let temp = tempdir().expect("create tempdir");
3264        let src = temp.path().join("src_xattrs");
3265        let dest = temp.path().join("dest_xattrs");
3266        let state = temp.path().join("state_dir");
3267        fs::create_dir_all(&src).expect("create src");
3268        fs::create_dir_all(&state).expect("create state");
3269
3270        let file = src.join("data.bin");
3271        fs::write(&file, b"Main stream payload").expect("write file");
3272
3273        xattr::set(&file, "user.test_attr", b"Value of attr 1")
3274            .expect("set xattr 1");
3275        xattr::set(
3276            &file,
3277            "user.complex_stream",
3278            b"Multi-line\nstream\x00with\x01binary\xFFdata",
3279        )
3280        .expect("set xattr 2");
3281
3282        let args = default_test_args(
3283            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
3284            state,
3285        );
3286
3287        run_csc(args).expect("run csc with xattrs");
3288
3289        let dest_file = dest.join("data.bin");
3290        assert_eq!(
3291            fs::read(&dest_file).expect("read dest"),
3292            b"Main stream payload"
3293        );
3294
3295        let val1 = xattr::get(&dest_file, "user.test_attr")
3296            .expect("get xattr 1")
3297            .expect("attr 1 exists");
3298        assert_eq!(val1, b"Value of attr 1");
3299
3300        let val2 = xattr::get(&dest_file, "user.complex_stream")
3301            .expect("get xattr 2")
3302            .expect("attr 2 exists");
3303        assert_eq!(val2, b"Multi-line\nstream\x00with\x01binary\xFFdata");
3304    }
3305
3306    #[crate::ctb_test]
3307    fn test_resume_repairs_committed_destination_without_nesting() {
3308        let temp = tempdir().unwrap();
3309        let source = temp.path().join("source");
3310        let destination = temp.path().join("destination");
3311        let state = temp.path().join("state");
3312        fs::create_dir(&source).unwrap();
3313        fs::create_dir(&state).unwrap();
3314        fs::write(source.join("data"), b"original").unwrap();
3315        let mut args =
3316            default_test_args(vec![source, destination.clone()], state.clone());
3317        args.no_verify_after = true;
3318        args.verify_after = false;
3319        run_csc(args).unwrap();
3320        fs::write(destination.join("data"), b"damaged!").unwrap();
3321        let journal_path = find_cscjournal(&state);
3322        let mut resume = default_test_args(Vec::new(), state.clone());
3323        resume.resume = Some(journal_path.clone());
3324        assert!(run_csc(resume.clone()).is_err());
3325        assert_eq!(fs::read(destination.join("data")).unwrap(), b"damaged!");
3326        resume.overwrite = true;
3327        run_csc(resume).unwrap();
3328        assert_eq!(fs::read(destination.join("data")).unwrap(), b"original");
3329        assert!(!destination.join("source").exists());
3330        assert!(
3331            crate::journal::read_journal_snapshot(&journal_path)
3332                .unwrap()
3333                .is_completed
3334        );
3335
3336        fs::write(destination.join("data"), b"damaged!").unwrap();
3337        {
3338            use std::io::Write;
3339            let mut journal = fs::OpenOptions::new()
3340                .append(true)
3341                .open(&journal_path)
3342                .unwrap();
3343            journal.write_all(b"damaged tail").unwrap();
3344        }
3345        let malformed_journal = fs::read(&journal_path).unwrap();
3346        let mut resume = default_test_args(Vec::new(), state.clone());
3347        resume.resume = Some(journal_path.clone());
3348        let error = run_csc(resume)
3349            .err()
3350            .expect("Malformed records must not authorize destructive resume");
3351        assert!(format!("{error:#}").contains("Unsupported journal record"));
3352        assert_eq!(fs::read(destination.join("data")).unwrap(), b"damaged!");
3353        assert_eq!(fs::read(&journal_path).unwrap(), malformed_journal);
3354        assert!(!destination.join("source").exists());
3355    }
3356
3357    #[cfg(unix)]
3358    #[crate::ctb_test]
3359    fn test_unusual_filenames_and_stream_names() {
3360        use std::os::unix::ffi::OsStrExt;
3361
3362        let temp = tempdir().expect("create tempdir");
3363        let src = temp.path().join("src_unusual");
3364        let dest = temp.path().join("dest_unusual");
3365        let state = temp.path().join("state_dir");
3366        fs::create_dir_all(&src).expect("create src");
3367        fs::create_dir_all(&state).expect("create state");
3368
3369        // 1. Filename with newlines
3370        let nl_file = src.join("file\nwith\nnewlines.txt");
3371        fs::write(&nl_file, b"Newlines in filename content")
3372            .expect("write nl_file");
3373
3374        // 2. Filename with unusual punctuation and spaces
3375        let punc_file = src.join("special !@#$%^&*()_+-=[]{}|;',.<>?~.txt");
3376        fs::write(&punc_file, b"Punctuation content").expect("write punc_file");
3377
3378        // 3. Misencoded non-UTF-8 raw byte filename
3379        let misencoded_name =
3380            std::ffi::OsStr::from_bytes(b"misencoded_\xFF\xFE_\x80_junk.dat");
3381        let mis_file = src.join(misencoded_name);
3382        fs::write(&mis_file, b"Misencoded filename payload")
3383            .expect("write mis_file");
3384
3385        // 4. Stream name with binary junk
3386        let misencoded_stream =
3387            std::ffi::OsStr::from_bytes(b"user.stream_\xFF\xFE_\x80_junk");
3388        xattr::set(&mis_file, misencoded_stream, b"Stream with binary name")
3389            .expect("set binary stream");
3390
3391        let args = default_test_args(
3392            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
3393            state,
3394        );
3395
3396        run_csc(args).expect("run csc with unusual names");
3397
3398        assert_eq!(
3399            fs::read(dest.join("file\nwith\nnewlines.txt")).expect("read nl"),
3400            b"Newlines in filename content"
3401        );
3402        assert_eq!(
3403            fs::read(dest.join("special !@#$%^&*()_+-=[]{}|;',.<>?~.txt"))
3404                .expect("read punc"),
3405            b"Punctuation content"
3406        );
3407
3408        let dest_mis = dest.join(misencoded_name);
3409        assert_eq!(
3410            fs::read(&dest_mis).expect("read mis"),
3411            b"Misencoded filename payload"
3412        );
3413
3414        let stream_val = xattr::get(&dest_mis, misencoded_stream)
3415            .expect("get binary stream")
3416            .expect("stream exists");
3417        assert_eq!(stream_val, b"Stream with binary name");
3418    }
3419
3420    #[crate::ctb_test]
3421    fn test_long_path_names_and_deep_nesting() {
3422        let temp = tempdir().expect("create tempdir");
3423        let src = temp.path().join("src_long");
3424        let dest = temp.path().join("dest_long");
3425        let state = temp.path().join("state_dir");
3426        fs::create_dir_all(&state).expect("create state");
3427
3428        // Long filename of 240 bytes (close to NAME_MAX = 255)
3429        let long_filename = "a".repeat(240);
3430        let long_file = src.join(&long_filename);
3431        fs::create_dir_all(&src).expect("create src");
3432        fs::write(&long_file, b"Payload in file with 240-byte name")
3433            .expect("write long file");
3434
3435        // Deep directory nesting (15 levels deep)
3436        let mut deep_dir = src.clone();
3437        for i in 0..15 {
3438            deep_dir = deep_dir.join(format!("level_{i}"));
3439        }
3440        fs::create_dir_all(&deep_dir).expect("create deep dir");
3441        let nested_file = deep_dir.join("deep_nested.txt");
3442        fs::write(&nested_file, b"Nested file content")
3443            .expect("write nested file");
3444
3445        let args = default_test_args(
3446            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
3447            state,
3448        );
3449
3450        run_csc(args).expect("run csc with long paths");
3451
3452        assert_eq!(
3453            fs::read(dest.join(&long_filename)).expect("read long file"),
3454            b"Payload in file with 240-byte name"
3455        );
3456
3457        let mut dest_deep = dest.clone();
3458        for i in 0..15 {
3459            dest_deep = dest_deep.join(format!("level_{i}"));
3460        }
3461        assert_eq!(
3462            fs::read(dest_deep.join("deep_nested.txt"))
3463                .expect("read nested file"),
3464            b"Nested file content"
3465        );
3466    }
3467
3468    #[cfg(unix)]
3469    #[crate::ctb_test]
3470    fn test_sparse_file_preservation() {
3471        use ctb_io::file::{Extent as FileExtent, get_file_extents};
3472        use std::io::Seek;
3473        use std::io::SeekFrom;
3474        use std::io::Write;
3475
3476        let temp = tempdir().expect("create tempdir");
3477        let src = temp.path().join("src_sparse");
3478        let dest = temp.path().join("dest_sparse");
3479        let state = temp.path().join("state_dir");
3480        fs::create_dir_all(&src).expect("create src");
3481        fs::create_dir_all(&state).expect("create state");
3482
3483        let sparse_src = src.join("sparse.img");
3484        let mut f = fs::File::create(&sparse_src).expect("create sparse file");
3485        // Write header
3486        f.write_all(b"HeaderData").expect("write header");
3487        // Seek forward 10MB
3488        f.seek(SeekFrom::Start(10 * 1024 * 1024))
3489            .expect("seek 10MB");
3490        // Write tail
3491        f.write_all(b"TailData").expect("write tail");
3492        f.sync_data().expect("sync sparse src");
3493        drop(f);
3494
3495        let src_meta = fs::metadata(&sparse_src).expect("src meta");
3496        let expected_len = src_meta.len();
3497
3498        let args = default_test_args(
3499            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
3500            state,
3501        );
3502
3503        run_csc(args).expect("run csc with sparse file");
3504
3505        let dest_sparse = dest.join("sparse.img");
3506        let dest_meta = fs::metadata(&dest_sparse).expect("dest meta");
3507        assert_eq!(dest_meta.len(), expected_len);
3508
3509        // Verify extents on dest contain a hole
3510        let dest_file = fs::File::open(&dest_sparse).expect("open dest sparse");
3511        let extents =
3512            get_file_extents(&dest_file, expected_len).expect("get extents");
3513        let has_hole =
3514            extents.iter().any(|e| matches!(e, FileExtent::Hole { .. }));
3515        assert!(
3516            has_hole,
3517            "Expected destination file to preserve sparse hole"
3518        );
3519
3520        // Verify content integrity
3521        let mut dest_f = dest_file;
3522        let mut header = [0_u8; 10];
3523        dest_f.seek(SeekFrom::Start(0)).expect("seek to 0");
3524        std::io::Read::read_exact(&mut dest_f, &mut header)
3525            .expect("read header");
3526        assert_eq!(&header, b"HeaderData");
3527
3528        dest_f
3529            .seek(SeekFrom::Start(10 * 1024 * 1024))
3530            .expect("seek to tail");
3531        let mut tail = [0_u8; 8];
3532        std::io::Read::read_exact(&mut dest_f, &mut tail).expect("read tail");
3533        assert_eq!(&tail, b"TailData");
3534    }
3535
3536    #[cfg(unix)]
3537    #[crate::ctb_test]
3538    fn test_timestamps_and_metadata_preserved() {
3539        use filetime::{FileTime, set_file_times};
3540        use std::os::unix::fs::PermissionsExt;
3541
3542        let temp = tempdir().expect("create tempdir");
3543        let src = temp.path().join("src_meta");
3544        let dest = temp.path().join("dest_meta");
3545        let state = temp.path().join("state_dir");
3546        fs::create_dir_all(&src).expect("create src");
3547        fs::create_dir_all(&state).expect("create state");
3548
3549        let file = src.join("custom_meta.txt");
3550        fs::write(&file, b"Testing metadata and timestamps")
3551            .expect("write file");
3552
3553        // Set permissions 0o640 (rw-r-----)
3554        fs::set_permissions(&file, fs::Permissions::from_mode(0o640))
3555            .expect("set permissions");
3556
3557        // Set directory permissions 0o750 (rwxr-x---)
3558        fs::set_permissions(&src, fs::Permissions::from_mode(0o750))
3559            .expect("set dir perms");
3560
3561        // Set specific mtime timestamp
3562        let custom_time = FileTime::from_unix_time(1_400_000_000, 500_000_000);
3563        set_file_times(&file, custom_time, custom_time)
3564            .expect("set file times");
3565
3566        let args = default_test_args(
3567            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
3568            state,
3569        );
3570
3571        run_csc(args).expect("run csc");
3572
3573        let dest_file = dest.join("custom_meta.txt");
3574        let dm = fs::metadata(&dest_file).expect("dest meta");
3575        assert_eq!(dm.permissions().mode() & 0o777, 0o640);
3576        assert_eq!(dm.mtime(), 1_400_000_000);
3577
3578        let d_dir = fs::metadata(&dest).expect("dest dir meta");
3579        assert_eq!(d_dir.permissions().mode() & 0o777, 0o750);
3580    }
3581
3582    #[cfg(unix)]
3583    #[crate::ctb_test]
3584    fn test_fifo_special_file_preserved() {
3585        use nix::sys::stat::Mode;
3586        use nix::unistd::mkfifo;
3587        use std::os::unix::fs::FileTypeExt;
3588
3589        let temp = tempdir().expect("create tempdir");
3590        let src = temp.path().join("src_fifo");
3591        let dest = temp.path().join("dest_fifo");
3592        let state = temp.path().join("state_dir");
3593        fs::create_dir_all(&src).expect("create src");
3594        fs::create_dir_all(&state).expect("create state");
3595
3596        let fifo_path = src.join("test.fifo");
3597        mkfifo(&fifo_path, Mode::from_bits_truncate(0o660)).expect("mkfifo");
3598
3599        let args = default_test_args(
3600            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
3601            state.clone(),
3602        );
3603
3604        let res = run_csc(args).expect("run csc with fifo default skip");
3605        if let ToolResult::Immediate { stdout, .. } = res {
3606            let out_str = String::from_utf8_lossy(&stdout);
3607            assert!(out_str.contains("Special files skipped:    1"));
3608        }
3609        let dest_fifo = dest.join("test.fifo");
3610        assert!(!dest_fifo.exists(), "Default should skip FIFO");
3611        let skip_journal = crate::journal::find_cscjournal(&state);
3612        let skip_snap = crate::journal::read_journal_snapshot(&skip_journal)
3613            .expect("read skip journal");
3614        assert!(
3615            !skip_snap.is_committed(b"test.fifo"),
3616            "Skipped FIFO must not be falsely committed to the state journal"
3617        );
3618
3619        // Direct single-file FIFO copy without explicit policy must fail without draining/corrupting source FIFO
3620        let direct_state = temp.path().join("state_direct");
3621        fs::create_dir_all(&direct_state).expect("create direct state");
3622        let direct_args = default_test_args(
3623            vec![fifo_path.clone(), temp.path().join("direct_out.fifo")],
3624            direct_state,
3625        );
3626        assert!(
3627            run_csc(direct_args).is_err(),
3628            "Direct FIFO copy without explicit special-file policy must fail"
3629        );
3630
3631        // Now test with copy_specials_as_specials = true while bytes are queued in the source FIFO
3632        let fifo_rw = fs::OpenOptions::new()
3633            .read(true)
3634            .write(true)
3635            .open(&fifo_path)
3636            .expect("open fifo rw");
3637        {
3638            use std::io::Write;
3639            (&fifo_rw)
3640                .write_all(b"preserved queued fifo bytes")
3641                .expect("queue bytes in source fifo");
3642        }
3643        let dest_copy = temp.path().join("dest_fifo_copy");
3644        let state_copy = temp.path().join("state_dir_copy");
3645        fs::create_dir_all(&state_copy).expect("create state copy");
3646        let mut args_copy = default_test_args(
3647            vec![
3648                PathBuf::from(format!("{}/", src.display())),
3649                dest_copy.clone(),
3650            ],
3651            state_copy,
3652        );
3653        args_copy.copy_specials_as_specials = true;
3654        args_copy.best_effort_metadata = true;
3655        run_csc(args_copy).expect("run csc with copy_specials_as_specials");
3656
3657        let dest_fifo_node = dest_copy.join("test.fifo");
3658        let meta =
3659            fs::symlink_metadata(&dest_fifo_node).expect("fifo metadata");
3660        assert!(
3661            meta.file_type().is_fifo(),
3662            "Expected created node to be a FIFO"
3663        );
3664
3665        // Verify the queued bytes in the source FIFO were not drained or corrupted
3666        let mut buf = [0_u8; 27];
3667        {
3668            use std::io::Read;
3669            (&fifo_rw)
3670                .read_exact(&mut buf)
3671                .expect("read queued bytes from source fifo");
3672        }
3673        assert_eq!(&buf, b"preserved queued fifo bytes");
3674
3675        // Unsupported special file (Unix domain socket) under --copy-specials-as-specials must fail cleanly
3676        let sock_path = src.join("unsupported.sock");
3677        let _listener = std::os::unix::net::UnixListener::bind(&sock_path)
3678            .expect("bind unix socket");
3679        let dest_sock = temp.path().join("dest_sock_copy");
3680        let state_sock = temp.path().join("state_sock_copy");
3681        fs::create_dir_all(&state_sock).expect("create state sock");
3682        let mut args_sock = default_test_args(
3683            vec![PathBuf::from(format!("{}/", src.display())), dest_sock],
3684            state_sock,
3685        );
3686        args_sock.copy_specials_as_specials = true;
3687        args_sock.best_effort_metadata = true;
3688        let sock_err = run_csc(args_sock).err().expect(
3689            "Unsupported socket must fail under --copy-specials-as-specials",
3690        );
3691        assert!(
3692            format!("{sock_err:#}").contains("Unsupported special file"),
3693            "Unexpected error: {sock_err:#}"
3694        );
3695        assert!(
3696            fs::symlink_metadata(&sock_path)
3697                .unwrap()
3698                .file_type()
3699                .is_socket()
3700        );
3701    }
3702
3703    #[cfg(unix)]
3704    #[crate::ctb_test]
3705    fn test_fifo_copied_as_regular_file() {
3706        use nix::sys::stat::Mode;
3707        use nix::unistd::mkfifo;
3708
3709        let temp = tempdir().expect("create tempdir");
3710        let src = temp.path().join("src_fifo_reg");
3711        let dest = temp.path().join("dest_fifo_reg");
3712        let state = temp.path().join("state_dir");
3713        fs::create_dir_all(&src).expect("create src");
3714        fs::create_dir_all(&state).expect("create state");
3715
3716        let fifo_path = src.join("test.fifo");
3717        mkfifo(&fifo_path, Mode::from_bits_truncate(0o660)).expect("mkfifo");
3718
3719        let writer_path = fifo_path.clone();
3720        let writer_handle = std::thread::spawn(move || {
3721            use std::io::Write;
3722            let mut file = fs::OpenOptions::new()
3723                .write(true)
3724                .open(&writer_path)
3725                .expect("open fifo for write");
3726            file.write_all(b"Payload from named pipe")
3727                .expect("write to fifo");
3728        });
3729
3730        let mut args = default_test_args(
3731            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
3732            state,
3733        );
3734        args.copy_fifos_as_regular_files = true;
3735
3736        let res =
3737            run_csc(args).expect("run csc with copy_fifos_as_regular_files");
3738        writer_handle.join().expect("writer thread join");
3739
3740        if let ToolResult::Immediate { stdout, .. } = res {
3741            let out_str = String::from_utf8_lossy(&stdout);
3742            assert!(out_str.contains("Files copied:             1"));
3743            assert!(out_str.contains("Bytes transferred:        23"));
3744        }
3745
3746        let dest_file = dest.join("test.fifo");
3747        let meta =
3748            fs::symlink_metadata(&dest_file).expect("dest file metadata");
3749        assert!(meta.is_file(), "Expected created item to be a regular file");
3750        let contents = fs::read(&dest_file).expect("read dest file");
3751        assert_eq!(contents, b"Payload from named pipe");
3752    }
3753
3754    #[cfg(unix)]
3755    #[crate::ctb_test]
3756    fn test_empty_fifo_copied_as_regular_file() {
3757        use nix::sys::stat::Mode;
3758        use nix::unistd::mkfifo;
3759
3760        let temp = tempdir().expect("create tempdir");
3761        let src = temp.path().join("src_empty_fifo");
3762        let dest = temp.path().join("dest_empty_fifo");
3763        let state = temp.path().join("state_dir");
3764        fs::create_dir_all(&src).expect("create src");
3765        fs::create_dir_all(&state).expect("create state");
3766
3767        let fifo_path = src.join("empty.fifo");
3768        mkfifo(&fifo_path, Mode::from_bits_truncate(0o660)).expect("mkfifo");
3769
3770        let writer_path = fifo_path.clone();
3771        let writer_handle = std::thread::spawn(move || {
3772            let _file = fs::OpenOptions::new()
3773                .write(true)
3774                .open(&writer_path)
3775                .expect("open fifo for write");
3776        });
3777
3778        let mut args = default_test_args(
3779            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
3780            state,
3781        );
3782        args.copy_fifos_as_regular_files = true;
3783
3784        run_csc(args)
3785            .expect("run csc with copy_fifos_as_regular_files for empty fifo");
3786        writer_handle.join().expect("writer thread join");
3787
3788        let dest_file = dest.join("empty.fifo");
3789        let meta =
3790            fs::symlink_metadata(&dest_file).expect("dest file metadata");
3791        assert!(meta.is_file(), "Expected created item to be a regular file");
3792        let contents = fs::read(&dest_file).expect("read dest file");
3793        assert_eq!(contents, b"");
3794    }
3795
3796    #[cfg(unix)]
3797    #[crate::ctb_test]
3798    fn test_symlink_dangling_and_relative_target_preserved() {
3799        let temp = tempdir().expect("create tempdir");
3800        let src = temp.path().join("src_dangling");
3801        let dest = temp.path().join("dest_dangling");
3802        let state = temp.path().join("state_dir");
3803        fs::create_dir_all(&src).expect("create src");
3804        fs::create_dir_all(&state).expect("create state");
3805
3806        let sym = src.join("dangling.sym");
3807        std::os::unix::fs::symlink("../non_existent_folder/absent.txt", &sym)
3808            .expect("create dangling symlink");
3809
3810        let args = default_test_args(
3811            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
3812            state,
3813        );
3814
3815        run_csc(args).expect("run csc");
3816
3817        let dest_sym = dest.join("dangling.sym");
3818        assert!(dest_sym.is_symlink());
3819        let read = fs::read_link(&dest_sym).expect("read dangling symlink");
3820        assert_eq!(read, PathBuf::from("../non_existent_folder/absent.txt"));
3821    }
3822
3823    #[crate::ctb_test]
3824    fn test_hardlinks_preserved_across_resume() {
3825        let temp = tempdir().expect("create tempdir");
3826        let src = temp.path().join("src_hl_res");
3827        let dest = temp.path().join("dest_hl_res");
3828        let state = temp.path().join("state_hl_res");
3829        fs::create_dir_all(&src).expect("create src");
3830        fs::create_dir_all(&state).expect("create state");
3831
3832        let f1 = src.join("orig.txt");
3833        fs::write(&f1, b"Shared payload across resumed hardlinks")
3834            .expect("write orig");
3835        let anchor = temp.path().join("anchor.tmp");
3836        fs::hard_link(&f1, &anchor).expect("create anchor link");
3837
3838        let args1 = default_test_args(
3839            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
3840            state.clone(),
3841        );
3842        run_csc(args1).expect("initial run");
3843
3844        let journal_path = find_cscjournal(&state);
3845
3846        // Simulate an interrupted run by stripping the 1-byte TAG_JOB_COMPLETED marker
3847        let f = fs::OpenOptions::new()
3848            .write(true)
3849            .open(&journal_path)
3850            .expect("open journal");
3851        let len = f.metadata().expect("meta").len();
3852        f.set_len(len.saturating_sub(1))
3853            .expect("truncate completion tag");
3854        drop(f);
3855        let desc_path = journal_path.with_extension("cscdesc");
3856        let _ = fs::remove_file(&desc_path);
3857
3858        let f2 = src.join("link.txt");
3859        fs::hard_link(&f1, &f2).expect("create link");
3860        let _ = fs::remove_file(&anchor);
3861
3862        let mut resume_args = default_test_args(
3863            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
3864            state,
3865        );
3866        resume_args.resume = Some(journal_path);
3867        resume_args.overwrite = true;
3868        run_csc(resume_args).expect("resume run");
3869
3870        let dest_f1 = dest.join("orig.txt");
3871        let dest_f2 = dest.join("link.txt");
3872
3873        let m1 = fs::metadata(&dest_f1).expect("meta1");
3874        let m2 = fs::metadata(&dest_f2).expect("meta2");
3875
3876        #[cfg(unix)]
3877        {
3878            assert_eq!(m1.ino(), m2.ino(), "Inodes must match across resume");
3879            assert_eq!(m1.nlink(), 2, "Link count must be 2");
3880        }
3881        #[cfg(windows)]
3882        {
3883            let id1 = ctb_io::file::identity::query_file_identity(&dest_f1)
3884                .expect("id1");
3885            let id2 = ctb_io::file::identity::query_file_identity(&dest_f2)
3886                .expect("id2");
3887            assert_eq!(id1, id2, "File identities must match across resume");
3888        }
3889    }
3890
3891    #[crate::ctb_test]
3892    fn test_best_effort_metadata_timestamp_tolerance() {
3893        use filetime::{FileTime, set_file_times};
3894
3895        let temp = tempdir().expect("create tempdir");
3896        let src = temp.path().join("src_be");
3897        let dest = temp.path().join("dest_be");
3898        let state = temp.path().join("state_be");
3899        fs::create_dir_all(&src).expect("create src");
3900        fs::create_dir_all(&state).expect("create state");
3901
3902        let file = src.join("file.txt");
3903        fs::write(&file, b"Timestamp drift test").expect("write file");
3904
3905        let args = default_test_args(
3906            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
3907            state.clone(),
3908        );
3909        run_csc(args).expect("run csc");
3910
3911        let journal_path = find_cscjournal(&state);
3912
3913        let dest_file = dest.join("file.txt");
3914        let dest_meta = fs::metadata(&dest_file).expect("dest meta");
3915        let atime = FileTime::from_last_access_time(&dest_meta);
3916        let mtime = FileTime::from_last_modification_time(&dest_meta);
3917        set_file_times(
3918            &dest_file,
3919            atime,
3920            FileTime::from_unix_time(
3921                mtime.unix_seconds().saturating_add(1),
3922                mtime.nanoseconds(),
3923            ),
3924        )
3925        .expect("set drifted mtime");
3926
3927        let mut strict_vargs =
3928            default_verify_args(journal_path.clone(), Some(dest.clone()));
3929        strict_vargs.best_effort = false;
3930        let res_strict = run_csc_verify(&strict_vargs).expect("verify strict");
3931        if let ToolResult::Immediate { stdout, .. } = res_strict {
3932            let out = String::from_utf8_lossy(&stdout);
3933            assert!(
3934                out.contains("discrepancies detected")
3935                    || out.contains("mismatch"),
3936                "Strict mode must report timestamp mismatch: {out}"
3937            );
3938        }
3939
3940        let mut be_vargs = default_verify_args(journal_path, Some(dest));
3941        be_vargs.best_effort = true;
3942        let res_be = run_csc_verify(&be_vargs).expect("verify best_effort");
3943        if let ToolResult::Immediate { stdout, .. } = res_be {
3944            let out = String::from_utf8_lossy(&stdout);
3945            assert!(
3946                out.contains("OK") || out.contains("0 discrepancies"),
3947                "Best effort mode must tolerate 1s timestamp difference: {out}"
3948            );
3949        }
3950    }
3951
3952    #[cfg(unix)]
3953    #[crate::ctb_test]
3954    fn test_csc_identical_file_metadata_requires_overwrite() {
3955        let temp = tempdir().expect("create tempdir");
3956        let src = temp.path().join("src_skip");
3957        let dest = temp.path().join("dest_skip");
3958        let state1 = temp.path().join("state_dir1");
3959        let state2 = temp.path().join("state_dir2");
3960        fs::create_dir_all(&src).expect("create src");
3961        fs::create_dir_all(&state1).expect("create state1");
3962        fs::create_dir_all(&state2).expect("create state2");
3963
3964        let file_path = src.join("doc.txt");
3965        let payload = b"Lossless smart skipping integration test payload";
3966        fs::write(&file_path, payload).expect("write initial file");
3967        fs::set_permissions(&file_path, fs::Permissions::from_mode(0o600))
3968            .expect("chmod initial");
3969
3970        // First copy: fresh write of 1 file
3971        let args1 = default_test_args(
3972            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
3973            state1,
3974        );
3975        let res1 = run_csc(args1).expect("first copy");
3976        match res1 {
3977            ToolResult::Immediate {
3978                stdout, exit_code, ..
3979            } => {
3980                assert_eq!(exit_code, 0);
3981                let out = String::from_utf8_lossy(&stdout);
3982                assert!(out.contains("Files copied:             1"));
3983            }
3984            _ => panic!("Expected Immediate ToolResult"),
3985        }
3986
3987        let dest_file = dest.join("doc.txt");
3988        assert_eq!(fs::read(&dest_file).expect("read dest"), payload);
3989        let meta1 = fs::metadata(&dest_file).expect("dest meta");
3990        assert_eq!(meta1.permissions().mode() & 0o7777, 0o600);
3991
3992        // Update metadata on source file (change mode to 0o644)
3993        fs::set_permissions(&file_path, fs::Permissions::from_mode(0o644))
3994            .expect("chmod updated");
3995
3996        // Second copy must explicitly authorize restoring metadata on existing entries.
3997        let mut args2 = default_test_args(
3998            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
3999            state2,
4000        );
4001        assert!(run_csc(args2.clone()).is_err());
4002        assert_eq!(
4003            fs::metadata(&dest_file).unwrap().permissions().mode() & 0o7777,
4004            0o600
4005        );
4006        assert_eq!(fs::read(&dest_file).unwrap(), payload);
4007        args2.overwrite = true;
4008        let res2 = run_csc(args2).expect("second copy with explicit overwrite");
4009        match res2 {
4010            ToolResult::Immediate {
4011                stdout, exit_code, ..
4012            } => {
4013                assert_eq!(exit_code, 0);
4014                let out = String::from_utf8_lossy(&stdout);
4015                assert!(out.contains("Files copied:             1"));
4016                assert!(out.contains("Files verified:           1"));
4017            }
4018            _ => panic!("Expected Immediate ToolResult"),
4019        }
4020
4021        // Verify that explicitly authorized replacement restores metadata to 0o644.
4022        let meta2 = fs::metadata(&dest_file).expect("dest meta after update");
4023        assert_eq!(meta2.permissions().mode() & 0o7777, 0o644);
4024        assert_eq!(
4025            fs::read(&dest_file).expect("read dest after update"),
4026            payload
4027        );
4028    }
4029
4030    #[crate::ctb_test]
4031    fn test_csc_overwrite_rewrites_identical_file() {
4032        let temp = tempdir().expect("create tempdir");
4033        let src = temp.path().join("src_always");
4034        let dest = temp.path().join("dest_always");
4035        let state1 = temp.path().join("state_dir1");
4036        let state2 = temp.path().join("state_dir2");
4037        fs::create_dir_all(&src).expect("create src");
4038        fs::create_dir_all(&state1).expect("create state1");
4039        fs::create_dir_all(&state2).expect("create state2");
4040
4041        let file_path = src.join("data.bin");
4042        let payload = b"Always overwrite payload verification";
4043        fs::write(&file_path, payload).expect("write data");
4044
4045        // First copy
4046        let args1 = default_test_args(
4047            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
4048            state1,
4049        );
4050        run_csc(args1).expect("first copy");
4051
4052        // Second copy with overwrite = true
4053        let mut args2 = default_test_args(
4054            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
4055            state2,
4056        );
4057        args2.overwrite = true;
4058
4059        let res2 = run_csc(args2).expect("always overwrite copy");
4060        match res2 {
4061            ToolResult::Immediate {
4062                stdout, exit_code, ..
4063            } => {
4064                assert_eq!(exit_code, 0);
4065                let out = String::from_utf8_lossy(&stdout);
4066                assert!(out.contains("Files copied:             1"));
4067                let payload_len = payload.len();
4068                assert!(out.contains(&format!(
4069                    "Bytes transferred:        {payload_len}"
4070                )));
4071            }
4072            _ => panic!("Expected Immediate ToolResult"),
4073        }
4074    }
4075
4076    #[crate::ctb_test]
4077    #[cfg(unix)]
4078    fn test_csc_file_overwrite_preserves_unrelated_hardlink() -> Result<()> {
4079        let temporary = tempdir()?;
4080        let source = temporary.path().join("source");
4081        let destination = temporary.path().join("destination");
4082        let alias = temporary.path().join("alias");
4083        let state = temporary.path().join("state");
4084        fs::create_dir(&state)?;
4085        fs::write(&source, b"new payload")?;
4086        fs::write(&destination, b"original payload")?;
4087        fs::set_permissions(&source, fs::Permissions::from_mode(0o644))?;
4088        fs::set_permissions(&destination, fs::Permissions::from_mode(0o600))?;
4089        fs::hard_link(&destination, &alias)?;
4090        let mut args =
4091            default_test_args(vec![source, destination.clone()], state);
4092        assert!(run_csc(args.clone()).is_err());
4093        assert_eq!(fs::read(&destination)?, b"original payload");
4094        assert_eq!(
4095            fs::metadata(&destination)?.permissions().mode() & 0o777,
4096            0o600
4097        );
4098        args.overwrite = true;
4099        run_csc(args)?;
4100        assert_eq!(fs::read(destination)?, b"new payload");
4101        assert_eq!(fs::read(&alias)?, b"original payload");
4102        assert_eq!(fs::metadata(alias)?.permissions().mode() & 0o777, 0o600);
4103        Ok(())
4104    }
4105
4106    #[crate::ctb_test]
4107    fn test_unknown_filesystem_error_and_allow_flags() {
4108        use ctb_io::file::{
4109            FilesystemInfo, clear_filesystem_cache, extract_device_id,
4110            set_cached_filesystem_info,
4111        };
4112
4113        let _fs_lock = ctb_io::file::FS_CACHE_TEST_MUTEX.lock().unwrap();
4114        let temp = tempdir().expect("create tempdir");
4115        let src = temp.path().join("src");
4116        let dest = temp.path().join("dest");
4117        let state = temp.path().join("state");
4118        fs::create_dir_all(&src).expect("create src");
4119        fs::create_dir_all(&state).expect("create state");
4120        fs::write(src.join("file.txt"), b"data").expect("write file");
4121
4122        let meta = fs::metadata(&src).expect("read src metadata");
4123        let dev_id = ctb_io::file::extract_device_id_for_path(&src, &meta)
4124            .expect("Filesystem identity is required to exercise unknown-filesystem policy");
4125
4126        // Simulate unknown filesystem
4127        set_cached_filesystem_info(
4128            dev_id,
4129            FilesystemInfo {
4130                fs_type: "unknown".to_string(),
4131                resolution_nsec: 1,
4132            },
4133        );
4134
4135        // 1. Without best-effort-metadata and without allow-unknown-fs -> should error
4136        let mut args =
4137            default_test_args(vec![src.clone(), dest.clone()], state.clone());
4138        args.best_effort_metadata = false;
4139        args.allow_unknown_fs = false;
4140        match crate::cli::run_csc(args) {
4141            Err(err) => {
4142                assert!(
4143                    err.to_string().contains("Cannot detect filesystem type")
4144                );
4145            }
4146            Ok(_) => panic!("Expected error when filesystem is unknown"),
4147        }
4148
4149        // 2. With allow-unknown-fs -> should succeed
4150        let dest2 = temp.path().join("dest2");
4151        let state2 = temp.path().join("state2");
4152        fs::create_dir_all(&state2).expect("create state2");
4153        let mut args2 = default_test_args(vec![src.clone(), dest2], state2);
4154        args2.best_effort_metadata = false;
4155        args2.allow_unknown_fs = true;
4156        match crate::cli::run_csc(args2) {
4157            Ok(_) => {}
4158            Err(e) => panic!("run_csc failed with allow_unknown_fs: {e:?}"),
4159        }
4160
4161        // 3. With best-effort-metadata -> should succeed
4162        let dest3 = temp.path().join("dest3");
4163        let state3 = temp.path().join("state3");
4164        fs::create_dir_all(&state3).expect("create state3");
4165        let mut args3 = default_test_args(vec![src.clone(), dest3], state3);
4166        args3.best_effort_metadata = true;
4167        args3.allow_unknown_fs = false;
4168        match crate::cli::run_csc(args3) {
4169            Ok(_) => {}
4170            Err(e) => panic!("run_csc failed with best_effort_metadata: {e:?}"),
4171        }
4172
4173        // Clean up cache
4174        clear_filesystem_cache();
4175    }
4176
4177    #[cfg(target_os = "linux")]
4178    #[crate::ctb_test]
4179    fn test_csc_noatime_recorded_and_verified() {
4180        let temp = tempdir().expect("tempdir");
4181        let src = temp.path().join("src");
4182        let dest = temp.path().join("dest");
4183        let state = temp.path().join("state");
4184        fs::create_dir_all(&src).expect("create src");
4185        fs::create_dir_all(&dest).expect("create dest");
4186        fs::create_dir_all(&state).expect("create state");
4187
4188        let f = src.join("test_file.txt");
4189        fs::write(&f, b"hello noatime test").expect("write file");
4190
4191        let mut args = default_test_args(
4192            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
4193            state.clone(),
4194        );
4195        args.verify_after = true;
4196        args.overwrite = true;
4197        run_csc(args).expect("run csc");
4198
4199        let journal_path = find_cscjournal(&state);
4200        let desc_path = journal_path.with_extension("cscdesc");
4201        assert!(desc_path.exists(), ".cscdesc must exist");
4202        let desc_content = fs::read_to_string(&desc_path).expect("read desc");
4203        assert!(
4204            desc_content.contains("NoatimeUsed: true"),
4205            "Descriptor should record NoatimeUsed: true when file owner copies file"
4206        );
4207    }
4208
4209    #[crate::ctb_test]
4210    fn test_csc_copy_apple_double_alongside_roundtrip() {
4211        let temp = tempdir().expect("tempdir");
4212        let src = temp.path().join("src");
4213        let dest = temp.path().join("dest");
4214        let state = temp.path().join("state");
4215        fs::create_dir_all(&src).unwrap();
4216        fs::create_dir_all(&state).unwrap();
4217        fs::write(src.join("hello.txt"), b"Hello Payload").unwrap();
4218
4219        let archive = ctb_io::file::AppleArchive {
4220            format: ctb_io::file::AppleFormat::AppleDouble,
4221            version: ctb_io::file::VERSION_2_0_BE,
4222            real_name: Some("hello.txt".to_string()),
4223            comment: Some("Test Comment".to_string()),
4224            timestamps: None,
4225            backup_timestamp_sec: None,
4226            finder_info: Some(ctb_io::file::FinderInfo {
4227                file_type: "TEXT".to_string(),
4228                file_creator: "ttxt".to_string(),
4229                label: ctb_io::file::FinderLabel::from_index(0),
4230                flags: ctb_io::file::FinderFlags::default(),
4231                location: (0, 0),
4232                folder_id: 0,
4233                extended: None,
4234                window_bounds: None,
4235            }),
4236            extended_attributes: Vec::new(),
4237            data_fork: None,
4238            resource_fork: Some(b"Resource Fork Bytes".to_vec()),
4239            data_fork_size: None,
4240            resource_fork_size: Some(19),
4241            unrecognized_entries: Vec::new(),
4242            entries: Vec::new(),
4243        };
4244        let companion_bytes =
4245            ctb_io::file::write_apple_single_double(&archive).unwrap();
4246        fs::write(src.join("._hello.txt"), companion_bytes).unwrap();
4247
4248        let mut args = default_test_args(
4249            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
4250            state,
4251        );
4252        args.read_apple_double_alongside = true;
4253        args.force_write_apple_double = Some(AppleDoubleStyle::Alongside);
4254
4255        let res = run_csc(args).expect("run csc");
4256        match res {
4257            ctb_utilities::cli::ToolResult::Immediate { exit_code, .. } => {
4258                assert_eq!(exit_code, 0);
4259            }
4260            _ => panic!("Expected immediate result"),
4261        }
4262
4263        assert_eq!(fs::read(dest.join("hello.txt")).unwrap(), b"Hello Payload");
4264        assert!(
4265            dest.join("._hello.txt").exists(),
4266            "Companion ._hello.txt must exist on dest"
4267        );
4268
4269        // Inspect entity with apple read options enabled
4270        let opts = ctb_io::file::AppleReadOptions {
4271            read_apple_double_alongside: true,
4272            ..ctb_io::file::AppleReadOptions::default()
4273        };
4274        let entity =
4275            ctb_io::file::FileEntity::from_filesystem_with_apple_options(
4276                &dest.join("hello.txt"),
4277                Some(&dest),
4278                &opts,
4279            )
4280            .unwrap();
4281
4282        let rsrc_stream = entity
4283            .streams
4284            .iter()
4285            .find(|s| s.kind == ctb_io::file::StreamKind::MacOsResourceFork);
4286        assert!(rsrc_stream.is_some(), "Resource fork must be preserved");
4287        assert_eq!(
4288            rsrc_stream.unwrap().data.as_deref(),
4289            Some(&b"Resource Fork Bytes"[..])
4290        );
4291        assert_eq!(
4292            entity
4293                .metadata
4294                .apple
4295                .as_ref()
4296                .and_then(|a| a.finder_info.as_ref())
4297                .map(|f| f.file_type.as_str()),
4298            Some("TEXT")
4299        );
4300    }
4301
4302    #[crate::ctb_test]
4303    fn test_csc_copy_apple_double_zip_roundtrip() {
4304        let temp = tempdir().expect("tempdir");
4305        let src = temp.path().join("src");
4306        let dest = temp.path().join("dest");
4307        let state = temp.path().join("state");
4308        fs::create_dir_all(&src).unwrap();
4309        fs::create_dir_all(&state).unwrap();
4310        fs::write(src.join("zipdoc.txt"), b"Zip Payload").unwrap();
4311
4312        let archive = ctb_io::file::AppleArchive {
4313            format: ctb_io::file::AppleFormat::AppleDouble,
4314            version: ctb_io::file::VERSION_2_0_BE,
4315            real_name: Some("zipdoc.txt".to_string()),
4316            comment: None,
4317            timestamps: None,
4318            backup_timestamp_sec: None,
4319            finder_info: Some(ctb_io::file::FinderInfo {
4320                file_type: "DOCU".to_string(),
4321                file_creator: "docu".to_string(),
4322                label: ctb_io::file::FinderLabel::from_index(0),
4323                flags: ctb_io::file::FinderFlags::default(),
4324                location: (0, 0),
4325                folder_id: 0,
4326                extended: None,
4327                window_bounds: None,
4328            }),
4329            extended_attributes: Vec::new(),
4330            data_fork: None,
4331            resource_fork: Some(b"Zip Resource Fork".to_vec()),
4332            data_fork_size: None,
4333            resource_fork_size: Some(17),
4334            unrecognized_entries: Vec::new(),
4335            entries: Vec::new(),
4336        };
4337        let companion_bytes =
4338            ctb_io::file::write_apple_single_double(&archive).unwrap();
4339        fs::write(src.join("._zipdoc.txt"), companion_bytes).unwrap();
4340
4341        let mut args = default_test_args(
4342            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
4343            state,
4344        );
4345        args.read_apple_double_alongside = true;
4346        args.force_write_apple_double = Some(AppleDoubleStyle::Zip);
4347
4348        let res = run_csc(args).expect("run csc");
4349        match res {
4350            ctb_utilities::cli::ToolResult::Immediate { exit_code, .. } => {
4351                assert_eq!(exit_code, 0);
4352            }
4353            _ => panic!("Expected immediate result"),
4354        }
4355
4356        assert_eq!(fs::read(dest.join("zipdoc.txt")).unwrap(), b"Zip Payload");
4357        let macosx_companion = dest.join("__MACOSX").join("._zipdoc.txt");
4358        assert!(
4359            macosx_companion.exists(),
4360            "__MACOSX/._zipdoc.txt must exist on dest"
4361        );
4362
4363        let opts = ctb_io::file::AppleReadOptions {
4364            read_apple_double_zip: true,
4365            ..ctb_io::file::AppleReadOptions::default()
4366        };
4367        let entity =
4368            ctb_io::file::FileEntity::from_filesystem_with_apple_options(
4369                &dest.join("zipdoc.txt"),
4370                Some(&dest),
4371                &opts,
4372            )
4373            .unwrap();
4374
4375        let rsrc_stream = entity
4376            .streams
4377            .iter()
4378            .find(|s| s.kind == ctb_io::file::StreamKind::MacOsResourceFork);
4379        assert!(
4380            rsrc_stream.is_some(),
4381            "Resource fork must be preserved in zip style"
4382        );
4383        assert_eq!(
4384            rsrc_stream.unwrap().data.as_deref(),
4385            Some(&b"Zip Resource Fork"[..])
4386        );
4387    }
4388
4389    #[crate::ctb_test]
4390    fn test_csc_copy_apple_double_netatalk_roundtrip() {
4391        let temp = tempdir().expect("tempdir");
4392        let src = temp.path().join("src");
4393        let dest = temp.path().join("dest");
4394        let state = temp.path().join("state");
4395        fs::create_dir_all(&src).unwrap();
4396        fs::create_dir_all(&state).unwrap();
4397        fs::write(src.join("netadoc.bin"), b"Netatalk Payload").unwrap();
4398
4399        let archive = ctb_io::file::AppleArchive {
4400            format: ctb_io::file::AppleFormat::AppleDouble,
4401            version: ctb_io::file::VERSION_2_0_BE,
4402            real_name: Some("netadoc.bin".to_string()),
4403            comment: None,
4404            timestamps: None,
4405            backup_timestamp_sec: None,
4406            finder_info: Some(ctb_io::file::FinderInfo {
4407                file_type: "BINA".to_string(),
4408                file_creator: "bina".to_string(),
4409                label: ctb_io::file::FinderLabel::from_index(0),
4410                flags: ctb_io::file::FinderFlags::default(),
4411                location: (0, 0),
4412                folder_id: 0,
4413                extended: None,
4414                window_bounds: None,
4415            }),
4416            extended_attributes: Vec::new(),
4417            data_fork: None,
4418            resource_fork: Some(b"Netatalk Resource Data".to_vec()),
4419            data_fork_size: None,
4420            resource_fork_size: Some(22),
4421            unrecognized_entries: Vec::new(),
4422            entries: Vec::new(),
4423        };
4424        let companion_bytes =
4425            ctb_io::file::write_apple_single_double(&archive).unwrap();
4426        fs::write(src.join("._netadoc.bin"), companion_bytes).unwrap();
4427
4428        let mut args = default_test_args(
4429            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
4430            state,
4431        );
4432        args.read_apple_double_alongside = true;
4433        args.force_write_apple_double = Some(AppleDoubleStyle::Netatalk);
4434
4435        let res = run_csc(args).expect("run csc");
4436        match res {
4437            ctb_utilities::cli::ToolResult::Immediate { exit_code, .. } => {
4438                assert_eq!(exit_code, 0);
4439            }
4440            _ => panic!("Expected immediate result"),
4441        }
4442
4443        assert_eq!(
4444            fs::read(dest.join("netadoc.bin")).unwrap(),
4445            b"Netatalk Payload"
4446        );
4447        let netatalk_companion = dest.join(".AppleDouble").join("netadoc.bin");
4448        assert!(
4449            netatalk_companion.exists(),
4450            ".AppleDouble/netadoc.bin must exist on dest"
4451        );
4452
4453        let opts = ctb_io::file::AppleReadOptions {
4454            read_apple_double_netatalk: true,
4455            ..ctb_io::file::AppleReadOptions::default()
4456        };
4457        let entity =
4458            ctb_io::file::FileEntity::from_filesystem_with_apple_options(
4459                &dest.join("netadoc.bin"),
4460                Some(&dest),
4461                &opts,
4462            )
4463            .unwrap();
4464
4465        let rsrc_stream = entity
4466            .streams
4467            .iter()
4468            .find(|s| s.kind == ctb_io::file::StreamKind::MacOsResourceFork);
4469        assert!(
4470            rsrc_stream.is_some(),
4471            "Resource fork must be preserved in netatalk style"
4472        );
4473        assert_eq!(
4474            rsrc_stream.unwrap().data.as_deref(),
4475            Some(&b"Netatalk Resource Data"[..])
4476        );
4477    }
4478
4479    #[crate::ctb_test]
4480    fn test_csc_copy_apple_single_roundtrip_and_no_as_extension() {
4481        let temp = tempdir().expect("tempdir");
4482        let src = temp.path().join("src");
4483        let dest = temp.path().join("dest");
4484        let state = temp.path().join("state");
4485        fs::create_dir_all(&src).unwrap();
4486        fs::create_dir_all(&state).unwrap();
4487        fs::write(src.join("my_file.txt"), b"AppleSingle Plain Data").unwrap();
4488
4489        let archive = ctb_io::file::AppleArchive {
4490            format: ctb_io::file::AppleFormat::AppleDouble,
4491            version: ctb_io::file::VERSION_2_0_BE,
4492            real_name: Some("my_file.txt".to_string()),
4493            comment: Some("Single Test Comment".to_string()),
4494            timestamps: None,
4495            backup_timestamp_sec: None,
4496            finder_info: Some(ctb_io::file::FinderInfo {
4497                file_type: "APPL".to_string(),
4498                file_creator: "macs".to_string(),
4499                label: ctb_io::file::FinderLabel::from_index(0),
4500                flags: ctb_io::file::FinderFlags::default(),
4501                location: (0, 0),
4502                folder_id: 0,
4503                extended: None,
4504                window_bounds: None,
4505            }),
4506            extended_attributes: Vec::new(),
4507            data_fork: None,
4508            resource_fork: Some(b"Single Resource Fork Data".to_vec()),
4509            data_fork_size: None,
4510            resource_fork_size: Some(25),
4511            unrecognized_entries: Vec::new(),
4512            entries: Vec::new(),
4513        };
4514        let companion_bytes =
4515            ctb_io::file::write_apple_single_double(&archive).unwrap();
4516        fs::write(src.join("._my_file.txt"), companion_bytes).unwrap();
4517
4518        let mut args = default_test_args(
4519            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
4520            state,
4521        );
4522        args.read_apple_double_alongside = true;
4523        args.force_write_apple_single = true;
4524
4525        let res = run_csc(args).expect("run csc");
4526        match res {
4527            ctb_utilities::cli::ToolResult::Immediate { exit_code, .. } => {
4528                assert_eq!(exit_code, 0);
4529            }
4530            _ => panic!("Expected immediate result"),
4531        }
4532
4533        // AppleSingle file MUST NOT get a .as extension appended!
4534        assert!(
4535            dest.join("my_file.txt").exists(),
4536            "Destination file must be my_file.txt"
4537        );
4538        assert!(
4539            !dest.join("my_file.txt.as").exists(),
4540            "Destination file must NOT have .as appended"
4541        );
4542
4543        // Verify magic bytes on disk are AppleSingle
4544        let disk_bytes = fs::read(dest.join("my_file.txt")).unwrap();
4545        let magic = u32::from_be_bytes(disk_bytes[..4].try_into().unwrap());
4546        assert_eq!(magic, ctb_io::file::APPLESINGLE_MAGIC_BE);
4547
4548        // Read and decode with read_apple_single
4549        let opts = ctb_io::file::AppleReadOptions {
4550            read_apple_single: true,
4551            ..ctb_io::file::AppleReadOptions::default()
4552        };
4553        let entity =
4554            ctb_io::file::FileEntity::from_filesystem_with_apple_options(
4555                &dest.join("my_file.txt"),
4556                Some(&dest),
4557                &opts,
4558            )
4559            .unwrap();
4560
4561        assert!(entity.is_regular());
4562        if let ctb_io::file::FileEntityKind::Regular { size, .. } = entity.kind
4563        {
4564            assert_eq!(size, 22); // length of b"AppleSingle Plain Data"
4565        } else {
4566            panic!("Expected regular entity");
4567        }
4568
4569        let rsrc_stream = entity
4570            .streams
4571            .iter()
4572            .find(|s| s.kind == ctb_io::file::StreamKind::MacOsResourceFork);
4573        assert!(
4574            rsrc_stream.is_some(),
4575            "Resource fork must be preserved in AppleSingle"
4576        );
4577        assert_eq!(
4578            rsrc_stream.unwrap().data.as_deref(),
4579            Some(&b"Single Resource Fork Data"[..])
4580        );
4581        assert_eq!(
4582            entity
4583                .metadata
4584                .apple
4585                .as_ref()
4586                .and_then(|a| a.finder_info.as_ref())
4587                .map(|f| f.file_type.as_str()),
4588            Some("APPL")
4589        );
4590    }
4591
4592    #[crate::ctb_test]
4593    fn test_csc_orphan_apple_double_preserved_during_traversal() {
4594        let temp = tempdir().expect("tempdir");
4595        let src = temp.path().join("src");
4596        let dest = temp.path().join("dest");
4597        let state = temp.path().join("state");
4598        fs::create_dir_all(&src).unwrap();
4599        fs::create_dir_all(&state).unwrap();
4600
4601        fs::write(src.join("valid.txt"), b"Valid base file").unwrap();
4602
4603        let archive = ctb_io::file::AppleArchive {
4604            format: ctb_io::file::AppleFormat::AppleDouble,
4605            version: ctb_io::file::VERSION_2_0_BE,
4606            real_name: Some("valid.txt".to_string()),
4607            comment: None,
4608            timestamps: None,
4609            backup_timestamp_sec: None,
4610            finder_info: None,
4611            extended_attributes: Vec::new(),
4612            data_fork: None,
4613            resource_fork: Some(b"valid rsrc".to_vec()),
4614            data_fork_size: None,
4615            resource_fork_size: Some(10),
4616            unrecognized_entries: Vec::new(),
4617            entries: Vec::new(),
4618        };
4619        let valid_companion_bytes =
4620            ctb_io::file::write_apple_single_double(&archive).unwrap();
4621        fs::write(src.join("._valid.txt"), valid_companion_bytes).unwrap();
4622
4623        // Orphaned AppleDouble companion (no sibling "orphan.txt")
4624        let orphan_archive = ctb_io::file::AppleArchive {
4625            format: ctb_io::file::AppleFormat::AppleDouble,
4626            version: ctb_io::file::VERSION_2_0_BE,
4627            real_name: Some("orphan.txt".to_string()),
4628            comment: None,
4629            timestamps: None,
4630            backup_timestamp_sec: None,
4631            finder_info: None,
4632            extended_attributes: Vec::new(),
4633            data_fork: None,
4634            resource_fork: Some(b"orphan rsrc".to_vec()),
4635            data_fork_size: None,
4636            resource_fork_size: Some(11),
4637            unrecognized_entries: Vec::new(),
4638            entries: Vec::new(),
4639        };
4640        let orphan_bytes =
4641            ctb_io::file::write_apple_single_double(&orphan_archive).unwrap();
4642        fs::write(src.join("._orphan.txt"), orphan_bytes).unwrap();
4643
4644        // Plain text file starting with "._" that is NOT an AppleDouble file
4645        fs::write(src.join("._fake.txt"), b"plain text not appledouble")
4646            .unwrap();
4647
4648        let mut args = default_test_args(
4649            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
4650            state,
4651        );
4652        args.read_apple_double_alongside = true;
4653        args.maybe_write_apple_double = Some(AppleDoubleStyle::Alongside);
4654
4655        let res = run_csc(args).expect("run csc");
4656        match res {
4657            ctb_utilities::cli::ToolResult::Immediate { exit_code, .. } => {
4658                assert_eq!(exit_code, 0);
4659            }
4660            _ => panic!("Expected immediate result"),
4661        }
4662
4663        // 1. valid.txt must exist on dest
4664        assert!(dest.join("valid.txt").exists());
4665
4666        // 2. Orphaned ._orphan.txt MUST NOT be omitted; it must be copied as an ordinary file
4667        assert!(
4668            dest.join("._orphan.txt").exists(),
4669            "Orphaned ._orphan.txt must be preserved on dest"
4670        );
4671
4672        // 3. Fake ._fake.txt MUST NOT be omitted; it must be copied as an ordinary file
4673        assert!(
4674            dest.join("._fake.txt").exists(),
4675            "Fake ._fake.txt must be preserved on dest"
4676        );
4677        assert_eq!(
4678            fs::read(dest.join("._fake.txt")).unwrap(),
4679            b"plain text not appledouble"
4680        );
4681    }
4682
4683    #[cfg(unix)]
4684    #[crate::ctb_test]
4685    fn test_csc_windows_ads_fixture_roundtrip_and_orphan_preservation() {
4686        let fixture_dir = ctb_utilities::manifest_fixture_path(
4687            concat!(env!("CARGO_MANIFEST_DIR"), "/../file"),
4688            "windows_ads",
4689        );
4690        let expected_pan =
4691            fs::read(fixture_dir.join("example2 with lemurs.pan")).unwrap();
4692        let expected_pan_zone = fs::read(
4693            fixture_dir.join("example2 with lemurs.pan:Zone.Identifier"),
4694        )
4695        .unwrap();
4696        let expected_bin =
4697            fs::read(fixture_dir.join("example2 with lemurs-edited.bin"))
4698                .unwrap();
4699        let expected_bin_zone = fs::read(
4700            fixture_dir.join("example2 with lemurs-edited.bin:Zone.Identifier"),
4701        )
4702        .unwrap();
4703
4704        let temp = tempdir().expect("tempdir");
4705        let src = temp.path().join("src");
4706        let dest_ads = temp.path().join("dest_ads");
4707        let dest_apple = temp.path().join("dest_apple");
4708        let state1 = temp.path().join("state1");
4709        let state2 = temp.path().join("state2");
4710        fs::create_dir_all(&src).unwrap();
4711        fs::create_dir_all(&state1).unwrap();
4712        fs::create_dir_all(&state2).unwrap();
4713
4714        fs::write(src.join("example2 with lemurs.pan"), &expected_pan).unwrap();
4715        fs::write(
4716            src.join("example2 with lemurs.pan:Zone.Identifier"),
4717            &expected_pan_zone,
4718        )
4719        .unwrap();
4720        fs::write(src.join("example2 with lemurs-edited.bin"), &expected_bin)
4721            .unwrap();
4722        fs::write(
4723            src.join("example2 with lemurs-edited.bin:Zone.Identifier"),
4724            &expected_bin_zone,
4725        )
4726        .unwrap();
4727        // Orphaned Windows ADS file with no base sibling must be preserved as a normal file
4728        fs::write(
4729            src.join("orphan.bin:Zone.Identifier"),
4730            b"[ZoneTransfer]\r\nZoneId=3\r\n",
4731        )
4732        .unwrap();
4733
4734        // 1. Copy with --read-windows-ads and --force-write-windows-ads: joins companions on read and recreates them on dest
4735        let mut args1 = default_test_args(
4736            vec![
4737                PathBuf::from(format!("{}/", src.display())),
4738                dest_ads.clone(),
4739            ],
4740            state1,
4741        );
4742        args1.read_windows_ads = true;
4743        args1.force_write_windows_ads = true;
4744
4745        let res1 = run_csc(args1).expect("run csc windows ads");
4746        match res1 {
4747            ctb_utilities::cli::ToolResult::Immediate { exit_code, .. } => {
4748                assert_eq!(exit_code, 0);
4749            }
4750            _ => panic!("Expected immediate result"),
4751        }
4752
4753        assert_eq!(
4754            fs::read(dest_ads.join("example2 with lemurs.pan")).unwrap(),
4755            expected_pan
4756        );
4757        assert_eq!(
4758            fs::read(dest_ads.join("example2 with lemurs.pan:Zone.Identifier"))
4759                .unwrap(),
4760            expected_pan_zone
4761        );
4762        assert_eq!(
4763            fs::read(dest_ads.join("example2 with lemurs-edited.bin")).unwrap(),
4764            expected_bin
4765        );
4766        assert_eq!(
4767            fs::read(
4768                dest_ads
4769                    .join("example2 with lemurs-edited.bin:Zone.Identifier")
4770            )
4771            .unwrap(),
4772            expected_bin_zone
4773        );
4774        assert_eq!(
4775            fs::read(dest_ads.join("orphan.bin:Zone.Identifier")).unwrap(),
4776            b"[ZoneTransfer]\r\nZoneId=3\r\n"
4777        );
4778
4779        // Diff src and dest_ads: must match cleanly with 0 untracked entries
4780        let mut diff_args =
4781            crate::args::default_diff_args(src.clone(), dest_ads.clone());
4782        diff_args.read_windows_ads = true;
4783        diff_args.criteria.ignore_ctime = true;
4784        let diff_report = crate::diff_engine::diff_paths(&diff_args).unwrap();
4785        assert!(
4786            diff_report.is_clean(),
4787            "Diff report not clean: {}",
4788            diff_report.format_human_report()
4789        );
4790
4791        // 2. Copy from Windows ADS sidecars to AppleDouble alongside companions (cross-convention conversion!)
4792        let mut args2 = default_test_args(
4793            vec![
4794                PathBuf::from(format!("{}/", dest_ads.display())),
4795                dest_apple.clone(),
4796            ],
4797            state2,
4798        );
4799        args2.read_windows_ads = true;
4800        args2.force_write_apple_double = Some(AppleDoubleStyle::Alongside);
4801
4802        let res2 = run_csc(args2).expect("run csc windows ads to appledouble");
4803        match res2 {
4804            ctb_utilities::cli::ToolResult::Immediate { exit_code, .. } => {
4805                assert_eq!(exit_code, 0);
4806            }
4807            _ => panic!("Expected immediate result"),
4808        }
4809
4810        assert!(dest_apple.join("._example2 with lemurs.pan").exists());
4811        assert!(
4812            !dest_apple
4813                .join("example2 with lemurs.pan:Zone.Identifier")
4814                .exists()
4815        );
4816        let ad_read_opts = ctb_io::file::AppleReadOptions {
4817            read_apple_double_alongside: true,
4818            ..Default::default()
4819        };
4820        let entity_from_apple =
4821            ctb_io::file::FileEntity::from_filesystem_with_apple_options(
4822                &dest_apple.join("example2 with lemurs.pan"),
4823                Some(&dest_apple),
4824                &ad_read_opts,
4825            )
4826            .unwrap();
4827        let zone_from_apple = entity_from_apple
4828            .streams
4829            .iter()
4830            .find(|s| {
4831                s.name.as_ref().is_some_and(|n| {
4832                    n.as_bytes().as_ref() == b"Zone.Identifier"
4833                })
4834            })
4835            .expect("Zone.Identifier preserved inside AppleDouble companion");
4836        assert_eq!(
4837            zone_from_apple.data.as_deref(),
4838            Some(expected_pan_zone.as_slice())
4839        );
4840    }
4841
4842    #[crate::ctb_test]
4843    fn test_csc_directory_windows_ads_and_best_effort_stream_adaptation_journal_verify()
4844     {
4845        let temp = tempdir().expect("tempdir");
4846        let src = temp.path().join("src");
4847        let dest = temp.path().join("dest");
4848        let state = temp.path().join("state");
4849        fs::create_dir_all(&src).unwrap();
4850        fs::create_dir_all(&state).unwrap();
4851
4852        // 1. Subdirectory with an alongside Windows ADS companion (`subdir:Zone.Identifier`)
4853        let subdir = src.join("subdir");
4854        fs::create_dir_all(&subdir).unwrap();
4855        let dir_zone =
4856            b"[ZoneTransfer]\r\nZoneId=3\r\nHostUrl=https://example.com/\r\n";
4857        fs::write(src.join("subdir:Zone.Identifier"), dir_zone).unwrap();
4858        fs::write(subdir.join("inside.txt"), b"inside subdir").unwrap();
4859
4860        // 2. Copy with --read-windows-ads and --force-write-windows-ads and verify with `verify_directory_against_manifest`
4861        let mut args = default_test_args(
4862            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
4863            state.clone(),
4864        );
4865        args.read_windows_ads = true;
4866        args.force_write_windows_ads = true;
4867
4868        let res = run_csc(args).expect("run csc directory windows ads");
4869        match res {
4870            ctb_utilities::cli::ToolResult::Immediate { exit_code, .. } => {
4871                assert_eq!(exit_code, 0);
4872            }
4873            _ => panic!("Expected immediate result"),
4874        }
4875
4876        assert!(dest.join("subdir").is_dir());
4877        assert_eq!(
4878            fs::read(dest.join("subdir:Zone.Identifier")).unwrap(),
4879            dir_zone
4880        );
4881        assert_eq!(
4882            fs::read(dest.join("subdir").join("inside.txt")).unwrap(),
4883            b"inside subdir"
4884        );
4885
4886        let verify_args = crate::args::default_verify_args(state, Some(dest));
4887        let verify_report =
4888            crate::verifier::verify_directory_against_manifest(&verify_args)
4889                .unwrap();
4890        assert!(
4891            verify_report.is_clean(),
4892            "csc verify must pass for directory Windows ADS companion: {}",
4893            verify_report.format_human_report()
4894        );
4895
4896        // 3. Test AppleDouble with slashes/collisions converted to Windows ADS in best-effort mode:
4897        //    - Default mode must fail when stream name contains `/`
4898        //    - `--best-effort-metadata` must clean stream names, disambiguate collisions,
4899        //      record `materialized.stream_name` in the journal, and pass `verify_directory_against_manifest`!
4900        let src2 = temp.path().join("src2");
4901        let dest2_strict = temp.path().join("dest2_strict");
4902        let dest2_best = temp.path().join("dest2_best");
4903        let state2_strict = temp.path().join("state2_strict");
4904        let state2_best = temp.path().join("state2_best");
4905        fs::create_dir_all(&src2).unwrap();
4906        fs::create_dir_all(&state2_strict).unwrap();
4907        fs::create_dir_all(&state2_best).unwrap();
4908
4909        fs::write(src2.join("doc.txt"), b"Document payload").unwrap();
4910        let mut doc_entity = ctb_io::file::FileEntity::from_filesystem(
4911            &src2.join("doc.txt"),
4912            Some(&src2),
4913        )
4914        .unwrap();
4915        doc_entity.streams = vec![
4916            ctb_io::file::AttachedStream::from_data(
4917                Some(ctb_io::file::StreamName::from_bytes(
4918                    b"stream/with/slash",
4919                )),
4920                ctb_io::file::StreamKind::ExtendedAttribute,
4921                b"slash-payload-1".to_vec(),
4922            )
4923            .unwrap(),
4924            ctb_io::file::AttachedStream::from_data(
4925                Some(ctb_io::file::StreamName::from_bytes(
4926                    b"stream\\with\\slash",
4927                )),
4928                ctb_io::file::StreamKind::ExtendedAttribute,
4929                b"slash-payload-2".to_vec(),
4930            )
4931            .unwrap(),
4932            ctb_io::file::AttachedStream::from_data(
4933                Some(ctb_io::file::StreamName::from_bytes(
4934                    b"stream:with:colon",
4935                )),
4936                ctb_io::file::StreamKind::ExtendedAttribute,
4937                b"colon-payload".to_vec(),
4938            )
4939            .unwrap(),
4940        ];
4941        let ad_bytes =
4942            ctb_io::file::serialize_apple_double_for_entity(&doc_entity)
4943                .unwrap();
4944        fs::write(src2.join("._doc.txt"), ad_bytes).unwrap();
4945
4946        // Strict/default copy must fail because `stream/with/slash` is invalid as a sidecar filename
4947        let mut strict_args = default_test_args(
4948            vec![PathBuf::from(format!("{}/", src2.display())), dest2_strict],
4949            state2_strict,
4950        );
4951        strict_args.read_apple_double_alongside = true;
4952        strict_args.force_write_windows_ads = true;
4953        assert!(
4954            run_csc(strict_args).is_err(),
4955            "Default/strict mode must fail on stream names containing path separators or colons"
4956        );
4957
4958        // Best-effort copy must clean, disambiguate, record in journal, and verify!
4959        let mut best_args = default_test_args(
4960            vec![
4961                PathBuf::from(format!("{}/", src2.display())),
4962                dest2_best.clone(),
4963            ],
4964            state2_best.clone(),
4965        );
4966        best_args.read_apple_double_alongside = true;
4967        best_args.force_write_windows_ads = true;
4968        best_args.best_effort_metadata = true;
4969        let best_res =
4970            run_csc(best_args).expect("best-effort copy must succeed");
4971        match best_res {
4972            ctb_utilities::cli::ToolResult::Immediate { exit_code, .. } => {
4973                assert_eq!(exit_code, 0);
4974            }
4975            _ => panic!("Expected immediate result"),
4976        }
4977
4978        assert!(dest2_best.join("doc.txt:stream⌿with⌿slash").exists());
4979        assert!(dest2_best.join("doc.txt:stream_with_colon").exists());
4980
4981        // Verify journal recorded `materialized.stream_name` even when verify runs with best_effort = false!
4982        let mut verify_best_args =
4983            crate::args::default_verify_args(state2_best, Some(dest2_best));
4984        verify_best_args.criteria.best_effort = false;
4985        let verify_best_report =
4986            crate::verifier::verify_directory_against_manifest(
4987                &verify_best_args,
4988            )
4989            .unwrap();
4990        assert!(
4991            verify_best_report.is_clean(),
4992            "csc verify must pass for adapted & disambiguated streams using journal metadata: {}",
4993            verify_best_report.format_human_report()
4994        );
4995    }
4996
4997    #[crate::ctb_test]
4998    fn test_csc_read_apple_single_with_extension_strips() {
4999        let temp = tempdir().expect("tempdir");
5000        let src = temp.path().join("src");
5001        let dest = temp.path().join("dest");
5002        let state = temp.path().join("state");
5003        fs::create_dir_all(&src).unwrap();
5004        fs::create_dir_all(&state).unwrap();
5005
5006        let archive = ctb_io::file::AppleArchive {
5007            format: ctb_io::file::AppleFormat::AppleSingle,
5008            version: ctb_io::file::VERSION_2_0_BE,
5009            real_name: Some("doc".to_string()),
5010            comment: None,
5011            timestamps: None,
5012            backup_timestamp_sec: None,
5013            finder_info: None,
5014            extended_attributes: Vec::new(),
5015            data_fork: Some(b"Unpacked doc payload".to_vec()),
5016            resource_fork: None,
5017            data_fork_size: Some(20),
5018            resource_fork_size: None,
5019            unrecognized_entries: Vec::new(),
5020            entries: Vec::new(),
5021        };
5022        let single_bytes =
5023            ctb_io::file::write_apple_single_double(&archive).unwrap();
5024        fs::write(src.join("doc.as"), single_bytes).unwrap();
5025
5026        let mut args = default_test_args(
5027            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
5028            state,
5029        );
5030        args.read_apple_single_with_extension =
5031            vec![ctb_io::file::AppleSingleExtension::As];
5032        args.force_write_apple_double = Some(AppleDoubleStyle::Alongside);
5033
5034        let res = run_csc(args).expect("run csc");
5035        match res {
5036            ctb_utilities::cli::ToolResult::Immediate { exit_code, .. } => {
5037                assert_eq!(exit_code, 0);
5038            }
5039            _ => panic!("Expected immediate result"),
5040        }
5041
5042        // Extension .as must be stripped automatically upon valid AppleSingle decode
5043        assert!(
5044            dest.join("doc").exists(),
5045            "Stripped destination 'doc' must exist"
5046        );
5047        assert_eq!(
5048            fs::read(dest.join("doc")).unwrap(),
5049            b"Unpacked doc payload"
5050        );
5051        assert!(
5052            !dest.join("doc.as").exists(),
5053            "doc.as must not exist on dest"
5054        );
5055    }
5056
5057    #[crate::ctb_test]
5058    fn test_csc_read_apple_single_non_applesingle_preserves_extension() {
5059        let temp = tempdir().expect("tempdir");
5060        let src = temp.path().join("src");
5061        let dest = temp.path().join("dest");
5062        let state = temp.path().join("state");
5063        fs::create_dir_all(&src).unwrap();
5064        fs::create_dir_all(&state).unwrap();
5065
5066        // Ordinary ActionScript source file (not AppleSingle)
5067        fs::write(src.join("script.as"), b"package { class Main {} }").unwrap();
5068
5069        let mut args = default_test_args(
5070            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
5071            state,
5072        );
5073        args.read_apple_single_with_extension =
5074            vec![ctb_io::file::AppleSingleExtension::As];
5075
5076        let res = run_csc(args).expect("run csc");
5077        match res {
5078            ctb_utilities::cli::ToolResult::Immediate { exit_code, .. } => {
5079                assert_eq!(exit_code, 0);
5080            }
5081            _ => panic!("Expected immediate result"),
5082        }
5083
5084        // Non-AppleSingle file must preserve its .as extension intact
5085        assert!(
5086            dest.join("script.as").exists(),
5087            "script.as must remain intact"
5088        );
5089        assert_eq!(
5090            fs::read(dest.join("script.as")).unwrap(),
5091            b"package { class Main {} }"
5092        );
5093        assert!(!dest.join("script").exists(), "script must not exist");
5094    }
5095
5096    #[crate::ctb_test]
5097    fn test_csc_apple_single_dependency_ordering() {
5098        let temp = tempdir().expect("tempdir");
5099        let src = temp.path().join("src");
5100        let dest = temp.path().join("dest");
5101        let state = temp.path().join("state");
5102        fs::create_dir_all(&src).unwrap();
5103        fs::create_dir_all(&state).unwrap();
5104
5105        // Foo.as and Foo.as.as
5106        fs::write(src.join("Foo.as"), b"content of Foo.as").unwrap();
5107        fs::write(src.join("Foo.as.as"), b"content of Foo.as.as").unwrap();
5108
5109        let mut args = default_test_args(
5110            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
5111            state,
5112        );
5113        args.force_write_apple_single = true;
5114        args.write_apple_single_with_extension =
5115            Some(ctb_io::file::AppleSingleExtension::As);
5116
5117        let res = run_csc(args).expect("run csc");
5118        match res {
5119            ctb_utilities::cli::ToolResult::Immediate { exit_code, .. } => {
5120                assert_eq!(exit_code, 0);
5121            }
5122            _ => panic!("Expected immediate result"),
5123        }
5124
5125        // Foo.as -> Foo.as.as and Foo.as.as -> Foo.as.as.as
5126        assert!(dest.join("Foo.as.as").exists(), "Foo.as.as must exist");
5127        assert!(
5128            dest.join("Foo.as.as.as").exists(),
5129            "Foo.as.as.as must exist"
5130        );
5131
5132        let d1 = fs::read(dest.join("Foo.as.as")).unwrap();
5133        let a1 = ctb_io::file::read_apple_single_double(&d1).unwrap();
5134        assert_eq!(a1.data_fork.as_deref(), Some(&b"content of Foo.as"[..]));
5135
5136        let d2 = fs::read(dest.join("Foo.as.as.as")).unwrap();
5137        let a2 = ctb_io::file::read_apple_single_double(&d2).unwrap();
5138        assert_eq!(a2.data_fork.as_deref(), Some(&b"content of Foo.as.as"[..]));
5139    }
5140
5141    #[crate::ctb_test]
5142    fn test_csc_apple_single_name_collision_preservation() {
5143        let temp = tempdir().expect("tempdir");
5144        let src = temp.path().join("src");
5145        let dest = temp.path().join("dest");
5146        let state = temp.path().join("state");
5147        fs::create_dir_all(&src).unwrap();
5148        fs::create_dir_all(&state).unwrap();
5149
5150        // Three files with potential collision: Foo, Foo.as, Foo.as.as
5151        fs::write(src.join("Foo"), b"content of Foo").unwrap();
5152        fs::write(src.join("Foo.as"), b"content of Foo.as").unwrap();
5153        fs::write(src.join("Foo.as.as"), b"content of Foo.as.as").unwrap();
5154
5155        let mut args = default_test_args(
5156            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
5157            state,
5158        );
5159        args.force_write_apple_single = true;
5160
5161        let res = run_csc(args).expect("run csc");
5162        match res {
5163            ctb_utilities::cli::ToolResult::Immediate { exit_code, .. } => {
5164                assert_eq!(exit_code, 0);
5165            }
5166            _ => panic!("Expected immediate result"),
5167        }
5168
5169        // All three files must exist independently and not clobber each other
5170        assert!(dest.join("Foo").exists());
5171        assert!(dest.join("Foo.as").exists());
5172        assert!(dest.join("Foo.as.as").exists());
5173
5174        let opts = ctb_io::file::AppleReadOptions {
5175            read_apple_single: true,
5176            ..ctb_io::file::AppleReadOptions::default()
5177        };
5178
5179        let e1 = ctb_io::file::FileEntity::from_filesystem_with_apple_options(
5180            &dest.join("Foo"),
5181            Some(&dest),
5182            &opts,
5183        )
5184        .unwrap();
5185        let e2 = ctb_io::file::FileEntity::from_filesystem_with_apple_options(
5186            &dest.join("Foo.as"),
5187            Some(&dest),
5188            &opts,
5189        )
5190        .unwrap();
5191        let e3 = ctb_io::file::FileEntity::from_filesystem_with_apple_options(
5192            &dest.join("Foo.as.as"),
5193            Some(&dest),
5194            &opts,
5195        )
5196        .unwrap();
5197
5198        if let ctb_io::file::FileEntityKind::Regular { size, .. } = e1.kind {
5199            assert_eq!(size, 14); // "content of Foo"
5200        }
5201        if let ctb_io::file::FileEntityKind::Regular { size, .. } = e2.kind {
5202            assert_eq!(size, 17); // "content of Foo.as"
5203        }
5204        if let ctb_io::file::FileEntityKind::Regular { size, .. } = e3.kind {
5205            assert_eq!(size, 20); // "content of Foo.as.as"
5206        }
5207    }
5208
5209    #[crate::ctb_test]
5210    fn test_csc_read_apple_single_collision_bailout() {
5211        let temp = tempdir().expect("tempdir");
5212        let src = temp.path().join("src");
5213        let dest = temp.path().join("dest");
5214        let state = temp.path().join("state");
5215        fs::create_dir_all(&src).unwrap();
5216        fs::create_dir_all(&state).unwrap();
5217
5218        // Sibling files: foo and foo.as
5219        fs::write(src.join("foo"), b"regular file foo").unwrap();
5220
5221        let archive = ctb_io::file::AppleArchive {
5222            format: ctb_io::file::AppleFormat::AppleSingle,
5223            version: ctb_io::file::VERSION_2_0_BE,
5224            real_name: Some("foo".to_string()),
5225            comment: None,
5226            timestamps: None,
5227            backup_timestamp_sec: None,
5228            finder_info: None,
5229            extended_attributes: Vec::new(),
5230            data_fork: Some(b"applesingle foo".to_vec()),
5231            resource_fork: None,
5232            data_fork_size: Some(15),
5233            resource_fork_size: None,
5234            unrecognized_entries: Vec::new(),
5235            entries: Vec::new(),
5236        };
5237        let single_bytes =
5238            ctb_io::file::write_apple_single_double(&archive).unwrap();
5239        fs::write(src.join("foo.as"), single_bytes).unwrap();
5240
5241        let mut args = default_test_args(
5242            vec![PathBuf::from(format!("{}/", src.display())), dest],
5243            state,
5244        );
5245        args.read_apple_single_with_extension =
5246            vec![ctb_io::file::AppleSingleExtension::As];
5247
5248        // Must bail out because both unpack/target 'foo'
5249        match run_csc(args) {
5250            Err(err) => {
5251                let err_msg = err.to_string();
5252                assert!(
5253                    err_msg.contains("collision")
5254                        || err_msg.contains("Target collision"),
5255                    "Error message must report collision: {err_msg}"
5256                );
5257            }
5258            Ok(_) => {
5259                panic!("Must error on target collision between foo and foo.as")
5260            }
5261        }
5262    }
5263
5264    #[crate::ctb_test]
5265    fn test_csc_apple_double_companion_collision_bailout() {
5266        let temp = tempdir().expect("tempdir");
5267        let src = temp.path().join("src");
5268        let dest = temp.path().join("dest");
5269        let state = temp.path().join("state");
5270        fs::create_dir_all(&src).unwrap();
5271        fs::create_dir_all(&state).unwrap();
5272
5273        fs::write(src.join("file.txt"), b"base file").unwrap();
5274        // Independent file that happens to match the companion path
5275        fs::write(src.join("._file.txt"), b"independent not appledouble")
5276            .unwrap();
5277
5278        let mut args = default_test_args(
5279            vec![PathBuf::from(format!("{}/", src.display())), dest],
5280            state,
5281        );
5282        args.force_write_apple_double = Some(AppleDoubleStyle::Alongside);
5283
5284        match run_csc(args) {
5285            Err(err) => {
5286                let err_msg = err.to_string();
5287                assert!(
5288                    err_msg.contains("collision")
5289                        || err_msg.contains("Companion collision"),
5290                    "Error message must report collision: {err_msg}"
5291                );
5292            }
5293            Ok(_) => panic!(
5294                "Must error on companion collision with independent ._file.txt"
5295            ),
5296        }
5297    }
5298
5299    #[crate::ctb_test]
5300    fn test_csc_netatalk_companion_collision_bailout() {
5301        let temp = tempdir().expect("tempdir");
5302        let src = temp.path().join("src");
5303        let dest = temp.path().join("dest");
5304        let state = temp.path().join("state");
5305        fs::create_dir_all(src.join(".AppleDouble")).unwrap();
5306        fs::create_dir_all(&state).unwrap();
5307
5308        fs::write(src.join("file.txt"), b"base file").unwrap();
5309        // Preexisting independent file in .AppleDouble
5310        fs::write(
5311            src.join(".AppleDouble").join("file.txt"),
5312            b"independent netatalk",
5313        )
5314        .unwrap();
5315
5316        let mut args = default_test_args(
5317            vec![PathBuf::from(format!("{}/", src.display())), dest],
5318            state,
5319        );
5320        args.force_write_apple_double = Some(AppleDoubleStyle::Netatalk);
5321
5322        let res = run_csc(args);
5323        assert!(
5324            res.is_err(),
5325            "Must error on companion collision with independent .AppleDouble/file.txt"
5326        );
5327    }
5328
5329    #[crate::ctb_test]
5330    fn test_csc_zip_apple_double_macosx_file_collision_bailout() {
5331        let temp = tempdir().expect("tempdir");
5332        let src = temp.path().join("src");
5333        let dest = temp.path().join("dest");
5334        let state = temp.path().join("state");
5335        fs::create_dir_all(&src).unwrap();
5336        fs::create_dir_all(&state).unwrap();
5337
5338        fs::write(src.join("__MACOSX"), b"regular file not dir").unwrap();
5339        fs::write(src.join("foo.txt"), b"some content").unwrap();
5340
5341        let mut args = default_test_args(
5342            vec![PathBuf::from(format!("{}/", src.display())), dest],
5343            state,
5344        );
5345        args.force_write_apple_double = Some(AppleDoubleStyle::Zip);
5346
5347        match run_csc(args) {
5348            Err(err) => {
5349                let msg = err.to_string();
5350                assert!(
5351                    msg.contains("collision") || msg.contains("__MACOSX"),
5352                    "Error must report __MACOSX collision: {msg}"
5353                );
5354            }
5355            Ok(_) => panic!(
5356                "Must bail on regular file __MACOSX collision with AppleDouble zip"
5357            ),
5358        }
5359    }
5360
5361    #[crate::ctb_test]
5362    fn test_csc_netatalk_dot_appledouble_file_collision_bailout() {
5363        let temp = tempdir().expect("tempdir");
5364        let src = temp.path().join("src");
5365        let dest = temp.path().join("dest");
5366        let state = temp.path().join("state");
5367        fs::create_dir_all(&src).unwrap();
5368        fs::create_dir_all(&state).unwrap();
5369
5370        fs::write(src.join(".AppleDouble"), b"regular file not dir").unwrap();
5371        fs::write(src.join("foo.txt"), b"some content").unwrap();
5372
5373        let mut args = default_test_args(
5374            vec![PathBuf::from(format!("{}/", src.display())), dest],
5375            state,
5376        );
5377        args.force_write_apple_double = Some(AppleDoubleStyle::Netatalk);
5378
5379        match run_csc(args) {
5380            Err(err) => {
5381                let msg = err.to_string();
5382                assert!(
5383                    msg.contains("collision") || msg.contains(".AppleDouble"),
5384                    "Error must report .AppleDouble collision: {msg}"
5385                );
5386            }
5387            Ok(_) => panic!(
5388                "Must bail on regular file .AppleDouble collision with Netatalk"
5389            ),
5390        }
5391    }
5392
5393    #[crate::ctb_test]
5394    fn test_csc_netatalk_parent_file_collision_bailout() {
5395        let temp = tempdir().expect("tempdir");
5396        let src = temp.path().join("src");
5397        let dest = temp.path().join("dest");
5398        let state = temp.path().join("state");
5399        fs::create_dir_all(&src).unwrap();
5400        fs::create_dir_all(&state).unwrap();
5401
5402        fs::write(src.join(".Parent"), b"regular file named .Parent").unwrap();
5403
5404        let mut args = default_test_args(
5405            vec![PathBuf::from(format!("{}/", src.display())), dest],
5406            state,
5407        );
5408        args.force_write_apple_double = Some(AppleDoubleStyle::Netatalk);
5409
5410        match run_csc(args) {
5411            Err(err) => {
5412                let msg = err.to_string();
5413                assert!(
5414                    msg.contains("collision") || msg.contains(".Parent"),
5415                    "Error must report .Parent collision: {msg}"
5416                );
5417            }
5418            Ok(_) => panic!(
5419                "Must bail on regular file .Parent collision with Netatalk metadata"
5420            ),
5421        }
5422    }
5423
5424    #[crate::ctb_test]
5425    fn test_csc_foo_as_and_foo_as_as_target_collision_bailout() {
5426        let temp = tempdir().expect("tempdir");
5427        let src = temp.path().join("src");
5428        let dest = temp.path().join("dest");
5429        let state = temp.path().join("state");
5430        fs::create_dir_all(&src).unwrap();
5431        fs::create_dir_all(&state).unwrap();
5432
5433        // foo.as is a regular file (not AppleSingle)
5434        fs::write(src.join("foo.as"), b"regular actionscript").unwrap();
5435
5436        // foo.as.as is AppleSingle
5437        let archive = ctb_io::file::AppleArchive {
5438            format: ctb_io::file::AppleFormat::AppleSingle,
5439            version: ctb_io::file::VERSION_2_0_BE,
5440            real_name: Some("foo.as".to_string()),
5441            comment: None,
5442            timestamps: None,
5443            backup_timestamp_sec: None,
5444            finder_info: None,
5445            extended_attributes: Vec::new(),
5446            data_fork: Some(b"nested applesingle".to_vec()),
5447            resource_fork: None,
5448            data_fork_size: Some(18),
5449            resource_fork_size: None,
5450            unrecognized_entries: Vec::new(),
5451            entries: Vec::new(),
5452        };
5453        let single_bytes =
5454            ctb_io::file::write_apple_single_double(&archive).unwrap();
5455        fs::write(src.join("foo.as.as"), single_bytes).unwrap();
5456
5457        let mut args = default_test_args(
5458            vec![PathBuf::from(format!("{}/", src.display())), dest],
5459            state,
5460        );
5461        args.read_apple_single_with_extension =
5462            vec![ctb_io::file::AppleSingleExtension::As];
5463
5464        // foo.as targets dest/foo.as; foo.as.as unpacks to dest/foo.as -> Collision!
5465        match run_csc(args) {
5466            Err(err) => {
5467                let msg = err.to_string();
5468                assert!(
5469                    msg.contains("collision")
5470                        || msg.contains("Target collision"),
5471                    "Error must report collision: {msg}"
5472                );
5473            }
5474            Ok(_) => panic!(
5475                "Must bail on target collision between foo.as and foo.as.as"
5476            ),
5477        }
5478    }
5479
5480    #[crate::ctb_test]
5481    fn test_csc_as_and_asf_target_collision_bailout() {
5482        let temp = tempdir().expect("tempdir");
5483        let src = temp.path().join("src");
5484        let dest = temp.path().join("dest");
5485        let state = temp.path().join("state");
5486        fs::create_dir_all(&src).unwrap();
5487        fs::create_dir_all(&state).unwrap();
5488
5489        let archive = ctb_io::file::AppleArchive {
5490            format: ctb_io::file::AppleFormat::AppleSingle,
5491            version: ctb_io::file::VERSION_2_0_BE,
5492            real_name: Some("doc".to_string()),
5493            comment: None,
5494            timestamps: None,
5495            backup_timestamp_sec: None,
5496            finder_info: None,
5497            extended_attributes: Vec::new(),
5498            data_fork: Some(b"doc content".to_vec()),
5499            resource_fork: None,
5500            data_fork_size: Some(11),
5501            resource_fork_size: None,
5502            unrecognized_entries: Vec::new(),
5503            entries: Vec::new(),
5504        };
5505        let single_bytes =
5506            ctb_io::file::write_apple_single_double(&archive).unwrap();
5507        fs::write(src.join("doc.as"), &single_bytes).unwrap();
5508        fs::write(src.join("doc.asf"), &single_bytes).unwrap();
5509
5510        let mut args = default_test_args(
5511            vec![PathBuf::from(format!("{}/", src.display())), dest],
5512            state,
5513        );
5514        args.read_apple_single_with_extension = vec![
5515            ctb_io::file::AppleSingleExtension::As,
5516            ctb_io::file::AppleSingleExtension::Asf,
5517        ];
5518
5519        // Both doc.as and doc.asf strip to dest/doc -> Collision!
5520        match run_csc(args) {
5521            Err(err) => {
5522                let msg = err.to_string();
5523                assert!(
5524                    msg.contains("collision")
5525                        || msg.contains("Target collision"),
5526                    "Error must report collision: {msg}"
5527                );
5528            }
5529            Ok(_) => panic!(
5530                "Must bail on target collision between doc.as and doc.asf"
5531            ),
5532        }
5533    }
5534
5535    #[crate::ctb_test]
5536    fn test_csc_double_dot_underscore_companion_collision_bailout() {
5537        let temp = tempdir().expect("tempdir");
5538        let src = temp.path().join("src");
5539        let dest = temp.path().join("dest");
5540        let state = temp.path().join("state");
5541        fs::create_dir_all(&src).unwrap();
5542        fs::create_dir_all(&state).unwrap();
5543
5544        // Independent ._foo and ._._foo files
5545        fs::write(src.join("._foo"), b"independent file 1").unwrap();
5546        fs::write(src.join("._._foo"), b"independent file 2").unwrap();
5547
5548        let mut args = default_test_args(
5549            vec![PathBuf::from(format!("{}/", src.display())), dest],
5550            state,
5551        );
5552        // Turn off reading apple double alongside so both are treated as independent files
5553        args.no_read_apple_double_alongside = true;
5554        args.force_write_apple_double = Some(AppleDoubleStyle::Alongside);
5555
5556        // Writing alongside for ._foo produces companion ._._foo, which collides with destination for ._._foo
5557        match run_csc(args) {
5558            Err(err) => {
5559                let msg = err.to_string();
5560                assert!(
5561                    msg.contains("collision")
5562                        || msg.contains("Companion collision"),
5563                    "Error must report collision: {msg}"
5564                );
5565            }
5566            Ok(_) => {
5567                panic!("Must bail on companion collision for ._foo and ._._foo")
5568            }
5569        }
5570    }
5571
5572    #[cfg(unix)]
5573    fn run_permission_test_unprivileged(test_name: &str) -> bool {
5574        crate::run_permission_test_unprivileged(&format!(
5575            "copy_engine::tests::{test_name}"
5576        ))
5577        .unwrap()
5578    }
5579
5580    #[cfg(unix)]
5581    #[crate::ctb_test]
5582    fn test_csc_continue_on_error_copies_remaining_and_records_errors_and_warnings()
5583     {
5584        if run_permission_test_unprivileged(
5585            "test_csc_continue_on_error_copies_remaining_and_records_errors_and_warnings",
5586        ) {
5587            return;
5588        }
5589        let temp = tempdir().expect("create tempdir");
5590        let src = temp.path().join("src");
5591        let dest = temp.path().join("dest");
5592        let state = temp.path().join("state");
5593        fs::create_dir_all(&src).expect("create src");
5594        fs::create_dir_all(&state).expect("create state");
5595
5596        let readable_file = src.join("readable.txt");
5597        let unreadable_file = src.join("unreadable.txt");
5598        fs::write(&readable_file, b"readable content").expect("write readable");
5599        fs::write(&unreadable_file, b"unreadable content")
5600            .expect("write unreadable");
5601
5602        fs::set_permissions(
5603            &unreadable_file,
5604            fs::Permissions::from_mode(0o000),
5605        )
5606        .expect("chmod 000");
5607
5608        let mut args = default_test_args(
5609            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
5610            state.clone(),
5611        );
5612        args.continue_on_error = true;
5613
5614        let res = run_csc(args);
5615        let _ = fs::set_permissions(
5616            &unreadable_file,
5617            fs::Permissions::from_mode(0o644),
5618        );
5619
5620        let res = res.expect("run_csc with continue_on_error must succeed");
5621        match res {
5622            ctb_utilities::cli::ToolResult::Immediate {
5623                stdout,
5624                exit_code,
5625                ..
5626            } => {
5627                assert_ne!(exit_code, 0);
5628                let out = String::from_utf8_lossy(&stdout);
5629                assert!(out.contains("Errors recorded:"));
5630            }
5631            _ => panic!("Expected Immediate ToolResult"),
5632        }
5633
5634        assert_eq!(
5635            fs::read(dest.join("readable.txt")).expect("read copied file"),
5636            b"readable content"
5637        );
5638        assert!(
5639            !dest.join("unreadable.txt").exists(),
5640            "unreadable file must not be copied"
5641        );
5642
5643        let journal_path = crate::journal::find_cscjournal(&state);
5644        let snapshot = crate::journal::read_journal_snapshot(&journal_path)
5645            .expect("read journal snapshot");
5646        assert_eq!(snapshot.errors.len(), 1);
5647        let err = &snapshot.errors[0];
5648        assert_eq!(err.stage, crate::journal::JournalErrorStage::MetadataRead);
5649        assert!(err.path.to_string_lossy().contains("unreadable.txt"));
5650
5651        assert!(
5652            !snapshot.warnings.is_empty(),
5653            "Warnings must be recorded in journal"
5654        );
5655
5656        let desc_path = journal_path.with_extension("cscdesc");
5657        let desc_content = fs::read_to_string(&desc_path).expect("read desc");
5658        assert!(
5659            desc_content.contains("ErrorsCount: 1"),
5660            "desc must report ErrorsCount: 1: {desc_content}"
5661        );
5662        assert!(
5663            desc_content.contains("unreadable.txt"),
5664            "desc must contain error path"
5665        );
5666        assert!(
5667            desc_content.contains("WarningsCount:"),
5668            "desc must report WarningsCount"
5669        );
5670    }
5671
5672    #[cfg(unix)]
5673    #[crate::ctb_test]
5674    fn test_csc_aborts_and_records_error_without_continue_on_error() {
5675        if run_permission_test_unprivileged(
5676            "test_csc_aborts_and_records_error_without_continue_on_error",
5677        ) {
5678            return;
5679        }
5680        let temp = tempdir().expect("create tempdir");
5681        let src = temp.path().join("src");
5682        let dest = temp.path().join("dest");
5683        let state = temp.path().join("state");
5684        fs::create_dir_all(&src).expect("create src");
5685        fs::create_dir_all(&state).expect("create state");
5686
5687        let unreadable_file = src.join("bad.txt");
5688        fs::write(&unreadable_file, b"cannot read").expect("write bad");
5689        fs::set_permissions(
5690            &unreadable_file,
5691            fs::Permissions::from_mode(0o000),
5692        )
5693        .expect("chmod 000");
5694
5695        let mut args = default_test_args(
5696            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
5697            state.clone(),
5698        );
5699        args.continue_on_error = false;
5700
5701        let res = run_csc(args);
5702        let _ = fs::set_permissions(
5703            &unreadable_file,
5704            fs::Permissions::from_mode(0o644),
5705        );
5706
5707        assert!(
5708            res.is_err(),
5709            "Must abort on unreadable file when continue_on_error is false"
5710        );
5711
5712        let journal_path = crate::journal::find_cscjournal(&state);
5713        let snapshot = crate::journal::read_journal_snapshot(&journal_path)
5714            .expect("read journal snapshot");
5715        assert_eq!(snapshot.errors.len(), 1);
5716        assert_eq!(
5717            snapshot.errors[0].stage,
5718            crate::journal::JournalErrorStage::MetadataRead
5719        );
5720
5721        let desc_path = journal_path.with_extension("cscdesc");
5722        let desc_content = fs::read_to_string(&desc_path).expect("read desc");
5723        assert!(
5724            desc_content.contains("Status: Failed:"),
5725            "desc must record Failed status: {desc_content}"
5726        );
5727        assert!(
5728            desc_content.contains("ErrorsCount: 1"),
5729            "desc must record ErrorsCount: 1"
5730        );
5731    }
5732
5733    #[cfg(target_os = "linux")]
5734    #[crate::ctb_test]
5735    fn test_checksum_read_failure_is_journaled_before_commit() {
5736        for continue_on_error in [false, true] {
5737            let temp = tempdir().unwrap();
5738            let source = PathBuf::from("/proc/self/mem");
5739            let destination = temp.path().join("destination");
5740            let state = temp.path().join("state");
5741            fs::create_dir(&state).unwrap();
5742            let mut args = default_test_args(
5743                vec![source.clone(), destination.clone()],
5744                state.clone(),
5745            );
5746            args.continue_on_error = continue_on_error;
5747            args.allow_unknown_fs = true;
5748            let result = run_csc(args);
5749            assert_eq!(
5750                result.is_ok(),
5751                continue_on_error,
5752                "Unexpected copy error: {:?}",
5753                result.as_ref().err()
5754            );
5755            let snapshot = crate::journal::read_journal_snapshot(
5756                &crate::journal::find_cscjournal(&state),
5757            )
5758            .unwrap();
5759            assert_eq!(snapshot.errors.len(), 1);
5760            assert_eq!(
5761                snapshot.errors[0].stage,
5762                JournalErrorStage::PayloadRead
5763            );
5764            assert_eq!(snapshot.errors[0].path, source);
5765            assert!(
5766                snapshot.errors[0]
5767                    .error_message
5768                    .contains("Failed to checksum source payload")
5769            );
5770            assert!(
5771                snapshot
5772                    .committed_entities
5773                    .values()
5774                    .all(|entity| !entity.is_regular())
5775            );
5776            assert!(!destination.exists());
5777        }
5778    }
5779
5780    #[crate::ctb_test]
5781    fn test_csc_progress_reporting_during_copy_pipeline() {
5782        let temp = tempdir().expect("create tempdir");
5783        let src = temp.path().join("src_prog");
5784        let dest = temp.path().join("dest_prog");
5785        let state = temp.path().join("state_prog");
5786        fs::create_dir_all(&src).expect("create src");
5787        fs::create_dir_all(&state).expect("create state");
5788
5789        // Write a 256KB sample file
5790        fs::write(src.join("sample.bin"), vec![0x42; 256 * 1024])
5791            .expect("write file");
5792
5793        let mut args = default_test_args(
5794            vec![src.join("sample.bin"), dest.join("sample.bin")],
5795            state,
5796        );
5797        args.progress = true;
5798
5799        let res = run_csc(args).expect("run csc");
5800        match res {
5801            ctb_utilities::cli::ToolResult::Immediate {
5802                exit_code,
5803                stdout,
5804                ..
5805            } => {
5806                assert_eq!(exit_code, 0);
5807                let out = String::from_utf8_lossy(&stdout);
5808                assert!(out.contains("Files copied:             1"));
5809                assert!(dest.join("sample.bin").exists());
5810            }
5811            _ => panic!("Expected immediate result"),
5812        }
5813    }
5814
5815    #[crate::ctb_test]
5816    fn test_resume_without_overwrite_using_durable_destination_receipts()
5817    -> Result<()> {
5818        let temp = tempdir()?;
5819        let src = temp.path().join("src_durable");
5820        let dest = temp.path().join("dest_durable");
5821        let state = temp.path().join("state_durable");
5822        let deep_rel = Path::new("a").join("b").join("c");
5823        fs::create_dir_all(src.join(&deep_rel))?;
5824        fs::create_dir_all(&state)?;
5825
5826        // Preexisting regular files in the deep source subtree before the interrupted run starts:
5827        let committed_rel = deep_rel.join("committed.txt");
5828        let uncommitted1_rel = deep_rel.join("uncommitted1.txt");
5829        let uncommitted2_rel = deep_rel.join("uncommitted2.txt");
5830        fs::write(src.join(&committed_rel), b"already committed before crash")?;
5831        fs::write(
5832            src.join(&uncommitted1_rel),
5833            b"preexisting uncommitted file 1",
5834        )?;
5835        fs::write(
5836            src.join(&uncommitted2_rel),
5837            b"preexisting uncommitted file 2",
5838        )?;
5839
5840        // Simulate an interrupted Run 1 crash window:
5841        // Directories "", "a", "a/b", "a/b/c" were created on dest with AppliedDirectoryReceipts,
5842        // and "a/b/c/committed.txt" was materialized and committed to the journal, while
5843        // "a/b/c/uncommitted1.txt" and "a/b/c/uncommitted2.txt" were not yet committed or
5844        // materialized when the crash occurred (journal is NOT marked completed).
5845        let journal_path = state.join("interrupted_deep.cscjournal");
5846        let desc_path = state.join("interrupted_deep.cscdesc");
5847        let src_with_slash = PathBuf::from(format!("{}/", src.display()));
5848        {
5849            let mut journal = StateJournal::create_at_path(
5850                &journal_path,
5851                &desc_path,
5852                std::slice::from_ref(&src_with_slash),
5853                &dest,
5854            )?;
5855            let dest_dir = SandboxableDir::create_or_open(&dest)?;
5856            let root_id =
5857                dest_dir.query_owned_directory_identity(Path::new(""))?;
5858            journal.record_applied_directory(PathBuf::new(), root_id);
5859
5860            let apple_opts = ctb_io::file::AppleReadOptions::default();
5861            for rel_dir in [
5862                PathBuf::new(),
5863                PathBuf::from("a"),
5864                Path::new("a").join("b"),
5865                deep_rel.clone(),
5866            ] {
5867                let dir_src = if rel_dir.as_os_str().is_empty() {
5868                    src.clone()
5869                } else {
5870                    src.join(&rel_dir)
5871                };
5872                let mut dir_entity = CapturedSource::capture(
5873                    &dir_src,
5874                    Some(&src),
5875                    &apple_opts,
5876                    false,
5877                )?
5878                .entity;
5879                dir_entity.identity.relative_path = Some(rel_dir.clone());
5880                let rel_target = if rel_dir.as_os_str().is_empty() {
5881                    Path::new(".")
5882                } else {
5883                    rel_dir.as_path()
5884                };
5885                dest_dir.ensure_dir_all(
5886                    rel_target,
5887                    PathTraversalPolicy::StrictSandboxed,
5888                )?;
5889                let id = dest_dir.query_owned_directory_identity(rel_target)?;
5890                journal.record_applied_directory(rel_dir, id);
5891                journal.record_entity(&dir_entity);
5892            }
5893
5894            let CapturedSource {
5895                entity: mut committed_entity,
5896                snapshot: committed_snap,
5897            } = CapturedSource::capture(
5898                &src.join(&committed_rel),
5899                Some(&src),
5900                &apple_opts,
5901                false,
5902            )?;
5903            committed_entity.identity.relative_path =
5904                Some(committed_rel.clone());
5905            let mut payload =
5906                open_payload(&src.join(&committed_rel), &committed_snap)?;
5907            hash_primary(
5908                &mut committed_entity,
5909                &mut payload,
5910                &src.join(&committed_rel),
5911            )?;
5912            let mat_opts = MaterializeOptions {
5913                existing_entry_policy:
5914                    ctb_io::file::ExistingEntryPolicy::Refuse,
5915                force_overwrite: false,
5916                ..MaterializeOptions::default()
5917            };
5918            let mut write_payload =
5919                open_payload(&src.join(&committed_rel), &committed_snap)?;
5920            materialize_entity(
5921                &committed_entity,
5922                Some(&mut write_payload),
5923                &dest_dir,
5924                &mat_opts,
5925            )?;
5926            record_journal_entry(
5927                &mut journal,
5928                &dest.join(&committed_rel),
5929                &committed_entity,
5930            )?;
5931            journal.commit_batch()?;
5932        }
5933
5934        let snap_before = crate::journal::read_journal_snapshot(&journal_path)?;
5935        assert!(
5936            !snap_before.is_completed,
5937            "Crash-window fixture must be an incomplete journal"
5938        );
5939        assert!(
5940            snap_before
5941                .is_committed(committed_rel.as_os_str().as_encoded_bytes())
5942        );
5943        assert!(
5944            !snap_before
5945                .is_committed(uncommitted1_rel.as_os_str().as_encoded_bytes())
5946        );
5947        assert!(
5948            !snap_before
5949                .is_committed(uncommitted2_rel.as_os_str().as_encoded_bytes())
5950        );
5951        let committed_id_before = ctb_io::file::identity::query_file_identity(
5952            &dest.join(&committed_rel),
5953        )?;
5954
5955        let clean_journal_bytes = fs::read(&journal_path)?;
5956        let clean_desc_bytes = fs::read(&desc_path)?;
5957
5958        // Sub-test 1: If a preexisting uncommitted regular file exists on the destination inside
5959        // the deep subtree (even with a valid AppliedDirectoryReceipt on dest/a/b/c), resume under
5960        // ExistingEntryPolicy::Refuse (overwrite = false) MUST refuse to overwrite or adopt it.
5961        fs::write(
5962            dest.join(&uncommitted1_rel),
5963            b"preexisting on-destination uncommitted payload",
5964        )?;
5965        let mut refuse_args = default_test_args(
5966            vec![src_with_slash.clone(), dest.clone()],
5967            state.clone(),
5968        );
5969        refuse_args.resume = Some(journal_path.clone());
5970        refuse_args.overwrite = false;
5971        assert!(
5972            run_csc(refuse_args).is_err(),
5973            "Resume without --overwrite must refuse preexisting uncommitted regular file in deep destination subtree"
5974        );
5975        assert_eq!(
5976            fs::read(dest.join(&uncommitted1_rel))?,
5977            b"preexisting on-destination uncommitted payload"
5978        );
5979        let snap_after_refuse =
5980            crate::journal::read_journal_snapshot(&journal_path)?;
5981        assert!(
5982            snap_after_refuse
5983                .committed_entities
5984                .get(uncommitted1_rel.as_os_str().as_encoded_bytes())
5985                .is_none_or(|e| !e.metadata.errors.is_empty()),
5986            "Refused preexisting uncommitted destination file must not have an error-free committed record"
5987        );
5988
5989        // Restore the crash-window journal/descriptor and remove the conflicting destination file
5990        // so the uncommitted source files can be materialized on resume without overwrite.
5991        fs::remove_file(dest.join(&uncommitted1_rel))?;
5992        fs::write(&journal_path, &clean_journal_bytes)?;
5993        fs::write(&desc_path, &clean_desc_bytes)?;
5994
5995        // Sub-test 2: Resume WITHOUT --overwrite (ExistingEntryPolicy::Refuse) across the incomplete
5996        // deep subtree: must verify and keep committed.txt (same inode), materialize uncommitted1.txt
5997        // and uncommitted2.txt, apply directory metadata bottom-up, and mark the journal completed.
5998        let mut resume_args = default_test_args(
5999            vec![src_with_slash.clone(), dest.clone()],
6000            state.clone(),
6001        );
6002        resume_args.resume = Some(journal_path.clone());
6003        resume_args.overwrite = false;
6004
6005        let res = run_csc(resume_args)?;
6006        match res {
6007            ctb_utilities::cli::ToolResult::Immediate { exit_code, .. } => {
6008                assert_eq!(exit_code, 0);
6009            }
6010            _ => panic!("Expected immediate result"),
6011        }
6012
6013        assert_eq!(
6014            fs::read(dest.join(&committed_rel))?,
6015            b"already committed before crash"
6016        );
6017        assert_eq!(
6018            ctb_io::file::identity::query_file_identity(
6019                &dest.join(&committed_rel)
6020            )?,
6021            committed_id_before,
6022            "Already-committed regular file must be verified in-place without replacing its inode"
6023        );
6024        assert_eq!(
6025            fs::read(dest.join(&uncommitted1_rel))?,
6026            b"preexisting uncommitted file 1"
6027        );
6028        assert_eq!(
6029            fs::read(dest.join(&uncommitted2_rel))?,
6030            b"preexisting uncommitted file 2"
6031        );
6032        let snap_completed =
6033            crate::journal::read_journal_snapshot(&journal_path)?;
6034        assert!(snap_completed.is_completed);
6035
6036        // Sub-test 3: Tampering test on a deep directory (dest/a/b/c replaced with a different inode)
6037        let tampered_dest = temp.path().join("dest_tampered");
6038        let tampered_state = temp.path().join("state_tampered");
6039        fs::create_dir_all(&tampered_state)?;
6040        let tamper_args = default_test_args(
6041            vec![src_with_slash.clone(), tampered_dest.clone()],
6042            tampered_state.clone(),
6043        );
6044        run_csc(tamper_args)?;
6045        let tampered_journal = find_cscjournal(&tampered_state);
6046
6047        let sub_dir = tampered_dest.join(&deep_rel);
6048        fs::remove_dir_all(&sub_dir)?;
6049        fs::create_dir(&sub_dir)?;
6050        let new_id = ctb_io::file::identity::query_file_identity(&sub_dir)?;
6051
6052        let mut tamper_resume = default_test_args(
6053            vec![src_with_slash, tampered_dest],
6054            tampered_state,
6055        );
6056        tamper_resume.resume = Some(tampered_journal);
6057        tamper_resume.overwrite = false;
6058
6059        let snap = crate::journal::read_journal_snapshot(
6060            &tamper_resume.resume.clone().unwrap(),
6061        )?;
6062        if let Some(expected_id) = snap.applied_directories.get(&deep_rel) {
6063            if *expected_id != new_id {
6064                let err = run_csc(tamper_resume);
6065                assert!(
6066                    err.is_err(),
6067                    "Resume must refuse when deep directory identity receipt does not match"
6068                );
6069            }
6070        }
6071
6072        Ok(())
6073    }
6074
6075    #[crate::ctb_test]
6076    fn test_journal_tracks_materialized_path_for_renamed_entities() -> Result<()>
6077    {
6078        let temp = tempdir()?;
6079        let dest = temp.path().join("dest_renamed");
6080        let state = temp.path().join("state_renamed");
6081        fs::create_dir_all(&dest)?;
6082        fs::create_dir_all(&state)?;
6083
6084        let journal_path = state.join("rename.cscjournal");
6085        let desc_path = state.join("rename.cscdesc");
6086        let mut journal = StateJournal::create_at_path(
6087            &journal_path,
6088            &desc_path,
6089            &[],
6090            &dest,
6091        )?;
6092
6093        let orig_rel =
6094            Path::new("dir").join(format!("{}.txt", "x".repeat(260)));
6095        let (adapted_rel, warnings) =
6096            ctb_io::file::adapt_relative_path_for_materialization(
6097                &orig_rel, true,
6098            );
6099        assert_ne!(orig_rel, adapted_rel);
6100        assert!(!warnings.is_empty());
6101
6102        let mut entity = FileEntity::from_vec(b"renamed content".to_vec());
6103        entity.identity.relative_path = Some(orig_rel.clone());
6104        record_materialization_warnings(&mut journal, &mut entity, warnings)?;
6105
6106        // Simulate pre-materialization record at original path followed by post-materialization record at adapted path.
6107        record_journal_entry(&mut journal, &dest.join(&orig_rel), &entity)?;
6108        journal.commit_batch()?;
6109        record_journal_entry(&mut journal, &dest.join(&adapted_rel), &entity)?;
6110        journal.mark_completed()?;
6111
6112        let snapshot = crate::journal::read_journal_snapshot(&journal_path)?;
6113        // Must answer "where was file foo materialized to" even if materialization logic changes later.
6114        assert_eq!(
6115            snapshot.materialized_path_for(&orig_rel),
6116            Some(adapted_rel.clone())
6117        );
6118        assert_eq!(
6119            snapshot.materialized_path_for(&adapted_rel),
6120            Some(adapted_rel.clone())
6121        );
6122        assert!(snapshot.is_committed(orig_rel.as_os_str().as_encoded_bytes()));
6123        assert!(
6124            snapshot.is_committed(adapted_rel.as_os_str().as_encoded_bytes())
6125        );
6126        assert_eq!(
6127            snapshot.committed_entities.len(),
6128            1,
6129            "Pre-materialization unadapted entry must be superseded by post-materialization entry"
6130        );
6131        assert!(
6132            snapshot
6133                .warnings
6134                .iter()
6135                .any(|w| w.code == "FileMaterializationWarning"
6136                    && w.message.contains("Adapted destination path")),
6137            "Expected FileMaterializationWarning in journal warnings, got: {:?}",
6138            snapshot.warnings
6139        );
6140
6141        Ok(())
6142    }
6143}