proj-janitor 0.7.21

Scan, back up, restore, prune, and clean old projects safely
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
use clap::{Parser, Subcommand};
use globset::{GlobBuilder, GlobMatcher};
use serde::{Deserialize, Serialize};
use std::{
    collections::HashSet,
    env, fs,
    path::{Component, Path, PathBuf},
    sync::OnceLock,
};
mod archive;
mod backup;
mod clean;
mod config;
mod crypto;
mod project;
mod restore;
mod retention;
mod secrets;
use backup::backup_cmd;
use clean::clean_cmd;
use config::{discover_config, resolve_check_remote, resolve_tri_state};
use project::discover;
use restore::restore_cmd;

pub(crate) const RULES: &[(&str, &[&str])] = &[
    (
        "python-cache",
        &[
            "__pycache__",
            ".pytest_cache",
            ".mypy_cache",
            ".ruff_cache",
            "*.pyc",
            ".coverage",
            "htmlcov",
        ],
    ),
    (
        "python-env",
        &[".venv", "venv", ".tox", ".nox", "*.egg-info"],
    ),
    (
        "node",
        &[
            "node_modules",
            ".next",
            ".nuxt",
            ".svelte-kit",
            ".turbo",
            ".parcel-cache",
            "coverage",
        ],
    ),
    (
        "build",
        &[
            "build",
            "dist",
            "dist-standalone",
            "out",
            "target",
            "CMakeFiles",
            ".gradle",
        ],
    ),
    ("editor", &[".cache", ".DS_Store", "Thumbs.db"]),
];

static ARTIFACT_GLOBS: OnceLock<Vec<GlobMatcher>> = OnceLock::new();

#[derive(Parser)]
#[command(
    name = "projjan",
    version,
    about = "Scan, back up, restore, prune, and clean old projects safely"
)]
struct Cli {
    #[command(subcommand)]
    command: Action,
}

#[derive(Subcommand)]
enum Action {
    Scan {
        #[arg(required = true)]
        roots: Vec<PathBuf>,
        #[arg(long)]
        all: bool,
        #[arg(long)]
        json: bool,
    },
    Backup {
        #[arg(required = true)]
        roots: Vec<PathBuf>,
        #[arg(long, env = "BACKUP_DEST", hide_env_values = true)]
        backup_dest: Option<PathBuf>,
        #[arg(long)]
        config: Option<PathBuf>,
        #[arg(long, value_parser = parse_positive_usize)]
        keep: Option<usize>,
        #[arg(long)]
        yes: bool,
        #[arg(long)]
        dry_run: bool,
        #[arg(long)]
        include_artifacts: bool,
        #[arg(long)]
        always_archive: bool,
        #[arg(long)]
        exclude_git_metadata: bool,
        #[arg(long)]
        incremental: bool,
        #[arg(long, conflicts_with = "no_fail_on_secrets")]
        fail_on_secrets: bool,
        #[arg(long = "no-fail-on-secrets", conflicts_with = "fail_on_secrets")]
        no_fail_on_secrets: bool,
        #[arg(long, conflicts_with = "no_exclude_secrets")]
        exclude_secrets: bool,
        #[arg(long = "no-exclude-secrets", conflicts_with = "exclude_secrets")]
        no_exclude_secrets: bool,
        #[arg(long, conflicts_with = "no_progress")]
        progress: bool,
        #[arg(long = "no-progress", conflicts_with = "progress")]
        no_progress: bool,
        #[arg(long, conflicts_with = "no_check_space")]
        check_space: bool,
        #[arg(long = "no-check-space", conflicts_with = "check_space")]
        no_check_space: bool,
        #[arg(long, conflicts_with = "no_fail_on_insecure_dest")]
        fail_on_insecure_dest: bool,
        #[arg(
            long = "no-fail-on-insecure-dest",
            conflicts_with = "fail_on_insecure_dest"
        )]
        no_fail_on_insecure_dest: bool,
        #[arg(long, value_name = "FILE")]
        encrypt_passphrase_file: Option<PathBuf>,
        #[arg(long, conflicts_with = "encrypt_passphrase_file")]
        no_encrypt: bool,
    },
    Clean {
        roots: Vec<PathBuf>,
        #[arg(long, value_delimiter = ',')]
        rules: Vec<String>,
        #[arg(long)]
        apply: bool,
        #[arg(long)]
        yes: bool,
        #[arg(long)]
        json: bool,
        #[arg(long)]
        list_rules: bool,
    },
    Prune {
        backup_root: PathBuf,
        #[arg(long, value_parser = parse_positive_usize)]
        keep: Option<usize>,
        #[arg(long)]
        config: Option<PathBuf>,
        #[arg(long)]
        apply: bool,
        #[arg(long)]
        yes: bool,
        #[arg(long)]
        json: bool,
    },
    Restore {
        manifest: PathBuf,
        #[arg(long)]
        dest: Option<PathBuf>,
        #[arg(long = "project")]
        projects: Vec<String>,
        #[arg(long)]
        dry_run: bool,
        #[arg(long)]
        no_verify: bool,
        #[arg(long)]
        yes: bool,
        #[arg(long, conflicts_with = "no_check_remote")]
        check_remote: bool,
        #[arg(long = "no-check-remote", conflicts_with = "check_remote")]
        no_check_remote: bool,
        #[arg(long, conflicts_with = "no_require_dest")]
        require_dest: bool,
        #[arg(long = "no-require-dest", conflicts_with = "require_dest")]
        no_require_dest: bool,
        #[arg(long, conflicts_with = "no_force")]
        force: bool,
        #[arg(long = "no-force", conflicts_with = "force")]
        no_force: bool,
        #[arg(long, conflicts_with = "no_continue_on_error")]
        continue_on_error: bool,
        #[arg(long = "no-continue-on-error", conflicts_with = "continue_on_error")]
        no_continue_on_error: bool,
        #[arg(long, conflicts_with = "no_skip_existing")]
        skip_existing: bool,
        #[arg(long = "no-skip-existing", conflicts_with = "skip_existing")]
        no_skip_existing: bool,
        #[arg(long, conflicts_with = "no_progress")]
        progress: bool,
        #[arg(long = "no-progress", conflicts_with = "progress")]
        no_progress: bool,
        #[arg(long, value_name = "FILE")]
        decrypt_passphrase_file: Option<PathBuf>,
        #[arg(long)]
        config: Option<PathBuf>,
        #[arg(long)]
        json: bool,
    },
    Verify {
        manifest: PathBuf,
        #[arg(long = "project")]
        projects: Vec<String>,
        #[arg(long, conflicts_with = "no_check_remote")]
        check_remote: bool,
        #[arg(long = "no-check-remote", conflicts_with = "check_remote")]
        no_check_remote: bool,
        #[arg(long)]
        config: Option<PathBuf>,
        #[arg(long)]
        json: bool,
    },
}

