ctb_io_csc/
cli.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//! Top-level CLI entry point and orchestration for `csc`.
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;
30use crate::copy_engine::execute_copy_pipeline;
31use crate::journal::{StateJournal, read_journal_snapshot_with_policy};
32use crate::path_resolution::resolve_tasks;
33use crate::verifier::check_cache_flush_privileges;
34use ctb_utilities::cli::ToolResult;
35use std::path::PathBuf;
36use std::time::Instant;
37
38/// Main entry point for the `csc` command called by CLI routing.
39pub fn run_csc(args: CscArgs) -> Result<ToolResult> {
40    let _env_scope = if args.full_provenance {
41        ctb_io_environment::GlobalEnvironmentScope::enter_full()
42    } else {
43        ctb_io_environment::GlobalEnvironmentScope::enter_fresh()
44    };
45    let start_time = Instant::now();
46
47    // 1. Startup root / privilege check and warning
48    check_cache_flush_privileges();
49
50    let home_dir = if let Some(ref custom_dir) = args.state_dir {
51        custom_dir.clone()
52    } else {
53        // Reason for fallback: When neither HOME nor USERPROFILE is set, fall back to the system temporary directory to avoid writing state journals into the working directory.
54        std::env::var("HOME")
55            .or_else(|_| std::env::var("USERPROFILE"))
56            .map_or_else(|_| std::env::temp_dir(), PathBuf::from)
57    };
58
59    let progress = Progress::new(args.should_show_progress());
60
61    let (tasks, mut journal) = if let Some(ref resume_path) = args.resume {
62        // Resume mode: recover state from journal
63        let journal_path = if resume_path.extension().and_then(|e| e.to_str())
64            == Some("cscdesc")
65        {
66            resume_path.with_extension("cscjournal")
67        } else {
68            resume_path.clone()
69        };
70
71        let desc_path = journal_path.with_extension("cscdesc");
72
73        progress.message(&format!(
74            "Resuming session from journal: {}",
75            journal_path.display()
76        ));
77
78        let snap = read_journal_snapshot_with_policy(
79            &journal_path,
80            &args.journal_projection_policy(),
81        )?;
82        if snap.is_completed {
83            progress.message("Session was completed; revalidating source and destination entries.");
84        }
85
86        let mut all_paths = snap.sources.clone();
87        all_paths.push(snap.destination.clone());
88        let (mut resolved, _) = resolve_tasks(&all_paths)?;
89        for task in &mut resolved {
90            if !std::fs::symlink_metadata(&task.source_root)?.is_dir() {
91                continue;
92            }
93            let source_entity =
94                ctb_io::file::FileEntity::from_filesystem_metadata_only(
95                    &task.source_root,
96                    None,
97                )?;
98            let recorded_root = snap.committed_entities.values().find(|entity| {
99                entity.is_dir() && matches!((&entity.identity.origin, &source_entity.identity.origin),
100                    (ctb_io::file::FileOrigin::Filesystem { key, .. },
101                     ctb_io::file::FileOrigin::Filesystem { key: source_key, .. })
102                    if key == source_key)
103            });
104            if let Some(entity) = recorded_root {
105                task.target_root = match &entity.identity.relative_path {
106                    Some(rel) => snap.destination.join(rel),
107                    None => snap.destination.clone(),
108                };
109            } else {
110                anyhow::ensure!(
111                    task.copy_contents_only || !snap.destination.exists(),
112                    "Cannot safely recover the original directory destination from this journal"
113                );
114            }
115        }
116        crate::path_resolution::validate_task_overlap(&resolved)?;
117
118        let jw =
119            StateJournal::open_for_resume(&journal_path, &desc_path, &snap)?;
120        (resolved, jw)
121    } else {
122        // New run: resolve tasks from command-line arguments
123        anyhow::ensure!(
124            args.paths.len() >= 2,
125            "Must provide at least one source and one destination path (or pass --resume)"
126        );
127
128        let (resolved, dest_path) = resolve_tasks(&args.paths)?;
129        let sources: Vec<PathBuf> =
130            resolved.iter().map(|t| t.source_root.clone()).collect();
131
132        let jw = if let Some(ref custom_jp) = args.journal_path {
133            let journal_path = if custom_jp.extension().and_then(|e| e.to_str())
134                == Some("cscdesc")
135            {
136                custom_jp.with_extension("cscjournal")
137            } else if custom_jp.extension().and_then(|e| e.to_str())
138                == Some("cscjournal")
139            {
140                custom_jp.clone()
141            } else {
142                custom_jp.with_extension("cscjournal")
143            };
144            let desc_path = journal_path.with_extension("cscdesc");
145            anyhow::ensure!(
146                !journal_path.exists() && !desc_path.exists(),
147                "Journal file already exists at {}: will not overwrite existing file (pass --resume to resume an interrupted run)",
148                journal_path.display()
149            );
150            StateJournal::create_at_path(
151                &journal_path,
152                &desc_path,
153                &sources,
154                &dest_path,
155            )?
156        } else {
157            StateJournal::create_new(&home_dir, &sources, &dest_path)?
158        };
159        progress.message(&format!(
160            "State journal: {}",
161            jw.journal_path().display()
162        ));
163        (resolved, jw)
164    };
165
166    // 2. Execute pipeline
167    let stats = match execute_copy_pipeline(
168        &tasks,
169        &args,
170        &mut journal,
171        &progress,
172    ) {
173        Ok(s) => s,
174        Err(err) => {
175            if let Err(record_error) = journal.mark_failed(&format!("{err:#}"))
176            {
177                return Err(err).context(format!(
178                    "Recording copy failure in {} also failed: {record_error:#}",
179                    journal.journal_path().display()
180                ));
181            }
182            return Err(err);
183        }
184    };
185
186    let journal_path = journal.journal_path().to_path_buf();
187    let desc_path = journal.desc_path().to_path_buf();
188    let error_count = journal.errors().len();
189    let warning_count = journal.warnings().len();
190    let errors = journal.errors().to_vec();
191    let warnings = journal.warnings().to_vec();
192    drop(journal);
193
194    let has_errors = error_count > 0 || stats.files_failed > 0;
195    let retain_metadata_journal = warning_count > 0
196        || stats.copied_entities.iter().any(|(_, _, entity)| {
197            crate::journal::entity_requires_metadata_retention(entity)
198        });
199    if args.delete_manifest_after && has_errors {
200        warn_fmt!(
201            "Retaining {}: it contains recorded error records",
202            journal_path.display()
203        );
204    } else if args.delete_manifest_after && retain_metadata_journal {
205        warn_fmt!(
206            "Retaining {}: it contains original metadata that is not guaranteed to be reproducible",
207            journal_path.display()
208        );
209    } else if args.delete_manifest_after {
210        if journal_path.exists() {
211            std::fs::remove_file(&journal_path).with_context(|| {
212                format!("Failed to remove journal {}", journal_path.display())
213            })?;
214        }
215        if desc_path.exists() {
216            std::fs::remove_file(&desc_path).with_context(|| {
217                format!(
218                    "Failed to remove journal description {}",
219                    desc_path.display()
220                )
221            })?;
222        }
223    }
224
225    let elapsed = start_time.elapsed().as_secs_f64();
226
227    // 3. Format result summary
228    let mut summary = String::new();
229    use std::fmt::Write;
230    writeln!(summary, "--- CSC Summary ---")?;
231    if retain_metadata_journal || has_errors {
232        writeln!(
233            summary,
234            "Original metadata journal: {}",
235            journal_path.display()
236        )?;
237    }
238    writeln!(summary, "Files copied:             {}", stats.files_copied)?;
239    if stats.files_failed > 0 || !errors.is_empty() {
240        writeln!(summary, "Files failed (skipped):   {}", stats.files_failed)?;
241        writeln!(summary, "Errors recorded:          {error_count}")?;
242        if args.continue_on_error {
243            writeln!(summary, "\n--- Continue-on-Error Diagnostics ---")?;
244            for err in &errors {
245                writeln!(
246                    summary,
247                    "  [Error] {:?} on {}: {}",
248                    err.stage,
249                    err.path.display(),
250                    err.error_message
251                )?;
252            }
253        }
254    }
255    if stats.files_skipped_identical > 0 {
256        writeln!(
257            summary,
258            "Files skipped (identical): {}",
259            stats.files_skipped_identical
260        )?;
261    }
262    writeln!(summary, "Bytes transferred:        {}", stats.bytes_copied)?;
263    writeln!(summary, "Directories created:      {}", stats.dirs_created)?;
264    writeln!(
265        summary,
266        "Symlinks created:         {}",
267        stats.symlinks_created
268    )?;
269    writeln!(
270        summary,
271        "Hardlinks created:        {}",
272        stats.hardlinks_created
273    )?;
274    if stats.special_files_created > 0 {
275        writeln!(
276            summary,
277            "Special nodes created:    {}",
278            stats.special_files_created
279        )?;
280    }
281    if stats.special_files_skipped > 0 {
282        writeln!(
283            summary,
284            "Special files skipped:    {}",
285            stats.special_files_skipped
286        )?;
287        writeln!(
288            summary,
289            "WARNING: {} special file(s) were skipped. Pass --copy-specials-as-specials to preserve them as device nodes, or --copy-block-devices-as-regular-files / --copy-fifos-as-regular-files to copy block devices or FIFOs as regular files.",
290            stats.special_files_skipped
291        )?;
292    }
293    if warning_count > 0 {
294        writeln!(summary, "Warnings recorded:        {warning_count}")?;
295        for warning in &warnings {
296            writeln!(
297                summary,
298                "  [Warning] {}: {}",
299                warning.code, warning.message
300            )?;
301        }
302    }
303    if args.should_verify_after() {
304        writeln!(
305            summary,
306            "Files verified:           {}",
307            stats.files_verified
308        )?;
309    }
310    writeln!(summary, "Duration:                 {elapsed:.2}s")?;
311    if has_errors {
312        writeln!(
313            summary,
314            "Status:                   Completed with {error_count} error record(s) and {} failed file(s).",
315            stats.files_failed
316        )?;
317    } else if warning_count > 0 {
318        writeln!(
319            summary,
320            "Status:                   Completed with {warning_count} warning record(s); fidelity limitations are retained in the journal."
321        )?;
322    } else {
323        writeln!(
324            summary,
325            "Status:                   All operations verified successfully."
326        )?;
327    }
328
329    if has_errors {
330        Ok(ToolResult::Immediate {
331            stdout: summary.into_bytes(),
332            stderr: Vec::new(),
333            exit_code: 1,
334        })
335    } else {
336        Ok(ToolResult::immediate_ok(summary.into_bytes()))
337    }
338}
339#[cfg(test)]
340#[allow(
341    clippy::panic,
342    clippy::expect_used,
343    clippy::unwrap_used,
344    clippy::unwrap_in_result,
345    clippy::panic_in_result_fn,
346    clippy::indexing_slicing,
347    clippy::arithmetic_side_effects,
348    reason = "Standard repository test boilerplate"
349)]
350mod tests {
351    use super::*;
352    use crate::args::default_test_args;
353    use crate::cli::run_csc;
354    use crate::journal::find_cscjournal;
355    use ctb_utilities::cli::ToolResult;
356    use std::fs;
357    use std::path::PathBuf;
358    use tempfile::tempdir;
359
360    #[crate::ctb_test]
361    fn test_multiple_sources_to_dest_dir() {
362        let temp = tempdir().expect("create tempdir");
363        let src1 = temp.path().join("src1");
364        let src2 = temp.path().join("src2");
365        let dest = temp.path().join("dest_multi");
366        let state = temp.path().join("state_dir");
367        fs::create_dir_all(&src1).expect("create src1");
368        fs::create_dir_all(&src2).expect("create src2");
369        fs::create_dir_all(&state).expect("create state");
370
371        fs::write(src1.join("a.txt"), b"Content A").expect("write a");
372        fs::write(src2.join("b.txt"), b"Content B").expect("write b");
373
374        let args = default_test_args(
375            vec![src1.clone(), src2.clone(), dest.clone()],
376            state,
377        );
378
379        run_csc(args).expect("run csc multiple sources");
380
381        assert_eq!(
382            fs::read(dest.join("src1").join("a.txt")).expect("read a"),
383            b"Content A"
384        );
385        assert_eq!(
386            fs::read(dest.join("src2").join("b.txt")).expect("read b"),
387            b"Content B"
388        );
389    }
390
391    #[crate::ctb_test]
392    fn test_copy_single_file_to_directory() {
393        let temp = tempdir().expect("create tempdir");
394        let src_file = temp.path().join(".face");
395        let dest_dir = temp.path().join("dest_dir");
396        let state = temp.path().join("state_dir");
397        fs::create_dir_all(&dest_dir).expect("create dest");
398        fs::create_dir_all(&state).expect("create state");
399
400        fs::write(&src_file, b"face icon bytes").expect("write face");
401
402        // Test case 1: dest with trailing slash (e.g. csc ~/.face ./)
403        let dest_with_slash = PathBuf::from(format!("{}/", dest_dir.display()));
404        let args = default_test_args(
405            vec![src_file.clone(), dest_with_slash],
406            state.clone(),
407        );
408
409        run_csc(args).expect("run csc single file with trailing slash");
410        assert_eq!(
411            fs::read(dest_dir.join(".face")).expect("read copied file"),
412            b"face icon bytes"
413        );
414
415        // Test case 2: dest without trailing slash (e.g. csc ~/.face .)
416        let dest_dir2 = temp.path().join("dest_dir2");
417        let state2 = temp.path().join("state_dir2");
418        fs::create_dir_all(&dest_dir2).expect("create dest2");
419        fs::create_dir_all(&state2).expect("create state2");
420
421        let args2 = default_test_args(
422            vec![src_file.clone(), dest_dir2.clone()],
423            state2,
424        );
425        run_csc(args2)
426            .expect("run csc single file to directory without trailing slash");
427        assert_eq!(
428            fs::read(dest_dir2.join(".face")).expect("read copied file 2"),
429            b"face icon bytes"
430        );
431
432        // Test case 3: direct file rename (e.g. csc ~/.face renamed.face)
433        let renamed_file = temp.path().join("renamed.face");
434        let state3 = temp.path().join("state_dir3");
435        fs::create_dir_all(&state3).expect("create state3");
436
437        let args3 = default_test_args(
438            vec![src_file.clone(), renamed_file.clone()],
439            state3,
440        );
441        run_csc(args3).expect("run csc single file rename");
442        assert_eq!(
443            fs::read(&renamed_file).expect("read renamed file"),
444            b"face icon bytes"
445        );
446    }
447
448    #[crate::ctb_test]
449    fn test_csc_configurable_journal_path() {
450        let temp = tempdir().expect("create tempdir");
451        let src = temp.path().join("src");
452        let dest = temp.path().join("dest");
453        let state = temp.path().join("state");
454        fs::create_dir_all(&src).expect("create src");
455        fs::create_dir_all(&state).expect("create state");
456        fs::write(src.join("test.txt"), b"Configurable journal test")
457            .expect("write test.txt");
458
459        let custom_journal = state.join("my_backup.cscjournal");
460        let custom_desc = state.join("my_backup.cscdesc");
461
462        let mut args =
463            default_test_args(vec![src.clone(), dest.clone()], state.clone());
464        args.journal_path = Some(custom_journal.clone());
465
466        let res =
467            run_csc(args.clone()).expect("run csc with explicit journal path");
468        match res {
469            ToolResult::Immediate { exit_code, .. } => assert_eq!(exit_code, 0),
470            _ => panic!("Expected immediate tool result"),
471        }
472
473        assert!(
474            custom_journal.exists(),
475            "Explicit .cscjournal must be created"
476        );
477        assert!(custom_desc.exists(), "Explicit .cscdesc must be created");
478        assert!(
479            dest.join("test.txt").exists(),
480            "Destination file must exist"
481        );
482
483        // Attempting to run again with the same journal path without --resume must fail
484        let err = match run_csc(args) {
485            Err(e) => e,
486            Ok(_) => panic!("Expected error when journal already exists"),
487        };
488        let err_msg = err.to_string();
489        assert!(
490            err_msg.contains("already exists"),
491            "Must reject overwriting existing journal file: {err_msg}"
492        );
493    }
494
495    #[cfg(target_os = "linux")]
496    #[crate::ctb_test]
497    fn test_csc_delete_manifest_after() {
498        let temp = tempdir().expect("create tempdir");
499        let src = temp.path().join("src_del_manifest");
500        let dest = temp.path().join("dest_del_manifest");
501        let state = temp.path().join("state_del_manifest");
502        fs::create_dir_all(&src).expect("create src");
503        fs::create_dir_all(&state).expect("create state dir");
504
505        fs::write(
506            src.join("test.txt"),
507            b"Manifest should be deleted after copy",
508        )
509        .expect("write file");
510
511        let mut args = default_test_args(
512            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
513            state.clone(),
514        );
515        args.delete_manifest_after = true;
516
517        let res = run_csc(args).expect("run csc with delete_manifest_after");
518        match res {
519            ToolResult::Immediate { stdout, .. } => {
520                let out = String::from_utf8_lossy(&stdout);
521                assert!(out.contains("Files copied:             1"));
522            }
523            _ => panic!("Expected Immediate ToolResult"),
524        }
525
526        assert!(dest.join("test.txt").exists());
527
528        let journal = find_cscjournal(&state);
529        let snapshot = crate::journal::read_journal_snapshot(&journal).unwrap();
530        assert!(
531            snapshot
532                .committed_entities
533                .values()
534                .any(|entity| entity.metadata.native.is_some())
535        );
536        assert!(journal.with_extension("cscdesc").exists());
537    }
538
539    #[crate::ctb_test]
540    fn test_csc_cli_summary_diagnostics() {
541        let temp = tempdir().expect("create tempdir");
542        let src = temp.path().join("src_diag");
543        let dest = temp.path().join("dest_diag");
544        let state = temp.path().join("state_diag");
545        fs::create_dir_all(&src).expect("create src");
546        fs::create_dir_all(&state).expect("create state dir");
547
548        fs::write(src.join("test.txt"), b"Hello diagnostics")
549            .expect("write test.txt");
550
551        let mut args = default_test_args(
552            vec![PathBuf::from(format!("{}/", src.display())), dest.clone()],
553            state.clone(),
554        );
555        args.continue_on_error = true;
556
557        let res = run_csc(args).expect("run csc with continue_on_error");
558        match res {
559            ToolResult::Immediate {
560                stdout, exit_code, ..
561            } => {
562                assert_eq!(exit_code, 0);
563                let out = String::from_utf8_lossy(&stdout);
564                assert!(out.contains("--- CSC Summary ---"));
565                assert!(out.contains("Files copied:             1"));
566                let journal_path = find_cscjournal(&state);
567                let snapshot =
568                    crate::journal::read_journal_snapshot(&journal_path)
569                        .unwrap();
570                if snapshot.warnings.is_empty() {
571                    assert!(
572                        out.contains("All operations verified successfully.")
573                    );
574                } else {
575                    assert!(out.contains(
576                        "fidelity limitations are retained in the journal"
577                    ));
578                }
579            }
580            _ => panic!("Expected Immediate ToolResult"),
581        }
582
583        let source_file = src.join("test.txt");
584        let resumed_dest = temp.path().join("resumed.txt");
585        let journal_path = state.join("diagnostics.cscjournal");
586        let desc_path = journal_path.with_extension("cscdesc");
587        let mut journal = StateJournal::create_at_path(
588            &journal_path,
589            &desc_path,
590            &[source_file.clone()],
591            &resumed_dest,
592        )
593        .unwrap();
594        let message = "Destination filesystem does not support sparse files for resumed.txt";
595        journal
596            .record_warning("FileMaterializationWarning", message)
597            .unwrap();
598        for error_message in ["First recorded issue", "Second recorded issue"] {
599            journal
600                .record_error(&crate::journal::JournalErrorRecord {
601                    path: source_file.clone(),
602                    raw_path: source_file
603                        .as_os_str()
604                        .as_encoded_bytes()
605                        .to_vec(),
606                    stage: crate::journal::JournalErrorStage::MetadataRead,
607                    error_message: error_message.to_owned(),
608                    os_error: None,
609                    timestamp_sec: 0,
610                })
611                .unwrap();
612        }
613        drop(journal);
614        let mut resume_args = default_test_args(Vec::new(), state);
615        resume_args.resume = Some(journal_path.clone());
616        resume_args.continue_on_error = true;
617        resume_args.delete_manifest_after = true;
618        match run_csc(resume_args).unwrap() {
619            ToolResult::Immediate {
620                stdout, exit_code, ..
621            } => {
622                assert_ne!(exit_code, 0);
623                let out = String::from_utf8(stdout).unwrap();
624                assert!(out.contains(&format!(
625                    "[Warning] FileMaterializationWarning: {message}"
626                )));
627                assert!(!out.contains("WINE sparse limitations"));
628                assert!(out.contains("Files failed (skipped):   0"));
629                assert!(out.contains("Errors recorded:          2"));
630                assert!(!out.contains("All operations verified successfully."));
631            }
632            _ => panic!("Expected Immediate ToolResult"),
633        }
634        assert!(journal_path.exists());
635        assert!(desc_path.exists());
636    }
637}