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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
use crate::cleanup::{CleanMode, CleanupSelection};
use clap::{Parser, Subcommand};
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, clap::ValueEnum)]
pub enum OutputFormat {
#[default]
Human,
Json,
/// One bounded ASCII summary line per report, for unattended schedulers
/// that retain a short history tail. Not a machine contract: complete
/// consumers use `json`.
Log,
}
#[derive(Debug, Parser)]
#[command(
name = "cargo-cleanme",
version,
about = "Clean inactive Cargo build artifacts through Cargo, or reconcile the machine read-only",
long_about = "Clean inactive Cargo build artifacts through Cargo, or reconcile the machine read-only.\n\n\
Bare `cargo cleanme` runs routine maintenance: it selects the maintenance scope \
(bounded seed roots plus active learned roots, or a configured scan.root when one exists), \
re-proves complete ownership for every discovered participant, and executes eligible Cargo \
cleanup units. `--dry-run` performs the identical decision and proof path while invoking no \
`cargo clean` process at all.\n\n\
`cargo cleanme scan` with no ROOT is the full read-only machine reconciliation; it is the only \
operation allowed to expire learned roots. `cargo cleanme scan ROOT` is a bounded explicit scan, \
and `cargo cleanme scan --known` is the read-only routine inventory.\n\n\
Deletion is always delegated to Cargo; cargo-cleanme never removes a directory itself."
)]
pub struct Cli {
#[arg(long, global = true)]
pub config: Option<PathBuf>,
/// Disable transient progress UI (useful for benchmarks and debugging).
#[arg(long, global = true)]
pub no_progress: bool,
/// Print detailed scan/cleanup counters and phase timings to stderr.
/// Never changes deterministic stdout. `--no-progress --stats` is the
/// canonical benchmark/debug combination.
#[arg(long, global = true)]
pub stats: bool,
/// Select human-readable output, the versioned JSON automation contract, or
/// one bounded ASCII summary line for unattended schedulers.
#[arg(long, global = true, value_enum, default_value_t = OutputFormat::Human)]
pub format: OutputFormat,
/// Simulate: run every decision, proof, and reporting step, but invoke no
/// `cargo clean` process at all. Honoured wherever it appears, so the
/// `cargo cleanme --dry-run clean ROOT` spelling cannot fall back to
/// Execute. Only `clean` (and `update`'s own `--dry-run`) honour it:
/// `scan` and `config` ignore a global `--dry-run` (read-only / local-only,
/// no behaviour change).
#[arg(long, conflicts_with = "dryrun_legacy")]
pub dry_run: bool,
/// Historical spelling of `--dry-run`; retained as a hidden alias.
#[arg(long = "dryrun", hide = true, conflicts_with = "dry_run")]
pub dryrun_legacy: bool,
/// Choose the workspaces to clean from an inline selection list (NOR/INS).
///
/// Resolves the cleanup units read-only, presents one row per unit with its
/// reclaimable bytes, and cleans only what is checked. A selection can
/// remove candidates but never add one: ownership is still proven across
/// the complete universe and the engine still re-proves it per spawn.
///
/// Requires a terminal on stdin and stdout. Combine with `--dry-run` to
/// review a selection without invoking `cargo clean`.
#[arg(short = 'i', long, global = true)]
pub interactive: bool,
#[command(subcommand)]
pub command: Option<Command>,
}
#[derive(Debug, Subcommand)]
pub enum Command {
/// Reconcile the machine read-only: full with `--all`, explicit with ROOT,
/// routine inventory with `--known`.
///
/// Exactly one scope selector is required. An `ArgGroup` expresses that
/// rather than a per-argument `required_unless_present_all`, because a
/// positional ROOT does not satisfy `required_unless_present` in clap 4 โ
/// `scan /tmp` still demanded `--all`. The group also makes the selectors
/// mutually exclusive as a consequence of the same declaration, so the
/// conflict rules cannot drift from the requiredness rules.
#[command(group = clap::ArgGroup::new("scan-scope").required(true).args(["root", "known", "all", "full"]))]
Scan {
/// Optional bounded root. Makes the scan Explicit and bypasses
/// configured ignore/unignore filters.
root: Option<PathBuf>,
/// Routine read-only inventory over the maintenance scope.
#[arg(long)]
known: bool,
/// Full machine reconciliation.
///
/// Required when no ROOT and no `--known` is given: this is the only
/// operation that may expire learned roots, and it walks the whole
/// platform, so it is never one keystroke from the front door.
#[arg(short = 'a', long)]
all: bool,
/// Historical spelling of `--all`; retained as a hidden alias.
#[arg(long, hide = true)]
full: bool,
},
Config {
#[command(subcommand)]
command: ConfigCommand,
},
/// Preview or execute cleanup of revalidated Cargo build artifacts.
Clean {
/// Optional bounded sandbox root. Omit to use the maintenance scope
/// (identical to bare invocation) or select `--known` / `--full`.
root: Option<PathBuf>,
/// Clean bounded roots selected by the current Routine policy.
#[arg(long, conflicts_with_all = ["root", "full"])]
known: bool,
/// Complete Full reconciliation before cleaning its learned roots.
#[arg(long, conflicts_with_all = ["root", "known"])]
full: bool,
/// Require at least this many reclaimable bytes per workspace.
#[arg(long)]
min_reclaimable_bytes: Option<u64>,
/// Require this many seconds of inactivity.
#[arg(long)]
older_than: Option<u64>,
/// Include canonical workspace roots matching this glob (repeatable).
#[arg(long = "include")]
include: Vec<String>,
/// Exclude canonical workspace roots matching this glob (repeatable).
#[arg(long = "exclude")]
exclude: Vec<String>,
/// Ask Cargo to clean one named profile. Selector byte estimates are unknown.
#[arg(long, conflicts_with = "package", value_parser = clap::builder::NonEmptyStringValueParser::new())]
profile: Option<String>,
/// Clean one validated workspace package through qualified Cargo versions.
#[arg(long, conflicts_with = "profile", value_parser = clap::builder::NonEmptyStringValueParser::new())]
package: Option<String>,
/// Application simulation: run the full decision/proof/report path but
/// invoke no Cargo clean command. The default mode is Execute.
#[arg(long, conflicts_with_all = ["cargo_preview", "yes_legacy", "dryrun_legacy"])]
dry_run: bool,
/// Cargo preview: after the same complete final proof, invoke Cargo's
/// own `clean --dry-run --verbose`. Never removes anything.
#[arg(long, conflicts_with_all = ["dry_run", "yes_legacy", "dryrun_legacy"])]
cargo_preview: bool,
/// Historical spelling of the (now default) Execute mode; retained as a
/// hidden alias.
#[arg(long = "yes", hide = true, conflicts_with_all = ["dry_run", "cargo_preview", "dryrun_legacy"])]
yes_legacy: bool,
/// Historical spelling of `--dry-run`; retained as a hidden alias.
#[arg(long = "dryrun", hide = true, conflicts_with_all = ["dry_run", "cargo_preview", "yes_legacy"])]
dryrun_legacy: bool,
},
/// Update this cargo-cleanme to the latest stable published release.
///
/// The registry is the version authority, the release tag is constructed
/// from that version rather than scraped, and the candidate is replaced
/// only after its `.sha256` evidence is verified and it identifies itself
/// as exactly the target version. A Cargo-managed installation is refused
/// with the exact manager command, because Cargo owns that file and its
/// bookkeeping.
Update {
/// Resolve the plan and report it without acquiring or replacing bytes.
#[arg(long)]
dry_run: bool,
},
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Subcommand)]
pub enum ConfigCommand {
Path,
Show,
Edit,
}
/// Which roots a cleanup intent selects.
///
/// Bare maintenance and `clean` with no scope selector deliberately resolve to
/// the *same* variant, so the two spellings cannot drift apart in root
/// selection, policy, proof, or reporting: there is one cleanup engine and one
/// set of gates behind both.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CleanupScope {
/// Maintenance scope, resolved by [`crate::policy::resolve`] with no CLI
/// root and no Full request: a configured legacy `scan.root` wins as an
/// exclusive Explicit override, otherwise bounded seed roots plus active
/// learned roots form the Routine scope.
Maintenance,
/// One bounded explicit root supplied as `clean ROOT`.
Root(PathBuf),
/// `clean --full`: complete Full reconciliation first, then cleanup of the
/// learned roots it retained.
Full,
}
/// Which roots a read-only scan selects.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ScanIntent {
/// `scan` with no ROOT: full machine reconciliation under platform policy.
///
/// This never consults a configured `scan.root`; configuration must not be
/// able to silently narrow the canonical reconciliation command.
Full,
/// `scan ROOT`: bounded explicit scan that bypasses discovery filters.
Explicit(PathBuf),
/// `scan --known`: the non-Full maintenance scope, read-only. Learned roots
/// may advance positive observations but are never pruned here.
Maintenance,
}
/// Advanced cleanup policy overrides.
///
/// These live only on the `clean` subcommand by design (M012A work package D):
/// bare maintenance intentionally uses the configured/default policy rather
/// than cloning the whole advanced option surface onto the root command.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct CleanupOverrides {
pub min_reclaimable_bytes: Option<u64>,
pub older_than: Option<u64>,
pub include: Vec<String>,
pub exclude: Vec<String>,
pub profile: Option<String>,
pub package: Option<String>,
}
/// One resolved cleanup intent: what to clean, in what mode, with which
/// policy overrides.
///
/// Bare maintenance and every advanced cleanup spelling produce this same
/// value, so there is exactly one cleanup code path behind all of them.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CleanupRequest {
pub scope: CleanupScope,
pub mode: CleanMode,
pub overrides: CleanupOverrides,
/// Which resolved cleanup units are candidates. M014: bare invocation and
/// `clean --known` anchor this to the working directory; `clean ROOT` and
/// `clean --full` leave it unfiltered because their roots already bound it.
///
/// `WorkingDirectory` here is *unresolved intent*. `main.rs` must call
/// [`CleanupSelection::resolved`] before the engine runs.
///
/// `-i` overrides this: the interactive session replaces it with the
/// operator's choice, which is a strictly narrower `Roots` selection.
pub selection: CleanupSelection,
/// `-i`/`--interactive`: present the selection list before cleaning.
///
/// Kept separate from `selection` because the two answer different
/// questions โ *how* units are chosen versus *whether* a session runs at
/// all โ and because the interactive selection can only be resolved once a
/// terminal exists, which argv parsing must not do.
pub interactive: bool,
}
/// The resolved operation, scope, and mode for one invocation.
///
/// This is the single internal representation shared by bare maintenance and
/// every advanced cleanup spelling, so "no subcommand" is an explicit Routine
/// cleanup intent rather than a fallthrough to scan.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Invocation {
Cleanup(CleanupRequest),
Scan(ScanIntent),
Config(ConfigCommand),
Update {
dry_run: bool,
},
/// An argv shape clap should have rejected before it reached this point.
///
/// `scan` requires one of ROOT / `--known` / `--all`; clap enforces that,
/// so this arm is unreachable through the parser. It exists because the
/// compiler cannot see clap's invariant, and the two available fallbacks
/// were both wrong: defaulting to Full would silently run the machine-wide
/// reconciliation the flag exists to gate, and panicking would exit 101,
/// outside the 0/1/2 contract.
UsageError(String),
}
/// Resolve the mode flag triple onto the canonical mode.
///
/// Execute is the default: absent a mode flag, cleanup executes eligible units.
/// The hidden compatibility aliases select the same two canonical modes and
/// never introduce a fourth mode or a different safety path.
pub fn clean_mode(dry_run: bool, cargo_preview: bool, dryrun_legacy: bool) -> CleanMode {
debug_assert!(
!((dry_run || dryrun_legacy) && cargo_preview),
"clap rejects conflicting mode flags before this mapping runs"
);
if dry_run || dryrun_legacy {
CleanMode::Simulate
} else if cargo_preview {
CleanMode::CargoPreview
} else {
CleanMode::Execute
}
}
impl Cli {
/// Parse the current process argv after Cargo external-subcommand normalization.
pub fn parse_normalized() -> Self {
Self::parse_from(normalize_cargo_argv(std::env::args_os()))
}
/// Parse an explicit argv vector after Cargo external-subcommand normalization.
pub fn try_parse_normalized_from(
args: impl IntoIterator<Item = OsString>,
) -> Result<Self, clap::Error> {
Self::try_parse_from(normalize_cargo_argv(args))
}
/// Collapse parsed argv into one resolved operation/scope/mode.
pub fn invocation(&self) -> Invocation {
match &self.command {
// No subcommand *is* routine maintenance, not a scan fallthrough.
None => Invocation::Cleanup(CleanupRequest {
scope: CleanupScope::Maintenance,
mode: clean_mode(self.dry_run, false, self.dryrun_legacy),
overrides: CleanupOverrides::default(),
selection: CleanupSelection::WorkingDirectory,
interactive: self.interactive,
}),
Some(Command::Scan {
root,
known,
all,
full,
}) => match (root, *known, *all || *full) {
(Some(root), _, _) => Invocation::Scan(ScanIntent::Explicit(root.clone())),
(None, true, _) => Invocation::Scan(ScanIntent::Maintenance),
// clap requires one of ROOT / --known / --all, so reaching the
// Full arm means an explicit flag (or its hidden alias) was
// actually given rather than defaulted.
(None, false, true) => Invocation::Scan(ScanIntent::Full),
// Unreachable through `clap`; fail closed rather than guess.
(None, false, false) => {
Invocation::UsageError("scan requires a ROOT, --known, or --all".into())
}
},
Some(Command::Config { command }) => Invocation::Config(*command),
// The root-level `--dry-run` is honoured here too, not only on the
// bare front door: `cargo cleanme --dry-run clean ROOT` is the
// spelling Cargo itself passes, so a flag parsed before the
// subcommand must never silently fall back to Execute.
Some(Command::Update { dry_run }) => Invocation::Update {
dry_run: *dry_run || self.dry_run || self.dryrun_legacy,
},
// `yes_legacy` is intentionally not bound: `--yes` used to be the
// only way to ask for Execute, Execute is now the default, so the
// flag carries no intent of its own and printing nothing about it
// is what keeps unattended runs quiet.
Some(Command::Clean {
root,
known,
full,
dry_run,
cargo_preview,
dryrun_legacy,
min_reclaimable_bytes,
older_than,
include,
exclude,
profile,
package,
..
}) => {
let scope = match (root, *full, *known) {
(Some(root), _, _) => CleanupScope::Root(root.clone()),
(None, true, _) => CleanupScope::Full,
// `clean` with no selector is the same intent as bare
// invocation, not a third scope.
(None, false, _) => CleanupScope::Maintenance,
};
// M014: the working-directory anchor belongs to the
// *maintenance* spellings, which are the ones whose Routine
// scope spans the machine. `clean ROOT` and `clean --full`
// already bound their own scope and stay unfiltered, so the
// two cannot silently disagree about what "everything" means.
let selection = match scope {
CleanupScope::Maintenance => CleanupSelection::WorkingDirectory,
CleanupScope::Root(_) | CleanupScope::Full => CleanupSelection::All,
};
Invocation::Cleanup(CleanupRequest {
scope,
mode: if self.dry_run || self.dryrun_legacy {
CleanMode::Simulate
} else {
clean_mode(*dry_run, *cargo_preview, *dryrun_legacy)
},
overrides: CleanupOverrides {
min_reclaimable_bytes: *min_reclaimable_bytes,
older_than: *older_than,
include: include.clone(),
exclude: exclude.clone(),
profile: profile.clone(),
package: package.clone(),
},
selection,
interactive: self.interactive,
})
}
}
}
}
/// Normalize Cargo external-subcommand argv before clap parses it.
///
/// Cargo executes an external subcommand `cargo cleanme ...` by invoking the
/// `cargo-cleanme` binary with the subcommand name injected as the second argv
/// element (`["cargo-cleanme", "cleanme", ...]`). Direct invocation never
/// produces that shape for a valid command because `cleanme` is not a
/// `cargo-cleanme` subcommand; the only valid first arguments are
/// `scan`/`config`/`clean`/`update`/help/version flags or no argument at all.
///
/// This strips exactly one `cleanme` token in the documented second position
/// and leaves every later `cleanme` path/value untouched.
pub fn normalize_cargo_argv(args: impl IntoIterator<Item = OsString>) -> Vec<OsString> {
let mut argv: Vec<OsString> = args.into_iter().collect();
if argv.len() >= 2 && argv[1] == "cleanme" {
argv.remove(1);
}
argv
}
/// Resolve a user-supplied `clean ROOT` against the invocation directory into
/// an absolute lexical path.
///
/// The internal cleanup boundary keeps its absolute-root invariant; this only
/// normalizes CLI ergonomics. Canonicalization is deliberately not required:
/// the policy/cleanup layers still verify that the effective root exists, is
/// a real directory, and is not a symlink.
///
/// A relative root with an unresolvable current directory is an `InvalidRoot`
/// usage error, never a silent fallback: hiding the IO error rewrote
/// `clean ./p` to `/p`.
pub fn absolutize_root(root: &Path) -> Result<PathBuf, crate::error::AppError> {
if root.is_absolute() {
return Ok(root.to_path_buf());
}
let base = std::env::current_dir().map_err(|e| crate::error::AppError::InvalidRoot {
path: root.display().to_string(),
reason: format!("cannot resolve current directory: {e}"),
})?;
Ok(absolutize_relative(&base, root))
}
/// Deterministic absolutization against an explicit base directory.
///
/// Production uses [`absolutize_root`] (current directory as base); tests use
/// this helper to avoid mutating the process-global current directory.
#[doc(hidden)]
pub fn absolutize_root_for_test(base: &Path, root: &Path) -> PathBuf {
if root.is_absolute() {
return root.to_path_buf();
}
absolutize_relative(base, root)
}
pub(crate) fn absolutize_relative(base: &Path, relative: &Path) -> PathBuf {
let mut out = if base.is_absolute() {
base.to_path_buf()
} else {
PathBuf::from("/").join(base)
};
for component in relative.components() {
match component {
Component::Prefix(part) => {
out = PathBuf::from(part.as_os_str());
}
Component::RootDir => {
out.push(component.as_os_str());
}
Component::CurDir => {}
Component::ParentDir => {
// Lexical pop only: never follows symlinks. A `..` that would
// rise above the filesystem root stays at the root; otherwise
// it resolves against the actual caller-selected directory
// stack without escaping it through surprising semantics.
let _ = out.pop();
}
Component::Normal(part) => out.push(part),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use clap::{CommandFactory, Parser};
use std::ffi::OsString;
fn maintenance(mode: CleanMode) -> CleanupRequest {
cleanup(CleanupScope::Maintenance, mode)
}
fn cleanup(scope: CleanupScope, mode: CleanMode) -> CleanupRequest {
// Mirror `Cli::invocation` exactly: the working-directory anchor belongs
// to the maintenance spellings, whose Routine scope spans the machine.
// `clean ROOT` / `clean --full` are already bounded by their own roots.
let selection = match &scope {
CleanupScope::Maintenance => CleanupSelection::WorkingDirectory,
CleanupScope::Root(_) | CleanupScope::Full => CleanupSelection::All,
};
CleanupRequest {
scope,
mode,
overrides: CleanupOverrides::default(),
selection,
interactive: false,
}
}
#[test]
fn bare_invocation_is_routine_execute_maintenance_not_scan() {
// ADR 003 ยง1: bare invocation is the canonical maintenance operation.
// This is the regression that fails against the old bare-read-only
// dispatch, where `Cli::command` was None and main fell through to
// `run_scan(None, false, ...)`.
let parsed = Cli::try_parse_from(["cargo-cleanme"]).unwrap();
assert!(parsed.command.is_none());
assert_eq!(
parsed.invocation(),
Invocation::Cleanup(maintenance(CleanMode::Execute))
);
}
#[test]
fn bare_dry_run_is_simulate_and_the_legacy_alias_maps_to_it() {
for args in [
vec!["cargo-cleanme", "--dry-run"],
vec!["cargo-cleanme", "--dryrun"],
] {
let parsed = Cli::try_parse_from(args.clone()).unwrap();
assert_eq!(
parsed.invocation(),
Invocation::Cleanup(maintenance(CleanMode::Simulate)),
"{args:?}"
);
}
assert!(
Cli::try_parse_from(["cargo-cleanme", "--dry-run", "--dryrun"]).is_err(),
"the alias must not be combinable with the canonical spelling"
);
}
#[test]
fn a_dry_run_before_the_subcommand_is_still_a_dry_run() {
// `cargo cleanme --dry-run clean ROOT` is the spelling Cargo itself
// passes, and it used to parse cleanly while the root field was never
// read on that arm -- so the flag was silently discarded and a real
// `cargo clean` ran. The canonical spelling was correct, which is what
// made it silent.
for args in [
vec!["cargo-cleanme", "--dry-run", "clean", "/tmp/p"],
vec!["cargo-cleanme", "--dryrun", "clean", "/tmp/p"],
] {
let parsed = Cli::try_parse_from(args.clone()).unwrap();
assert_eq!(
parsed.invocation(),
Invocation::Cleanup(cleanup(
CleanupScope::Root(std::path::PathBuf::from("/tmp/p")),
CleanMode::Simulate,
)),
"{args:?} must not fall back to Execute"
);
}
// The bare front door keeps its own spelling working.
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "--dry-run"])
.unwrap()
.invocation(),
Invocation::Cleanup(cleanup(CleanupScope::Maintenance, CleanMode::Simulate))
);
// And so does the position after the subcommand.
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "clean", "/tmp/p", "--dry-run"])
.unwrap()
.invocation(),
Invocation::Cleanup(cleanup(
CleanupScope::Root(std::path::PathBuf::from("/tmp/p")),
CleanMode::Simulate,
))
);
// Without the flag, Execute is still the default in that position.
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "clean", "/tmp/p"])
.unwrap()
.invocation(),
Invocation::Cleanup(cleanup(
CleanupScope::Root(std::path::PathBuf::from("/tmp/p")),
CleanMode::Execute,
))
);
}
#[test]
fn a_dry_run_before_update_is_still_a_dry_run() {
// Same route, same bug: the root flag was discarded before the
// `Update` arm too, so `cargo cleanme --dry-run update` would have
// replaced the binary.
for args in [
vec!["cargo-cleanme", "--dry-run", "update"],
vec!["cargo-cleanme", "--dryrun", "update"],
] {
assert_eq!(
Cli::try_parse_from(args.clone()).unwrap().invocation(),
Invocation::Update { dry_run: true },
"{args:?} must not replace the binary"
);
}
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "update"])
.unwrap()
.invocation(),
Invocation::Update { dry_run: false }
);
}
#[test]
fn a_root_dry_run_wins_over_cargo_preview_because_it_spawns_nothing() {
// clap cannot make a root flag mutually exclusive with a subcommand's
// flags, so the combination reaches here. Simulation is the mode that
// spawns no Cargo process at all, and a user who asked for it before
// the subcommand must not be handed a Cargo invocation instead.
assert_eq!(
Cli::try_parse_from([
"cargo-cleanme",
"--dry-run",
"clean",
"/tmp/p",
"--cargo-preview"
])
.unwrap()
.invocation(),
Invocation::Cleanup(cleanup(
CleanupScope::Root(std::path::PathBuf::from("/tmp/p")),
CleanMode::Simulate,
))
);
// Without the root flag, Cargo preview is unaffected.
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "clean", "/tmp/p", "--cargo-preview"])
.unwrap()
.invocation(),
Invocation::Cleanup(cleanup(
CleanupScope::Root(std::path::PathBuf::from("/tmp/p")),
CleanMode::CargoPreview,
))
);
}
#[test]
fn scan_scope_selection_is_full_explicit_or_maintenance() {
// M014: Full is no longer reachable without an explicit selector.
// `scan` alone is a usage error, so the machine-wide reconciliation --
// the only operation that may expire learned roots -- is never one
// keystroke from the front door.
assert!(
Cli::try_parse_from(["cargo-cleanme", "scan"]).is_err(),
"bare `scan` must require ROOT, --known, or --all"
);
// Both spellings of the Full selector reach the same intent.
for spelling in [
["cargo-cleanme", "scan", "--all"],
["cargo-cleanme", "scan", "-a"],
["cargo-cleanme", "scan", "--full"],
] {
assert_eq!(
Cli::try_parse_from(spelling).unwrap().invocation(),
Invocation::Scan(ScanIntent::Full),
"{spelling:?} must resolve to Full"
);
}
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "scan", "/tmp"])
.unwrap()
.invocation(),
Invocation::Scan(ScanIntent::Explicit(PathBuf::from("/tmp")))
);
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "scan", "--known"])
.unwrap()
.invocation(),
Invocation::Scan(ScanIntent::Maintenance)
);
}
#[test]
fn the_interactive_flag_is_declared_advertised_and_not_implied() {
use clap::CommandFactory;
// M014 removed a previously-declared `-i` precisely because a flag that
// parses and silently does nothing is worse than no flag. This is the
// regression against reintroducing that shape.
let help = Cli::command().render_long_help().to_string();
assert!(
help.contains("-i, --interactive"),
"the flag must be advertised: {help}"
);
assert!(
Cli::try_parse_from(["cargo-cleanme", "-i"])
.unwrap()
.interactive
);
assert!(
Cli::try_parse_from(["cargo-cleanme", "--interactive"])
.unwrap()
.interactive,
"--interactive must be the same flag"
);
assert!(
!Cli::try_parse_from(["cargo-cleanme"]).unwrap().interactive,
"-i must not be implied by an ordinary invocation"
);
// It is global, so the subcommand spelling must carry it too.
match Cli::try_parse_from(["cargo-cleanme", "clean", "--known", "-i"])
.unwrap()
.invocation()
{
Invocation::Cleanup(request) => assert!(
request.interactive,
"the flag must reach the cleanup intent, not just the parser"
),
other => panic!("expected a cleanup intent, got {other:?}"),
}
// The flag does not manufacture a selection: it declares that a
// session will produce one. The declared selection still travels
// alongside it, so the non-interactive path is unchanged.
match Cli::try_parse_from(["cargo-cleanme", "-i"])
.unwrap()
.invocation()
{
Invocation::Cleanup(request) => {
assert_eq!(
request.selection,
CleanupSelection::WorkingDirectory,
"-i must not pre-empt the anchor; the session replaces it"
);
}
other => panic!("expected a cleanup intent, got {other:?}"),
}
}
#[test]
fn interactive_without_a_terminal_still_means_human_format_only() {
// The machine formats are refused in `main`, not here: this layer does
// no IO and must stay pure. What it *can* prove is that the flag
// coexists with every output format, so the refusal is a runtime
// guard on a real conflict rather than an accident of parsing.
for (flag, expected) in [
("human", OutputFormat::Human),
("json", OutputFormat::Json),
("log", OutputFormat::Log),
] {
let cli = Cli::try_parse_from(["cargo-cleanme", "-i", "--format", flag]).unwrap();
assert_eq!(cli.format, expected);
assert!(cli.interactive);
}
}
#[test]
fn maintenance_spellings_anchor_selection_to_the_working_directory() {
// M014 / ADR 006: the anchor belongs to the two spellings whose Routine
// scope spans the machine. Both must agree, or `cargo cleanme` and
// `cargo cleanme clean --known` would disagree about what "everything"
// means โ which is the M012A silent-no-op failure in a new spelling.
for args in [
vec!["cargo-cleanme"],
vec!["cargo-cleanme", "clean"],
vec!["cargo-cleanme", "clean", "--known"],
] {
let Invocation::Cleanup(request) =
Cli::try_parse_from(args.clone()).unwrap().invocation()
else {
panic!("{args:?} must resolve to a cleanup request");
};
assert_eq!(
request.selection,
CleanupSelection::WorkingDirectory,
"{args:?} must anchor its selection to the working directory"
);
}
// `clean ROOT` and `clean --full` are already bounded by their own root
// selection; anchoring them too would silently narrow an explicit scope.
for args in [
vec!["cargo-cleanme", "clean", "/x"],
vec!["cargo-cleanme", "clean", "--full"],
] {
let Invocation::Cleanup(request) =
Cli::try_parse_from(args.clone()).unwrap().invocation()
else {
panic!("{args:?} must resolve to a cleanup request");
};
assert_eq!(
request.selection,
CleanupSelection::All,
"{args:?} must stay unfiltered"
);
}
}
#[test]
fn unresolved_working_directory_anchor_selects_nothing() {
// Fail-closed: `cli.rs` emits the anchor unresolved because it must not
// do IO. A caller that forgets to resolve it must clean nothing, not
// everything. Returning `true` here would make that bug delete data.
assert!(
!CleanupSelection::WorkingDirectory.admits(Path::new("/any/workspace")),
"an unresolved anchor must never admit a candidate"
);
}
#[test]
fn scan_scope_conflicts_fail_at_invocation_time() {
for args in [
vec!["cargo-cleanme", "scan", "/tmp", "--known"],
vec!["cargo-cleanme", "scan", "/tmp", "--all"],
vec!["cargo-cleanme", "scan", "/tmp", "--full"],
vec!["cargo-cleanme", "scan", "--known", "--full"],
vec!["cargo-cleanme", "scan", "--known", "--all"],
vec!["cargo-cleanme", "scan", "--all", "--full"],
] {
assert!(
Cli::try_parse_from(args.clone()).is_err(),
"{args:?} must be rejected before any traversal"
);
}
}
#[test]
fn hidden_full_alias_is_not_advertised_in_scan_help() {
let help = Cli::command().render_long_help().to_string();
assert!(!help.contains("--full"), "{help}");
assert!(help.contains("--known"), "{help}");
}
#[test]
fn clean_scope_selectors_stay_mutually_exclusive() {
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "clean", "/tmp"])
.unwrap()
.invocation(),
Invocation::Cleanup(cleanup(
CleanupScope::Root(PathBuf::from("/tmp")),
CleanMode::Execute
))
);
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "clean", "--known"])
.unwrap()
.invocation(),
Invocation::Cleanup(maintenance(CleanMode::Execute))
);
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "clean", "--full"])
.unwrap()
.invocation(),
Invocation::Cleanup(cleanup(CleanupScope::Full, CleanMode::Execute))
);
// No selector at all is the same intent as bare invocation.
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "clean"])
.unwrap()
.invocation(),
Cli::try_parse_from(["cargo-cleanme"]).unwrap().invocation()
);
assert!(Cli::try_parse_from(["cargo-cleanme", "clean", "/x", "--known"]).is_err());
assert!(Cli::try_parse_from(["cargo-cleanme", "clean", "--known", "--full"]).is_err());
assert!(Cli::try_parse_from(["cargo-cleanme", "clean", "/x", "--full"]).is_err());
}
#[test]
fn cleanup_modes_default_to_execute_and_expose_cargo_preview() {
for (args, expected) in [
(vec!["cargo-cleanme", "clean", "/tmp"], CleanMode::Execute),
(
vec!["cargo-cleanme", "clean", "/tmp", "--dry-run"],
CleanMode::Simulate,
),
(
vec!["cargo-cleanme", "clean", "/tmp", "--cargo-preview"],
CleanMode::CargoPreview,
),
(
vec!["cargo-cleanme", "clean", "/tmp", "--yes"],
CleanMode::Execute,
),
(
vec!["cargo-cleanme", "clean", "/tmp", "--dryrun"],
CleanMode::Simulate,
),
] {
let parsed = Cli::try_parse_from(args.clone()).unwrap();
assert_eq!(
parsed.invocation(),
Invocation::Cleanup(cleanup(CleanupScope::Root(PathBuf::from("/tmp")), expected)),
"{args:?}"
);
}
// Every mode pair is rejected rather than silently precedence-resolved.
for args in [
vec![
"cargo-cleanme",
"clean",
"/tmp",
"--dry-run",
"--cargo-preview",
],
vec!["cargo-cleanme", "clean", "/tmp", "--dry-run", "--yes"],
vec!["cargo-cleanme", "clean", "/tmp", "--cargo-preview", "--yes"],
vec!["cargo-cleanme", "clean", "/tmp", "--dry-run", "--dryrun"],
vec![
"cargo-cleanme",
"clean",
"/tmp",
"--cargo-preview",
"--dryrun",
],
vec!["cargo-cleanme", "clean", "/tmp", "--yes", "--dryrun"],
] {
assert!(Cli::try_parse_from(args.clone()).is_err(), "{args:?}");
}
}
#[test]
fn compatibility_aliases_are_hidden_but_accepted() {
let clean_help = Cli::command()
.find_subcommand_mut("clean")
.expect("clean subcommand")
.render_long_help()
.to_string();
assert!(!clean_help.contains("--yes"), "{clean_help}");
assert!(!clean_help.contains("--dryrun"), "{clean_help}");
assert!(clean_help.contains("--cargo-preview"), "{clean_help}");
assert!(clean_help.contains("--dry-run"), "{clean_help}");
}
#[test]
fn update_keeps_its_own_dry_run_meaning() {
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "update", "--dry-run"])
.unwrap()
.invocation(),
Invocation::Update { dry_run: true }
);
}
#[test]
fn format_log_parses_globally() {
// M012B ยง11.1: `--format log` is a global value, so it is accepted
// before or after a subcommand and through the external form.
for args in [
vec!["cargo-cleanme", "--format", "log"],
vec!["cargo-cleanme", "scan", "--all", "--format", "log"],
vec!["cargo-cleanme", "--format", "log", "scan", "--all"],
vec!["cargo-cleanme", "clean", "/x", "--format", "log"],
vec![
"cargo-cleanme",
"cleanme",
"--format",
"log",
"scan",
"--all",
],
] {
let normalized: Vec<OsString> = args.iter().map(OsString::from).collect();
let parsed = Cli::try_parse_from(normalize_cargo_argv(normalized)).unwrap();
assert_eq!(parsed.format, OutputFormat::Log, "{args:?}");
}
assert_eq!(
Cli::try_parse_from(["cargo-cleanme"]).unwrap().format,
OutputFormat::Human,
"log is opt-in; a non-TTY stdout must never select it"
);
assert!(Cli::try_parse_from(["cargo-cleanme", "--format", "yaml"]).is_err());
}
#[test]
fn config_command_parses() {
assert!(Cli::try_parse_from(["cargo-cleanme", "config", "path"]).is_ok());
assert!(Cli::try_parse_from(["cargo-cleanme", "config", "edit"]).is_ok());
assert!(Cli::try_parse_from(["cargo-cleanme", "config", "init"]).is_err());
assert_eq!(
Cli::try_parse_from(["cargo-cleanme", "config", "show"])
.unwrap()
.invocation(),
Invocation::Config(ConfigCommand::Show)
);
}
#[test]
fn root_parses() {
let c = Cli::try_parse_from(["cargo-cleanme", "scan", "/tmp"]).unwrap();
assert_eq!(
c.invocation(),
Invocation::Scan(ScanIntent::Explicit(PathBuf::from("/tmp")))
);
}
#[test]
fn cleanup_policy_options_are_repeatable_and_mode_independent() {
let parsed = Cli::try_parse_from([
"cargo-cleanme",
"clean",
"--known",
"--min-reclaimable-bytes",
"42",
"--older-than",
"60",
"--include",
"**/one",
"--include",
"**/two",
"--exclude",
"**/tmp",
"--dry-run",
])
.unwrap();
let intent = parsed.invocation();
assert!(
matches!(parsed.command, Some(Command::Clean { min_reclaimable_bytes: Some(42), older_than: Some(60), include, exclude, .. }) if include.len() == 2 && exclude == ["**/tmp"])
);
assert_eq!(
intent,
Invocation::Cleanup(CleanupRequest {
scope: CleanupScope::Maintenance,
mode: CleanMode::Simulate,
overrides: CleanupOverrides {
min_reclaimable_bytes: Some(42),
older_than: Some(60),
include: vec!["**/one".into(), "**/two".into()],
exclude: vec!["**/tmp".into()],
profile: None,
package: None,
},
selection: CleanupSelection::WorkingDirectory,
interactive: false,
}),
"advanced policy overrides travel with the intent, not beside it"
);
let selected =
Cli::try_parse_from(["cargo-cleanme", "clean", "/tmp", "--profile", "custom"]).unwrap();
assert!(
matches!(selected.command, Some(Command::Clean { profile: Some(p), .. }) if p == "custom")
);
assert!(
Cli::try_parse_from([
"cargo-cleanme",
"clean",
"/tmp",
"--profile",
"release",
"--package",
"app",
])
.is_err()
);
}
#[test]
fn orchestration_roots_are_mutually_exclusive_and_external_forms_match() {
for mode in ["--known", "--full"] {
let direct =
Cli::try_parse_from(["cargo-cleanme", "clean", mode, "--dry-run"]).unwrap();
let external = Cli::try_parse_normalized_from(argv(&[
"cargo-cleanme",
"cleanme",
"clean",
mode,
"--dry-run",
]))
.unwrap();
assert_eq!(direct.invocation(), external.invocation());
}
}
fn argv(items: &[&str]) -> Vec<OsString> {
items.iter().map(OsString::from).collect()
}
#[test]
fn direct_argv_is_unchanged() {
assert_eq!(
normalize_cargo_argv(argv(&["cargo-cleanme"])),
argv(&["cargo-cleanme"])
);
assert_eq!(
normalize_cargo_argv(argv(&["cargo-cleanme", "scan", "/x"])),
argv(&["cargo-cleanme", "scan", "/x"])
);
}
#[test]
fn cargo_external_argv_strips_exactly_one_documented_token() {
assert_eq!(
normalize_cargo_argv(argv(&["cargo-cleanme", "cleanme"])),
argv(&["cargo-cleanme"])
);
assert_eq!(
normalize_cargo_argv(argv(&["cargo-cleanme", "cleanme", "scan", "/x"])),
argv(&["cargo-cleanme", "scan", "/x"])
);
assert_eq!(
normalize_cargo_argv(argv(&["cargo-cleanme", "cleanme", "config", "show"])),
argv(&["cargo-cleanme", "config", "show"])
);
assert_eq!(
normalize_cargo_argv(argv(&["cargo-cleanme", "cleanme", "clean", "/x", "--yes"])),
argv(&["cargo-cleanme", "clean", "/x", "--yes"])
);
}
#[test]
fn later_literal_cleanme_values_are_preserved() {
assert_eq!(
normalize_cargo_argv(argv(&["cargo-cleanme", "scan", "cleanme"])),
argv(&["cargo-cleanme", "scan", "cleanme"])
);
assert_eq!(
normalize_cargo_argv(argv(&["cargo-cleanme", "cleanme", "scan", "cleanme"])),
argv(&["cargo-cleanme", "scan", "cleanme"])
);
assert_eq!(
normalize_cargo_argv(argv(&["cargo-cleanme", "clean", "./cleanme", "--yes"])),
argv(&["cargo-cleanme", "clean", "./cleanme", "--yes"])
);
}
#[test]
fn help_and_version_forms_normalize() {
assert_eq!(
normalize_cargo_argv(argv(&["cargo-cleanme", "cleanme", "--help"])),
argv(&["cargo-cleanme", "--help"])
);
assert_eq!(
normalize_cargo_argv(argv(&["cargo-cleanme", "cleanme", "--version"])),
argv(&["cargo-cleanme", "--version"])
);
assert_eq!(
normalize_cargo_argv(argv(&["cargo-cleanme", "cleanme", "clean", "--help"])),
argv(&["cargo-cleanme", "clean", "--help"])
);
}
#[test]
fn direct_and_external_forms_parse_equivalently() {
for (direct, external) in [
(
argv(&["cargo-cleanme"]),
argv(&["cargo-cleanme", "cleanme"]),
),
(
argv(&["cargo-cleanme", "scan", "/x"]),
argv(&["cargo-cleanme", "cleanme", "scan", "/x"]),
),
(
argv(&["cargo-cleanme", "--dry-run"]),
argv(&["cargo-cleanme", "cleanme", "--dry-run"]),
),
(
argv(&["cargo-cleanme", "scan", "--known"]),
argv(&["cargo-cleanme", "cleanme", "scan", "--known"]),
),
(
argv(&["cargo-cleanme", "config", "path"]),
argv(&["cargo-cleanme", "cleanme", "config", "path"]),
),
(
argv(&["cargo-cleanme", "clean", "/x"]),
argv(&["cargo-cleanme", "cleanme", "clean", "/x"]),
),
] {
let a = Cli::try_parse_from(normalize_cargo_argv(direct)).unwrap();
let b = Cli::try_parse_from(normalize_cargo_argv(external)).unwrap();
assert_eq!(
a.invocation(),
b.invocation(),
"direct and external forms must agree"
);
}
}
#[test]
fn config_init_is_removed_and_edit_parses() {
assert!(Cli::try_parse_from(["cargo-cleanme", "config", "init"]).is_err());
assert!(Cli::try_parse_from(["cargo-cleanme", "config", "edit"]).is_ok());
}
#[test]
fn absolute_root_is_stable() {
let absolute = if cfg!(windows) {
PathBuf::from(r"C:\projects")
} else {
PathBuf::from("/projects")
};
assert_eq!(absolutize_root(&absolute).unwrap(), absolute);
}
#[test]
fn relative_root_becomes_absolute() {
let cwd = std::env::current_dir().unwrap();
let joined = absolutize_root(Path::new("./project")).unwrap();
assert!(joined.is_absolute());
assert_eq!(joined, cwd.join("project"));
let dotdot = absolutize_relative(Path::new("/a/b"), Path::new("c/../d"));
assert_eq!(dotdot, PathBuf::from("/a/b/d"));
let up = absolutize_relative(Path::new("/a/b"), Path::new("../outside"));
assert_eq!(up, PathBuf::from("/a/outside"));
let rooted = absolutize_relative(Path::new("/a"), Path::new("../../x"));
assert_eq!(rooted, PathBuf::from("/x"));
}
#[test]
fn no_progress_flag_parses_globally() {
let c = Cli::try_parse_from(["cargo-cleanme", "--no-progress", "scan", "/tmp"]).unwrap();
assert!(c.no_progress);
let c = Cli::try_parse_from(["cargo-cleanme", "scan", "/tmp"]).unwrap();
assert!(!c.no_progress);
let c = Cli::try_parse_from(["cargo-cleanme", "--no-progress"]).unwrap();
assert!(c.no_progress);
assert!(matches!(
c.invocation(),
Invocation::Cleanup(CleanupRequest { .. })
));
}
#[test]
fn stats_flag_parses_globally_in_direct_and_external_forms() {
// C002 ยง7.8: `--stats` is additive and global.
let c = Cli::try_parse_from(["cargo-cleanme", "--stats", "scan", "/tmp"]).unwrap();
assert!(c.stats);
let c = Cli::try_parse_from(["cargo-cleanme", "scan", "/tmp"]).unwrap();
assert!(!c.stats);
let c = Cli::try_parse_from(["cargo-cleanme", "--no-progress", "--stats", "scan", "/tmp"])
.unwrap();
assert!(c.no_progress);
assert!(c.stats);
// Clean modes.
for args in [
vec!["cargo-cleanme", "clean", "/x", "--stats"],
vec!["cargo-cleanme", "clean", "/x", "--dry-run", "--stats"],
vec!["cargo-cleanme", "clean", "/x", "--cargo-preview", "--stats"],
vec!["cargo-cleanme", "clean", "/x", "--yes", "--stats"],
] {
let c = Cli::try_parse_from(args.clone()).unwrap();
assert!(c.stats, "{args:?}");
}
// External subcommand forms.
for args in [
vec!["cargo-cleanme", "cleanme", "--stats", "scan", "/x"],
vec!["cargo-cleanme", "cleanme", "clean", "/x", "--stats"],
vec![
"cargo-cleanme",
"cleanme",
"--no-progress",
"--stats",
"scan",
"/x",
],
] {
let normalized: Vec<OsString> = args.iter().map(OsString::from).collect::<Vec<_>>();
let parsed = Cli::try_parse_from(normalize_cargo_argv(normalized)).unwrap();
assert!(parsed.stats, "{args:?}");
}
}
}