fn parse_positive_usize(value: &str) -> Result<usize, String> {
    let keep = value
        .parse::<usize>()
        .map_err(|_| "must be a positive integer".to_owned())?;
    if keep == 0 {
        return Err("must be at least 1".into());
    }
    Ok(keep)
}

#[derive(Serialize, Deserialize)]
pub(crate) struct Manifest {
    pub(crate) schema_version: u32,
    pub(crate) created_at: String,
    pub(crate) tool: String,
    pub(crate) version: String,
    pub(crate) include_artifacts: bool,
    pub(crate) always_archive: bool,
    #[serde(default)]
    pub(crate) exclude_git_metadata: bool,
    pub(crate) records: Vec<Record>,
}
#[derive(Serialize, Deserialize, Clone)]
pub(crate) struct Record {
    pub(crate) project: String,
    pub(crate) source: String,
    pub(crate) archive: Option<String>,
    pub(crate) archive_bytes: u64,
    pub(crate) source_bytes: u64,
    pub(crate) sha256: Option<String>,
    pub(crate) strategy: String,
    pub(crate) remote: Option<String>,
    pub(crate) remote_url: Option<String>,
    pub(crate) branch: Option<String>,
    pub(crate) commit: Option<String>,
    pub(crate) upstream: Option<String>,
    pub(crate) verified: Option<String>,
    pub(crate) fallback_reason: Option<String>,
    /// Full file inventory (path -> sha256/size) for archive snapshots.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) inventory: Option<Vec<FileEntry>>,
    /// Present only for incremental (delta) archive snapshots.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) incremental: Option<IncrementalInfo>,
    /// Submodule URL -> pinned commit map for git-strategy records.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) submodules: Option<Vec<SubmoduleInfo>>,
    /// Git LFS pointer objects for git-strategy records (`oid` + `size`).
    /// Legacy manifests may store bare OID strings; those remain readable.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) lfs_objects: Option<Vec<LfsObjectRef>>,
    /// Optional archive encryption scheme (e.g. openssl-aes-256-cbc-pbkdf2).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) encryption: Option<String>,
}

/// One LFS object recorded at backup time. New backups always write
/// `{oid, size}`; older manifests may still contain a bare OID string.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
#[serde(untagged)]
pub(crate) enum LfsObjectRef {
    /// Legacy CR-094 form: OID only (availability probe needs a re-backup).
    Oid(String),
    /// Current form: OID plus exact byte size from the LFS pointer blob.
    Object { oid: String, size: u64 },
}

impl LfsObjectRef {
    pub(crate) fn oid(&self) -> &str {
        match self {
            Self::Oid(oid) | Self::Object { oid, .. } => oid,
        }
    }

    pub(crate) fn size(&self) -> Option<u64> {
        match self {
            Self::Oid(_) => None,
            Self::Object { size, .. } => Some(*size),
        }
    }
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub(crate) struct SubmoduleInfo {
    /// Submodule path relative to the project root, using `/` separators.
    pub(crate) path: String,
    pub(crate) url: String,
    /// Pinned gitlink commit recorded in the parent tree.
    pub(crate) commit: String,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub(crate) struct FileEntry {
    /// Path relative to the project root, using `/` separators.
    pub(crate) path: String,
    pub(crate) sha256: String,
    pub(crate) size: u64,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub(crate) struct IncrementalInfo {
    /// Filename of the previous snapshot manifest this delta is based on.
    pub(crate) base: String,
    /// Paths (relative to the project root) removed since the base snapshot.
    pub(crate) deleted: Vec<String>,
}

fn main() {
    #[cfg(windows)]
    let result = match std::thread::Builder::new()
        .stack_size(8 * 1024 * 1024)
        .spawn(run)
    {
        Ok(worker) => worker
            .join()
            .unwrap_or_else(|_| Err(anyhow::anyhow!("command thread panicked"))),
        Err(error) => Err(error.into()),
    };
    #[cfg(not(windows))]
    let result = run();
    if let Err(e) = result {
        if let Some(interrupted) = e.downcast_ref::<restore::RestoreInterrupted>() {
            std::process::exit(128 + interrupted.0);
        }
        eprintln!("error: {e}");
        std::process::exit(1);
    }
}
fn run() -> anyhow::Result<()> {
    match Cli::parse().command {
        Action::Scan { roots, all, json } => scan_cmd(&roots, all, json),
        Action::Backup {
            roots,
            backup_dest,
            config,
            keep,
            yes,
            dry_run,
            include_artifacts,
            always_archive,
            exclude_git_metadata,
            incremental,
            fail_on_secrets,
            no_fail_on_secrets,
            exclude_secrets,
            no_exclude_secrets,
            progress,
            no_progress,
            check_space,
            no_check_space,
            fail_on_insecure_dest,
            no_fail_on_insecure_dest,
            encrypt_passphrase_file,
            no_encrypt,
        } => {
            let config = discover_config(config.as_deref())?;
            let backup_dest = backup_dest
                .filter(|path| !path.as_os_str().is_empty())
                .or_else(|| config.as_ref().and_then(|cfg| cfg.backup.dest.clone()));
            let keep = keep.or_else(|| config.as_ref().and_then(|cfg| cfg.backup.keep));
            let exclude = config
                .as_ref()
                .map(|cfg| cfg.backup.exclude.clone())
                .unwrap_or_default();
            let incremental = incremental
                || config
                    .as_ref()
                    .map(|cfg| cfg.backup.incremental)
                    .unwrap_or(false);
            let fail_on_secrets = resolve_tri_state(
                fail_on_secrets,
                no_fail_on_secrets,
                config
                    .as_ref()
                    .map(|cfg| cfg.backup.fail_on_secrets)
                    .unwrap_or(false),
            );
            let exclude_secrets = resolve_tri_state(
                exclude_secrets,
                no_exclude_secrets,
                config
                    .as_ref()
                    .map(|cfg| cfg.backup.exclude_secrets)
                    .unwrap_or(false),
            );
            let progress = resolve_tri_state(
                progress,
                no_progress,
                config
                    .as_ref()
                    .map(|cfg| cfg.backup.progress)
                    .unwrap_or(false),
            );
            let check_space = resolve_tri_state(
                check_space,
                no_check_space,
                config
                    .as_ref()
                    .map(|cfg| cfg.backup.check_space)
                    .unwrap_or(false),
            );
            let fail_on_insecure_dest = resolve_tri_state(
                fail_on_insecure_dest,
                no_fail_on_insecure_dest,
                config
                    .as_ref()
                    .map(|cfg| cfg.backup.fail_on_insecure_dest)
                    .unwrap_or(false),
            );
            let encrypt_passphrase_file = if no_encrypt {
                None
            } else {
                encrypt_passphrase_file.or_else(|| {
                    config
                        .as_ref()
                        .and_then(|cfg| cfg.backup.encrypt_passphrase_file.clone())
                })
            };
            backup_cmd(
                &roots,
                backup_dest,
                keep,
                yes,
                dry_run,
                include_artifacts,
                always_archive,
                exclude_git_metadata,
                &exclude,
                incremental,
                fail_on_secrets,
                exclude_secrets,
                progress,
                check_space,
                fail_on_insecure_dest,
                encrypt_passphrase_file,
            )
        }
        Action::Clean {
            roots,
            rules,
            apply,
            yes,
            json,
            list_rules,
        } => clean_cmd(&roots, &rules, apply, yes, json, list_rules),
        Action::Prune {
            backup_root,
            keep,
            config,
            apply,
            yes,
            json,
        } => {
            let config = discover_config(config.as_deref())?;
            let keep = keep.or_else(|| config.as_ref().and_then(|cfg| cfg.prune.keep));
            retention::prune_cmd(
                &backup_root,
                keep.ok_or_else(|| anyhow::anyhow!("set --keep or configure [prune].keep"))?,
                apply,
                yes,
                json,
            )
        }
        Action::Restore {
            manifest,
            dest,
            projects,
            dry_run,
            no_verify,
            yes,
            check_remote,
            no_check_remote,
            require_dest,
            no_require_dest,
            force,
            no_force,
            continue_on_error,
            no_continue_on_error,
            skip_existing,
            no_skip_existing,
            progress,
            no_progress,
            decrypt_passphrase_file,
            config,
            json,
        } => {
            let config = discover_config(config.as_deref())?;
            let check_remote = resolve_check_remote(
                check_remote,
                no_check_remote,
                config
                    .as_ref()
                    .map(|cfg| cfg.restore.check_remote)
                    .unwrap_or(false),
            );
            let require_dest = resolve_tri_state(
                require_dest,
                no_require_dest,
                config
                    .as_ref()
                    .map(|cfg| cfg.restore.require_dest)
                    .unwrap_or(false),
            );
            let force = resolve_tri_state(
                force,
                no_force,
                config
                    .as_ref()
                    .map(|cfg| cfg.restore.force)
                    .unwrap_or(false),
            );
            let continue_on_error = resolve_tri_state(
                continue_on_error,
                no_continue_on_error,
                config
                    .as_ref()
                    .map(|cfg| cfg.restore.continue_on_error)
                    .unwrap_or(false),
            );
            let skip_existing = resolve_tri_state(
                skip_existing,
                no_skip_existing,
                config
                    .as_ref()
                    .map(|cfg| cfg.restore.skip_existing)
                    .unwrap_or(false),
            );
            let progress = resolve_tri_state(
                progress,
                no_progress,
                config
                    .as_ref()
                    .map(|cfg| cfg.restore.progress)
                    .unwrap_or(false),
            );
            anyhow::ensure!(
                !(force && skip_existing),
                "--force and --skip-existing cannot be combined"
            );
            let decrypt_passphrase_file = decrypt_passphrase_file.or_else(|| {
                config
                    .as_ref()
                    .and_then(|cfg| cfg.restore.decrypt_passphrase_file.clone())
            });
            restore_cmd(
                &manifest,
                dest,
                &projects,
                dry_run,
                no_verify,
                yes,
                check_remote,
                require_dest,
                force,
                continue_on_error,
                skip_existing,
                progress,
                decrypt_passphrase_file,
                json,
            )
        }
        Action::Verify {
            manifest,
            projects,
            check_remote,
            no_check_remote,
            config,
            json,
        } => {
            let config = discover_config(config.as_deref())?;
            let check_remote = resolve_check_remote(
                check_remote,
                no_check_remote,
                config
                    .as_ref()
                    .map(|cfg| cfg.verify.check_remote)
                    .unwrap_or(false),
            );
            restore::verify_cmd(&manifest, &projects, check_remote, json)
        }
    }
}

fn scan_cmd(roots: &[PathBuf], all: bool, json: bool) -> anyhow::Result<()> {
    let mut projects = Vec::new();
    let mut seen = HashSet::new();
    let mut failed = false;
    for root in roots {
        match discover(root, all) {
            Ok(ps) => {
                for p in ps {
                    if seen.insert(p.path.clone()) {
                        projects.push(p)
                    }
                }
            }
            Err(e) => {
                eprintln!("error: {e}");
                failed = true
            }
        }
    }
    if json {
        println!("{}", serde_json::to_string_pretty(&projects)?);
    } else if projects.is_empty() {
        eprintln!("No projects found.")
    } else {
        println!(
            "{:<24} {:>10}  {:<20} {:<8} {:<42} MODIFIED",
            "PROJECT", "SIZE", "BRANCH", "STATE", "MARKERS"
        );
        for p in &projects {
            let (branch, state): (String, String) = match &p.git {
                None => ("-".into(), "-".into()),
                Some(g) => (
                    g.branch.clone().unwrap_or_else(|| "-".into()),
                    g.dirty
                        .map(|d| if d { "dirty" } else { "clean" }.into())
                        .unwrap_or_else(|| "unknown".into()),
                ),
            };
            println!(
                "{:<24} {:>10}  {:<20} {:<8} {:<42} {}",
                p.name,
                human(p.size_bytes),
                branch,
                state,
                p.markers.join(", "),
                p.last_modified
                    .map(|d| d.format("%Y-%m-%d %H:%M").to_string())
                    .unwrap_or_else(|| "-".into())
            );
        }
    }
    for p in &projects {
        let Some(git) = &p.git else {
            continue;
        };
        if git.dirty.is_some() {
            continue;
        }
        let detail = git.detail.as_deref().unwrap_or("git status unavailable");
        eprintln!("warning: {}: git state unknown ({detail})", p.name);
    }
    if failed {
        anyhow::bail!("one or more roots could not be scanned")
    }
    Ok(())
}
pub(crate) fn human(n: u64) -> String {
    let mut v = n as f64;
    let mut unit = "B";
    for u in ["KiB", "MiB", "GiB", "TiB"] {
        if v < 1024.0 {
            break;
        }
        v /= 1024.0;
        unit = u;
    }
    if unit == "B" {
        format!("{n} B")
    } else {
        format!("{v:.1} {unit}")
    }
}
pub(crate) fn expand(p: &Path) -> PathBuf {
    let s = p.to_string_lossy();
    let home = || {
        #[cfg(windows)]
        {
            env::var_os("USERPROFILE").or_else(|| env::var_os("HOME"))
        }
        #[cfg(not(windows))]
        {
            env::var_os("HOME")
        }
    };
    if s == "~" {
        home().map(PathBuf::from).unwrap_or_else(|| p.to_owned())
    } else {
        let rest = if cfg!(windows) {
            s.strip_prefix("~/").or_else(|| s.strip_prefix("~\\"))
        } else {
            s.strip_prefix("~/")
        };
        rest.map(|rest| home().map(PathBuf::from).unwrap_or_default().join(rest))
            .unwrap_or_else(|| p.to_owned())
    }
}
fn resolve_for_creation(path: &Path) -> anyhow::Result<PathBuf> {
    let absolute = if path.is_absolute() {
        path.to_owned()
    } else {
        env::current_dir()?.join(path)
    };
    let mut resolved = PathBuf::new();
    for component in absolute.components() {
        match component {
            Component::Prefix(_) | Component::RootDir => resolved.push(component.as_os_str()),
            Component::CurDir => {}
            Component::ParentDir => {
                match fs::metadata(&resolved) {
                    Ok(metadata) => anyhow::ensure!(
                        metadata.is_dir(),
                        "path component is not a directory: {}",
                        resolved.display()
                    ),
                    Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
                    Err(error) => return Err(error.into()),
                }
                resolved.pop();
            }
            Component::Normal(name) => {
                resolved.push(name);
                match fs::symlink_metadata(&resolved) {
                    Ok(_) => resolved = fs::canonicalize(&resolved)?,
                    Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
                    Err(error) => return Err(error.into()),
                }
            }
        }
    }
    Ok(resolved)
}

pub(crate) fn is_artifact(s: &str) -> bool {
    ARTIFACT_GLOBS
        .get_or_init(|| {
            RULES
                .iter()
                .flat_map(|(_, patterns)| *patterns)
                .filter_map(|pattern| {
                    GlobBuilder::new(pattern)
                        .case_insensitive(cfg!(windows))
                        .build()
                        .ok()
                })
                .map(|glob| glob.compile_matcher())
                .collect()
        })
        .iter()
        .any(|glob| glob.is_match(s))
}
#[cfg(test)]
#[path = "tests.rs"]
mod tests;