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
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
//! aube's command layer as a library.
//!
//! The `aube` / `aubr` / `aubx` binaries are thin wrappers over
//! [`cli_main`]; everything else lives here so the command layer can be
//! embedded by other tools — e.g. constructing
//! [`embed::InstallOptions`] and calling [`embed::install`] in-process instead
//! of shelling out to the CLI. Embedding hosts should use [`embed`], which is
//! the stable facade over the lower-level [`commands`] modules. [`cli_args`]
//! and [`cli_main`] remain public for hosts that wrap aube's complete CLI.
//!
//! The library makes no global-allocator choice — the mimalloc opt-in
//! lives in `src/main.rs` so embedders keep control of their own
//! allocator.
mod argv;
pub mod cli_args;
pub mod command_effects;
pub mod commands;
mod dep_chain;
mod deprecations;
mod dirs;
pub mod embed;
mod engines;
mod patches;
mod pnpmfile;
mod process_guard;
mod progress;
mod runtime;
mod self_version;
mod startup;
mod state;
mod tool_shims;
mod update_check;
mod version;
use argv::{extract_config_overrides, lift_per_subcommand_flags, rewrite_multicall_argv};
use clap::{Parser, Subcommand, ValueEnum};
use miette::{Context, IntoDiagnostic};
use startup::{
ColorMode, PackageManagerGuard, ci_renders_ansi, command_needs_package_manager_guard,
compute_effective_filter, diag_config_from_flag, enforce_package_manager_guardrails,
env_disables_color, init_logging, load_startup_settings, raise_nofile_limit,
resolve_color_mode, resolve_loglevel, startup_cwd,
};
#[cfg(test)]
use startup::{PackageManagerGuardMode, PackageManagerStrictMode, package_manager_guard_mode};
use std::ffi::OsString;
use std::path::PathBuf;
#[derive(Parser)]
#[command(
name = "aube",
about = "A fast Node.js package manager",
version = version::VERSION_LONG.as_str(),
disable_version_flag = true
)]
pub(crate) struct Cli {
/// Change to directory before running (like `make -C` or `mise --cd`)
#[arg(short = 'C', long = "dir", visible_aliases = ["cd", "prefix"], global = true, value_name = "DIR")]
dir: Option<std::path::PathBuf>,
/// Scope command execution to workspace packages matching PATTERN.
///
/// Supports exact names (`my-pkg`), globs (`@scope/*`, `*-plugin`),
/// paths (`./packages/api`), graph selectors (`pkg...`, `...pkg`),
/// git-ref selectors (`[origin/main]`), and exclusions (`!pkg`).
/// Repeatable; matches are OR-ed.
///
/// Currently honored by `run`, `test`, `start`, `stop`, `restart`,
/// `install`, `exec`, `list`, `publish`, `deploy`, `add`, `remove`,
/// `update`, `why`, and implicit-script invocations.
#[arg(short = 'F', long, global = true, value_name = "WORKSPACE")]
filter: Vec<String>,
/// Run the command across every workspace package.
///
/// Equivalent to `--filter=*`; if `--filter` is also given,
/// `--recursive` is a no-op and the explicit filter wins. Honored
/// by the same commands as `--filter`.
#[arg(short = 'r', long, global = true)]
recursive: bool,
/// Enable verbose/debug logging (shortcut for `--loglevel debug`)
#[arg(short, long, global = true)]
verbose: bool,
/// Print version and check for updates.
///
/// Manual flag so we can run the async update notifier alongside
/// the version print — clap's auto `Action::Version` exits inside
/// `parse_from`, before the tokio runtime is built.
#[arg(short = 'V', long = "version", global = true)]
version: bool,
/// Group workspace command output after each package finishes.
///
/// Accepted for pnpm compatibility; aube's workspace fanout is
/// currently sequential, so output is already grouped.
#[arg(long, global = true, conflicts_with = "stream", hide = true)]
aggregate_output: bool,
/// Force colored output even when stderr is not a TTY.
///
/// Overrides `NO_COLOR` / `CLICOLOR=0`. Mutually exclusive with
/// `--no-color`.
#[arg(long, global = true, conflicts_with = "no_color")]
color: bool,
/// Enable cold-install deep diagnostics. Modes:
/// summary — sum_ms / mean / max / %wall table at end
/// trace — summary + critical path + starvation + what-if + lifecycle
/// live — like trace, plus print every span >= 100ms to stderr live
/// full — like trace, plus write JSONL trace to a file (defaults to ./aube-diag.jsonl)
///
/// Quick form: `--diag` with no value defaults to `trace`.
/// Output file path can be set via `--diag-file`. Threshold for live
/// mode via `--diag-threshold-ms`.
#[arg(long, global = true, value_name = "MODE", num_args = 0..=1, default_missing_value = "trace")]
diag: Option<String>,
/// Path for `--diag full` JSONL trace (default: ./aube-diag.jsonl)
#[arg(long, global = true, value_name = "PATH")]
diag_file: Option<PathBuf>,
/// Live-mode threshold: only print spans whose duration is >= N ms (default 100).
#[arg(long, global = true, value_name = "MS")]
diag_threshold_ms: Option<u64>,
/// Error when a workspace selector matches no packages.
///
/// Accepted globally; selected commands already fail on empty matches.
#[arg(long, global = true)]
fail_if_no_match: bool,
/// Production-only variant of `--filter`.
///
/// Same selector grammar as `--filter`, but graph walks (`pkg...`,
/// `...pkg`) only follow `dependencies` / `optionalDependencies` /
/// `peerDependencies` edges — `devDependencies` (and packages
/// reachable solely through them) are skipped. Non-graph forms
/// (exact name, glob, path, `[git-ref]`) behave identically to
/// `--filter`. Repeatable; can be combined with `--filter`.
#[arg(long, global = true, value_name = "PATTERN")]
filter_prod: Vec<String>,
/// Ignore workspace discovery for commands that support workspace fanout.
///
/// Parsed for pnpm compatibility.
#[arg(long, global = true, hide = true)]
ignore_workspace: bool,
/// Include the workspace root in recursive workspace operations.
///
/// Parsed for pnpm compatibility.
#[arg(long, global = true, hide = true)]
include_workspace_root: bool,
/// Set the log level. Logs at or above this level are shown.
#[arg(long, global = true, value_name = "LEVEL", value_enum)]
loglevel: Option<LogLevel>,
/// Disable colored output.
///
/// Overrides `FORCE_COLOR` / `CLICOLOR_FORCE` and sets `NO_COLOR=1`
/// so downstream libraries (miette, clx, child processes) all see
/// the same choice.
#[arg(long, global = true)]
no_color: bool,
/// Output format: default, append-only, ndjson, silent.
///
/// `default` renders the progress UI when stderr is a TTY;
/// `append-only` disables the progress UI in favor of plain
/// line-at-a-time logs; `ndjson` swaps the tracing fmt layer for
/// the JSON formatter (one JSON object per log event on stderr)
/// and is what tooling wrappers should consume; `silent`
/// suppresses all non-error output (alias for `--loglevel silent`).
#[arg(long, global = true, value_name = "NAME", value_enum)]
reporter: Option<ReporterType>,
/// Suppress all non-error output (alias for `--loglevel silent`)
#[arg(long, global = true)]
silent: bool,
/// Stream workspace command output as each child process writes it.
///
/// Accepted for pnpm compatibility; aube's workspace fanout is
/// currently sequential.
#[arg(long, global = true, conflicts_with = "aggregate_output", hide = true)]
stream: bool,
/// Route lifecycle and workspace command output through stderr.
///
/// Accepted for pnpm compatibility.
#[arg(long, global = true, hide = true)]
use_stderr: bool,
/// Prefer workspace packages when resolving dependencies.
///
/// Parsed for pnpm compatibility; aube already resolves workspace
/// packages when a workspace is present.
#[arg(long, global = true, hide = true)]
workspace_packages: bool,
/// Run from the workspace root regardless of the current package.
#[arg(long, global = true)]
workspace_root: bool,
/// Automatically answer yes to prompts.
///
/// Parsed for pnpm compatibility; aube does not currently prompt
/// on these paths.
#[arg(short = 'y', long, global = true, hide = true)]
yes: bool,
#[command(subcommand)]
command: Option<Commands>,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
#[clap(rename_all = "lowercase")]
pub(crate) enum LogLevel {
Trace,
Debug,
Info,
Warn,
Error,
Silent,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
#[clap(rename_all = "kebab-case")]
pub(crate) enum ReporterType {
Default,
AppendOnly,
Ndjson,
Silent,
}
impl LogLevel {
fn filter(self) -> &'static str {
match self {
LogLevel::Trace => "trace",
LogLevel::Debug => "debug",
LogLevel::Info => "info",
LogLevel::Warn => "warn",
LogLevel::Error => "error",
LogLevel::Silent => "off",
}
}
}
/// Redirects stderr (fd 2) to `/dev/null` for its lifetime, restoring the
/// original on drop. Used by `--silent` to suppress the ~230 direct
/// `eprintln!` calls scattered across command implementations without
/// rewriting them all. The guard must be dropped *before* `main` returns
/// so that any `miette` error report bubbled up through `?` is printed to
/// the real stderr. Stdout is left alone — `aube --silent config get foo`
/// should still emit data to a pipe.
struct SilentStderrGuard {
saved: libc::c_int,
}
impl SilentStderrGuard {
fn install() -> Option<Self> {
unsafe {
let saved = libc::dup(2);
if saved < 0 {
return None;
}
let devnull = libc::open(c"/dev/null".as_ptr(), libc::O_WRONLY);
if devnull < 0 {
libc::close(saved);
return None;
}
if libc::dup2(devnull, 2) < 0 {
libc::close(devnull);
libc::close(saved);
return None;
}
libc::close(devnull);
Some(Self { saved })
}
}
}
impl Drop for SilentStderrGuard {
fn drop(&mut self) {
unsafe {
libc::dup2(self.saved, 2);
libc::close(self.saved);
}
}
}
// Commands are listed in alphabetical order; validated by
// `cli_ordering_tests::test_cli_ordering`. Per-command arg fields are
// similarly sorted: positional first, then short flags by short option,
// then long-only flags alphabetically. The `External` catch-all is last
// because clap's external_subcommand must come after named variants; it
// has no fixed name so the sort check skips it.
#[derive(Subcommand)]
enum Commands {
/// Bootstrap aube's cached node-gyp and print the executable path.
#[command(name = "__node-gyp-bootstrap", hide = true)]
NodeGypBootstrap { project_dir: PathBuf },
/// Manage package access and visibility on the registry
Access(commands::access::AccessArgs),
/// Emit shell activation code for runtime tool shims
Activate(commands::activate::ActivateArgs),
/// Add a dependency
#[command(visible_alias = "a")]
Add(commands::add::AddArgs),
/// Approve ignored dependency build scripts.
///
/// Writes entries under `allowBuilds` in `aube-workspace.yaml` (or
/// `pnpm-workspace.yaml` if present).
ApproveBuilds(commands::approve_builds::ApproveBuildsArgs),
/// Check installed packages against the registry advisory DB
#[command(after_long_help = commands::audit::AFTER_LONG_HELP)]
Audit(commands::audit::AuditArgs),
/// Print the path to `node_modules/.bin`
#[command(after_long_help = commands::bin::AFTER_LONG_HELP)]
Bin(commands::bin::BinArgs),
/// Open package bug tracker URLs
#[command(visible_alias = "issues", after_long_help = commands::bugs::AFTER_LONG_HELP)]
Bugs(commands::bugs::BugsArgs),
/// Inspect and manage the packument metadata cache
Cache(commands::cache::CacheArgs),
/// Print a file from the global store by integrity or hex hash
CatFile(commands::cat_file::CatFileArgs),
/// Print the cached package index JSON for `<name>@<version>`
CatIndex(commands::cat_index::CatIndexArgs),
/// Verify installed packages can resolve their declared deps.
///
/// Walks the `node_modules/` symlink tree and confirms every
/// dependency in each `package.json` resolves to a real entry.
#[command(after_long_help = commands::check::AFTER_LONG_HELP)]
Check(commands::check::CheckArgs),
/// Clean install: delete node_modules, then install with frozen lockfile.
///
/// Use in CI to guarantee a reproducible install from the committed lockfile.
#[command(visible_alias = "clean-install", aliases = ["ic", "install-clean"])]
Ci(commands::ci::CiArgs),
/// Remove `node_modules` across every workspace project.
///
/// `--lockfile` / `-l` also deletes lockfiles. A `clean` script in
/// the root `package.json` overrides the built-in.
Clean(commands::clean::CleanArgs),
/// Generate shell completions (bash, zsh, fish)
Completion(commands::completion::CompletionArgs),
/// Read and write settings in `.npmrc`
#[command(alias = "c")]
Config(commands::config::ConfigArgs),
/// Scaffold a project from a `create-*` starter kit (via dlx)
Create(commands::create::CreateArgs),
/// Re-resolve the lockfile to collapse duplicate versions
Dedupe(commands::dedupe::DedupeArgs),
/// Deploy a workspace package into a target directory with deps inlined
Deploy(commands::deploy::DeployArgs),
/// Mark published versions of a package as deprecated on the registry
Deprecate(commands::deprecate::DeprecateArgs),
/// Report deprecated packages in the resolved dependency graph
Deprecations(commands::deprecations::DeprecationsArgs),
/// Diagnostic trace analysis (compare/analyze JSONL traces)
Diag(commands::diag::DiagArgs),
/// Manage package distribution tags on the registry
#[command(visible_alias = "dist-tags")]
DistTag(commands::dist_tag::DistTagArgs),
/// Fetch a package into a throwaway environment and run its binary
Dlx(commands::dlx::DlxArgs),
/// Run broad install-health diagnostics
#[command(after_long_help = commands::doctor::AFTER_LONG_HELP)]
Doctor(commands::doctor::DoctorArgs),
/// Execute a locally installed binary
#[command(visible_alias = "x")]
Exec(commands::exec::ExecArgs),
/// Download lockfile dependencies into the store without linking node_modules
Fetch(commands::fetch::FetchArgs),
/// List packages whose cached index references a given file hash
#[command(after_long_help = commands::find_hash::AFTER_LONG_HELP)]
FindHash(commands::find_hash::FindHashArgs),
/// Alias for `config get` (hidden; prefer `config get`)
#[command(hide = true)]
Get(commands::config::GetArgs),
/// Print packages whose install scripts were skipped by `pnpm.allowBuilds`
#[command(after_long_help = commands::ignored_builds::AFTER_LONG_HELP)]
IgnoredBuilds(commands::ignored_builds::IgnoredBuildsArgs),
/// Convert a supported lockfile into aube-lock.yaml
Import(commands::import::ImportArgs),
/// Create a `package.json` in the current directory
Init(commands::init::InitArgs),
/// Install all dependencies
#[command(alias = "i")]
Install(commands::install::InstallArgs),
/// Install dependencies, then run the `test` script (pnpm compat alias).
///
/// Hidden from help because `aube test` already auto-installs.
#[command(alias = "it", hide = true)]
InstallTest(commands::run::ScriptArgs),
/// Alias for `list --long` (hidden; prefer `list --long`)
#[command(hide = true)]
La(commands::list::ListArgs),
/// Report the licenses of installed dependencies
#[command(after_long_help = commands::licenses::AFTER_LONG_HELP)]
Licenses(commands::licenses::LicensesArgs),
/// Link a local package globally, or into the current project
#[command(visible_alias = "ln")]
Link(commands::link::LinkArgs),
/// Print the resolved dependency tree
#[command(visible_alias = "ls", after_long_help = commands::list::AFTER_LONG_HELP)]
List(commands::list::ListArgs),
/// Alias for `list --long` (hidden; prefer `list --long`)
#[command(hide = true)]
Ll(commands::list::ListArgs),
/// Store a registry auth token in the user's ~/.npmrc
#[command(alias = "adduser")]
Login(commands::login::LoginArgs),
/// Remove a registry auth token from the user's ~/.npmrc
Logout(commands::logout::LogoutArgs),
/// Run Node.js through aube's project runtime resolver
#[command(disable_help_flag = true, disable_version_flag = true)]
Node(commands::node::NodeArgs),
/// Report dependencies whose installed version lags behind the registry
#[command(after_long_help = commands::outdated::AFTER_LONG_HELP)]
Outdated(commands::outdated::OutdatedArgs),
/// Manage package owners (not implemented — use `npm owner`)
#[command(hide = true)]
Owner(commands::npm_fallback::FallbackArgs),
/// Create a publishable `.tgz` tarball from the current project
Pack(commands::pack::PackArgs),
/// Extract a package into an edit directory so it can be patched
Patch(commands::patch::PatchArgs),
/// Generate a `.patch` file from a `aube patch` edit directory
PatchCommit(commands::patch_commit::PatchCommitArgs),
/// Remove patch entries from `pnpm.patchedDependencies`
PatchRemove(commands::patch_remove::PatchRemoveArgs),
/// Inspect peer-dependency resolution from the lockfile
Peers(commands::peers::PeersArgs),
/// Manage package.json entries (not implemented — use `npm pkg`)
#[command(hide = true)]
Pkg(commands::npm_fallback::FallbackArgs),
/// Print the current package prefix directory
#[command(after_long_help = commands::prefix::AFTER_LONG_HELP)]
Prefix(commands::prefix::PrefixArgs),
/// Remove extraneous packages from project `node_modules`.
///
/// Reads the lockfile, computes the packages still reachable from each
/// importer, and removes stale top-level links, stale virtual-store entries,
/// and dangling .bin links. Does not modify package.json or the lockfile.
#[command(after_long_help = commands::prune::AFTER_LONG_HELP)]
Prune(commands::prune::PruneArgs),
/// Publish the current package to the registry
#[cfg(feature = "publish")]
Publish(commands::publish::PublishArgs),
/// Alias for `clean` — remove `node_modules` across every workspace project.
///
/// A `purge` script in the root `package.json` overrides the built-in.
Purge(commands::clean::CleanArgs),
/// Query packages in the resolved dependency graph
#[command(after_long_help = commands::query::AFTER_LONG_HELP)]
Query(commands::query::QueryArgs),
/// Re-run root lifecycle scripts and allowlisted dependency builds
#[command(visible_alias = "rb")]
Rebuild(commands::rebuild::RebuildArgs),
/// Run a supported command across workspace packages
#[command(visible_aliases = ["multi", "m"])]
Recursive(commands::recursive::RecursiveArgs),
/// Remove a dependency
#[command(visible_alias = "rm", aliases = ["uninstall", "un", "uni"])]
Remove(commands::remove::RemoveArgs),
/// Restart a package (shortcut for `run restart`; falls back to `stop` + `start`)
Restart(commands::run::ScriptArgs),
/// Print the path to `node_modules`
#[command(after_long_help = commands::root::AFTER_LONG_HELP)]
Root(commands::root::RootArgs),
/// Run a script defined in package.json
#[command(alias = "run-script")]
Run(commands::run::RunArgs),
/// Manage the project's Node.js runtime (pin, install, inspect)
#[command(visible_alias = "rt")]
Runtime(commands::runtime::RuntimeArgs),
/// Generate a Software Bill of Materials (CycloneDX or SPDX)
Sbom(commands::sbom::SbomArgs),
/// Search the registry for packages (not implemented — use `npm search`)
#[command(hide = true)]
Search(commands::npm_fallback::FallbackArgs),
/// Alias for `config set` (hidden; prefer `config set`)
#[command(hide = true)]
Set(commands::config::SetArgs),
/// Set a `package.json` script (not implemented — use `npm set-script`)
#[command(hide = true, name = "set-script")]
SetScript(commands::npm_fallback::FallbackArgs),
/// Show the companies sponsoring aube and the jdx.dev open source tools
Sponsors(commands::sponsors::SponsorsArgs),
/// Stage packages for publishing (not implemented — use `npm stage`)
Stage(commands::npm_fallback::FallbackArgs),
/// Start a package (shortcut for `run start`)
Start(commands::run::ScriptArgs),
/// Stop a package (shortcut for `run stop`)
Stop(commands::run::ScriptArgs),
/// Manage the global store
Store(commands::store::StoreArgs),
/// Run the `test` script (shortcut for `run test`)
#[command(visible_alias = "t")]
Test(commands::run::ScriptArgs),
/// Manage registry auth tokens (not implemented — use `npm token`)
#[command(hide = true)]
Token(commands::npm_fallback::FallbackArgs),
/// Inspect npm package publishing trust
Trust(commands::trust::TrustArgs),
/// Clear an existing deprecation on the registry
Undeprecate(commands::undeprecate::UndeprecateArgs),
/// Unlink a package (remove linked entries from node_modules)
#[command(alias = "dislink")]
Unlink(commands::unlink::UnlinkArgs),
/// Remove a package (or a single version) from the registry
Unpublish(commands::unpublish::UnpublishArgs),
/// Update dependencies
#[command(aliases = ["up", "upgrade"])]
Update(commands::update::UpdateArgs),
/// Bump the version in package.json (and optionally create a git commit + tag)
Version(commands::version::VersionArgs),
/// Print package metadata from the registry
#[command(visible_aliases = ["info", "show"], alias = "v", after_long_help = commands::view::AFTER_LONG_HELP)]
View(commands::view::ViewArgs),
/// Report the current registry user (not implemented — use `npm whoami`)
#[command(hide = true)]
Whoami(commands::npm_fallback::FallbackArgs),
/// Print reverse dependency chains explaining why a package is installed
#[command(visible_alias = "w", after_long_help = commands::why::AFTER_LONG_HELP)]
Why(commands::why::WhyArgs),
/// Catch-all for implicit script execution (e.g., `aube dev` = `aube run dev`)
#[command(external_subcommand)]
External(Vec<String>),
}
/// Library entry point. An embedder calls this with its own `&'static
/// Embedder` (and optional setting defaults); the `aube` binary passes
/// `&aube_util::AUBE` and no defaults, reproducing standalone behavior.
/// This is the whole embedding API: register-then-run in one call, so a host
/// never has to separately wire identity and defaults.
///
/// **Returns the exit code; it does not terminate the process.** It parses
/// argv, runs the selected command, renders any diagnostic to stderr, and
/// hands back the code the binary's `main` should exit with. Returning rather
/// than calling `std::process::exit` keeps it embed-safe: a host that drives
/// it in-process is not hard-killed by a non-zero result or an error. The
/// standalone binary does `std::process::exit(cli_main(..))`.
///
/// `#[must_use]`: the `i32` is the exit code, not a side effect. An
/// embedder migrating off the old `process::exit` entrypoint that drops
/// it would silently exit 0 on every failure — Rust won't warn on an
/// ignored return — so the lint nudges them to
/// `std::process::exit(cli_main(..))`.
#[must_use]
pub fn cli_main(embedder: &'static aube_util::Embedder) -> i32 {
cli_main_with_defaults(embedder, Vec::new())
}
/// The clap [`Command`](clap::Command) for the CLI, with its version reset to
/// the plain package version (stripping the `-DEBUG` runtime suffix) so any
/// derived artifact stays byte-stable across profiles. This exposes the
/// command surface itself — not aube's own `usage` KDL subcommand, which is
/// aube-specific tooling that lives in the binary (`src/main.rs`), not in the
/// embeddable command layer. A downstream embedder builds its own top-level
/// usage/completions from this.
pub fn command() -> clap::Command {
use clap::CommandFactory;
Cli::command().version(env!("CARGO_PKG_VERSION"))
}
/// [`cli_main`] plus embedder-supplied setting defaults. The `defaults` are
/// `(canonical_setting_name, raw_value)` pairs registered at the lowest
/// precedence tier — below every user- and project-level source — for the
/// genuinely user-overridable knobs an embedder wants to re-default.
/// (Embedder-*fixed* behavior lives on [`aube_util::Embedder`] itself, not
/// here.) Standalone aube passes an empty vec, so per-setting built-in
/// defaults apply unchanged.
///
/// `#[must_use]` for the same reason as [`cli_main`]: the returned `i32`
/// is the exit code the embedder must hand to `std::process::exit`.
#[must_use]
pub fn cli_main_with_defaults(
embedder: &'static aube_util::Embedder,
defaults: Vec<(String, String)>,
) -> i32 {
// Register the binary's embedder profile before anything reads branding,
// and its setting defaults before anything resolves settings. Both are
// idempotent — a no-op if already set (e.g. a test harness that
// registered one first).
aube_util::set_embedder(embedder);
aube_settings::set_embedder_defaults(defaults);
// Two-phase wrapper: `inner_main` runs the real CLI and returns
// `Result<i32, miette::Report>` — the command's exit code on Ok. On
// Err we render via miette's fancy handler (matching the previous
// `Termination` behavior), then look up the diagnostic's `code()`
// against `aube_codes::exit::EXIT_TABLE` to pick a bespoke exit code.
// Codes outside the table fall through to `EXIT_GENERIC` (1).
//
// Chain a panic hook that flushes the diag buffer before the
// default hook prints the panic. Without this, a debug-build panic
// (release uses `panic = "abort"` so the hook would not run anyway)
// would lose the BufWriter's 64 KiB tail and any unflushed events.
let prev_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
aube_util::diag::flush();
prev_hook(info);
}));
let result = inner_main();
aube_util::diag::flush();
// Drain any in-flight slow-metadata group whose debounce window
// hasn't fired yet. install pipelines also flush at end-of-resolve
// (for in-progress UX), but non-install commands — `aube add`,
// `aube audit`, `aube deprecate`, `aube deprecations`, `aube view`,
// etc. — never hit that path and would otherwise silently lose
// their slow-fetch warnings to the accumulator.
aube_registry::slow_metadata::flush_summary();
// Return the exit code rather than terminating: only the binary's
// `main` calls `std::process::exit`, so a host embedding the command
// layer in-process isn't hard-killed by a non-zero result or an
// error. The diagnostic still renders to stderr here (matching the
// previous `Termination` behavior); only the exit itself moves out.
match result {
Ok(code) => code,
Err(report) => {
eprintln!("{report:?}");
report_exit_code(&report)
}
}
}
/// Resolve a diagnostic's exit code by walking its `code()` chain.
/// Falls back to `EXIT_GENERIC` (1) when no `code` is set or the
/// reported code has no entry in `aube_codes::exit::EXIT_TABLE`.
fn report_exit_code(report: &miette::Report) -> i32 {
if let Some(code) = report.code() {
let code = code.to_string();
if let Some(exit) = aube_codes::exit::exit_code_for(&code) {
return exit;
}
}
aube_codes::exit::EXIT_GENERIC
}
fn inner_main() -> miette::Result<i32> {
let mut argv: Vec<OsString> = std::env::args_os().collect();
// pnpm-compat: pull `--config.<key>[=<value>]` out of argv before
// clap parses it. Stripping here means the rest of the binary sees
// a clean argv, and the parsed pairs feed every `ResolveCtx::cli`
// through the process-global slot in `aube_settings`.
let config_overrides = extract_config_overrides(&mut argv);
aube_settings::set_global_cli_overrides(config_overrides);
// Shell activation prepends aube's shim dir so `node` / `pnpm` /
// `yarn` resolve to this binary. Once aube is running, scrub that
// directory before any runtime probe or child spawn can recursively
// rediscover the shim as the "real" tool.
tool_shims::sanitize_process_path();
// Override the clap command name at runtime with the active embedder's
// name. The `#[command(name = "aube")]` attribute is a compile-time
// constant and can't read `embedder()`, so help/usage/error output would
// otherwise always say "aube" even under an embedder. `get_matches_from`
// keeps clap's parse-error / `--help` / `--version` print-and-exit
// behavior, matching the previous `parse_from`.
let cli = {
use clap::{CommandFactory, FromArgMatches};
let matches = Cli::command()
.name(aube_util::embedder().name)
.get_matches_from(lift_per_subcommand_flags(rewrite_multicall_argv(argv)));
Cli::from_arg_matches(&matches).unwrap_or_else(|e| e.exit())
};
// Shell-completion probes return here — ahead of every piece of startup
// that would either cost a TAB press real time or swallow the candidate
// list outright:
//
// - `useStderr` dup2s stdout onto stderr, and `usage` reads the
// child's stdout, so the completions would vanish;
// - `self_version::maybe_switch` can download and re-exec a
// different aube for a keypress;
// - `enforce_package_manager_guardrails` hard-errors in a project
// that pins a different package manager.
//
// None of those are things a completion helper should do.
//
// `-C` is honored explicitly, since the chdir that normally applies it
// happens further down: completing `aube -C packages/api run <TAB>`
// has to offer that package's scripts, not the shell's cwd's.
if let Some(Commands::Run(args)) = cli.command.as_ref()
&& args.complete
{
commands::run::print_script_completions(cli.dir.as_deref());
return Ok(0);
}
if let Some(Commands::Completion(args)) = cli.command.as_ref()
&& args.is_probe()
{
// Package search is async, but a completion probe does not need the
// full multi-thread runtime and blocking pool used by installs.
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.into_diagnostic()
.wrap_err("failed to build completion runtime")?;
runtime.block_on(args.run_probe(cli.dir.as_deref()));
return Ok(0);
}
// `--color` / `--no-color` take effect before anything else touches
// color state: we translate the flags into the env vars that miette,
// clx, `supports-color`, and spawned child processes all already
// consult, so the choice is consistent across every output path and
// inherits into `run` / `exec` / lifecycle scripts. The explicit flag
// wins over whatever was in the environment — that's what pnpm does.
//
// This has to happen *before* we build the Tokio runtime: the Rust
// 2024 contract on `std::env::set_var` requires that no other
// threads exist, and a multi-threaded runtime spawns its worker
// pool during `build()`. So we keep `main` synchronous, mutate env
// here, and only then enter the async body.
let color_mode = resolve_color_mode(&cli);
if matches!(color_mode, ColorMode::Never) {
// SAFETY: single-threaded `main` — no other threads exist yet.
unsafe {
std::env::set_var("NO_COLOR", "1");
std::env::remove_var("FORCE_COLOR");
std::env::remove_var("CLICOLOR_FORCE");
}
} else if matches!(color_mode, ColorMode::Always) {
// SAFETY: single-threaded `main` — no other threads exist yet.
unsafe {
std::env::set_var("FORCE_COLOR", "1");
std::env::set_var("CLICOLOR_FORCE", "1");
std::env::remove_var("NO_COLOR");
}
} else if ci_renders_ansi() && !env_disables_color() {
// Auto + a CI runner whose log viewer renders ANSI, and the
// user hasn't opted out via NO_COLOR / CLICOLOR=0: stderr isn't
// a TTY so console/clx would default to plain text. Flip color
// on for stderr only via console's per-stream override — that's
// the stream the install progress heartbeat writes to.
// Deliberately *not* setting FORCE_COLOR / CLICOLOR_FORCE:
// those are process-wide and would also colorize stdout (e.g.
// `aube view --json > out.json` baking escapes into the file)
// and propagate into lifecycle scripts.
console::set_colors_enabled_stderr(true);
}
// `--use-stderr` / `.npmrc` `useStderr=true`: redirect stdout to stderr
// so all output goes through a single fd. Resolved here (single-threaded)
// before the tokio runtime spawns workers.
//
// Skip when `--silent` is active: the SilentStderrGuard later redirects
// fd 2 to /dev/null, and if we dup2 first, fd 1 would capture the real
// stderr and escape silencing.
let is_silent = cli.silent || matches!(cli.reporter, Some(ReporterType::Silent));
if !is_silent {
let use_stderr_active = cli.use_stderr
|| startup_cwd(&cli).ok().is_some_and(|cwd| {
let files = commands::FileSources::load(&cwd);
let ws = std::collections::BTreeMap::new();
let env_snap = aube_settings::values::capture_env();
aube_settings::resolved::use_stderr(&files.ctx(&ws, &env_snap, &[]))
});
if use_stderr_active {
// SAFETY: single-threaded `main` — no other threads exist yet.
// `dup2(stderr, stdout)` makes fd 1 point at the same file as fd 2.
unsafe {
libc::dup2(2, 1);
}
}
}
/*
* High core boxes don't need 64-128 worker threads for an I/O
* pipeline. Default worker_threads = num_cpus and
* max_blocking_threads = 512 are both wasteful. Cap workers at
* 8 (install semaphore already gates network).
*
* Blocking pool sits at 128, raised from 64 after diag traces
* showed AdaptiveLimit running 100+ concurrent tarball imports
* (each holding a blocking slot for gzip + tar + CAS write)
* while the linker is also fanning out hardlinks on the same
* pool. 64 was saturating, queueing late tarballs behind
* earlier finishers. 128 covers worst case fat tarball
* pipeline plus linker plus side effects.
*
* AUBE_TOKIO_WORKERS / AUBE_TOKIO_BLOCKING for benchmarking.
*/
let parse_env = |key: &str, default: usize| -> usize {
std::env::var(key)
.ok()
.and_then(|s| s.parse::<usize>().ok())
.filter(|n| *n > 0)
.unwrap_or(default)
};
let cpu_count = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(4);
let workers = parse_env("AUBE_TOKIO_WORKERS", cpu_count.min(8));
let blocking = parse_env("AUBE_TOKIO_BLOCKING", 128);
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(workers)
.max_blocking_threads(blocking)
.enable_all()
.build()
.into_diagnostic()
.wrap_err("failed to build tokio runtime")?;
let exit_code = runtime.block_on(async_main(cli))?;
drop(runtime);
// Return the command's exit code rather than terminating here: a
// non-zero result (e.g. `run`/`exec` propagating a child's status)
// must travel back up to the binary's `main`, which owns the single
// `std::process::exit`. Exiting here would hard-kill a host that
// embeds the command layer in-process. `None` means "no explicit
// code" — the normal success exit of 0.
Ok(exit_code.unwrap_or(0))
}
async fn async_main(cli: Cli) -> miette::Result<Option<i32>> {
// Default log level is `warn` so routine install output doesn't collide
// with the clx progress display. `-v` / `--verbose` and `--loglevel debug`
// turn on debug logging, and in that mode we also force clx into Text
// output so the progress UI never renders over the log lines. `--silent`
// (and `--loglevel silent`) turn logging off entirely and disable the
// progress UI.
// `--reporter=silent` is equivalent to `--silent`; all other reporter
// values leave the log level alone and only affect output routing.
if let Some(dir) = &cli.dir {
std::env::set_current_dir(dir)
.into_diagnostic()
.wrap_err_with(|| format!("failed to change directory to {}", dir.display()))?;
}
let print_top_level_version = should_print_top_level_version(&cli);
if cli.workspace_root && !print_top_level_version {
let start = std::env::current_dir()
.into_diagnostic()
.wrap_err("failed to read current dir")?;
let root = commands::find_workspace_root(&start)?;
if root != start {
std::env::set_current_dir(&root)
.into_diagnostic()
.wrap_err_with(|| format!("failed to change directory to {}", root.display()))?;
}
crate::dirs::set_cwd(&root)?;
}
let settings = load_startup_settings()?;
let effective_level = resolve_loglevel(&cli, settings.loglevel.as_deref());
init_logging(&cli, effective_level);
// `--silent` suppresses non-error stderr output from every command,
// including the ~230 direct `eprintln!` calls in command bodies. The
// guard restores fd 2 on drop (before main returns), so miette still
// prints error reports to the real stderr. We also register the
// saved fd with aube-scripts so child processes spawned via
// `aube_scripts::child_stderr()` (lifecycle scripts, `aube run`,
// `aube exec`, `aube dlx`) keep writing to the real terminal — only
// aube's own output is silenced, matching pnpm `--loglevel silent`.
// Install it before self-version handling, which can emit download
// progress even for a top-level version request.
let _silent_guard = matches!(effective_level, LogLevel::Silent)
.then(SilentStderrGuard::install)
.flatten();
if let Some(ref guard) = _silent_guard {
aube_scripts::set_saved_stderr_fd(guard.saved);
}
if print_top_level_version {
self_version::maybe_switch(&settings).await?;
println!("{}", crate::version::VERSION_LONG.as_str());
let cwd =
crate::dirs::project_root_or_cwd().unwrap_or_else(|_| std::path::PathBuf::from("."));
update_check::check_and_notify(&cwd).await;
return Ok(None);
}
// Skip diag init for the `diag` subcommand itself — the analyzer
// would otherwise truncate the JSONL file it's about to read.
if !matches!(cli.command, Some(Commands::Diag(_))) {
match diag_config_from_flag(&cli) {
Some(cfg_opt) => aube_util::diag::init_with_config(cfg_opt),
None => aube_util::diag::init(),
}
}
raise_nofile_limit();
commands::set_skip_auto_install_on_package_manager_mismatch(false);
if command_needs_package_manager_guard(cli.command.as_ref()) {
// Self-version switch first: when the project pins aube and
// the pinned version resolves, this re-execs and never
// returns. The guard below then only sees matching (or
// policy-softened) states.
self_version::maybe_switch(&settings).await?;
let guard = enforce_package_manager_guardrails(&settings, cli.command.as_ref())?;
commands::set_skip_auto_install_on_package_manager_mismatch(
guard == PackageManagerGuard::WarnRunOnly,
);
}
// `--recursive` / `-r` is sugar for `--filter=*`. When a filter is
// already set, `-r` is a no-op — the explicit scope wins.
let effective_filter = compute_effective_filter(&cli);
commands::set_global_output_flags(commands::GlobalOutputFlags {
ndjson: matches!(cli.reporter, Some(ReporterType::Ndjson)),
silent: matches!(effective_level, LogLevel::Silent),
});
match cli.command {
Some(Commands::NodeGypBootstrap { project_dir }) => {
commands::install::node_gyp_bootstrap::print_bootstrapped_binary(&project_dir).await?
}
Some(Commands::Access(args)) => commands::access::run(args).await?,
Some(Commands::Activate(args)) => commands::activate::run(args)?,
Some(Commands::Add(args)) => {
commands::add::run(args, effective_filter.clone()).await?;
}
Some(Commands::ApproveBuilds(args)) => commands::approve_builds::run(args).await?,
Some(Commands::Audit(args)) => {
if let Some(code) = commands::audit::run(args).await? {
return Ok(Some(code));
}
}
Some(Commands::Bin(args)) => commands::bin::run(args).await?,
Some(Commands::Bugs(args)) => commands::bugs::run(args).await?,
Some(Commands::Cache(args)) => commands::cache::run(args).await?,
Some(Commands::CatFile(args)) => commands::cat_file::run(args).await?,
Some(Commands::CatIndex(args)) => commands::cat_index::run(args).await?,
Some(Commands::Check(args)) => {
if let Some(code) = commands::check::run(args).await? {
return Ok(Some(code));
}
}
Some(Commands::Ci(args)) => commands::ci::run(args).await?,
Some(Commands::Clean(args)) => {
if let Some(code) = commands::clean::run(args).await? {
return Ok(Some(code));
}
}
Some(Commands::Completion(args)) => commands::completion::run(args).await?,
Some(Commands::Config(args)) => commands::config::run(args).await?,
Some(Commands::Create(args)) => {
if let Some(code) = commands::create::run(args).await? {
return Ok(Some(code));
}
}
Some(Commands::Dedupe(args)) => commands::dedupe::run(args).await?,
Some(Commands::Deploy(args)) => {
commands::deploy::run(args, effective_filter.clone()).await?
}
Some(Commands::Deprecate(args)) => commands::deprecate::run(args).await?,
Some(Commands::Deprecations(args)) => {
if let Some(code) = commands::deprecations::run(args).await? {
return Ok(Some(code));
}
}
Some(Commands::Diag(args)) => commands::diag::run(args).await?,
Some(Commands::DistTag(args)) => commands::dist_tag::run(args).await?,
Some(Commands::Dlx(args)) => {
if let Some(code) = commands::dlx::run(args).await? {
return Ok(Some(code));
}
}
Some(Commands::Doctor(args)) => {
if let Some(code) = commands::doctor::run(args).await? {
return Ok(Some(code));
}
}
Some(Commands::Exec(args)) => {
if let Some(code) = commands::exec::run(args, effective_filter.clone()).await? {
return Ok(Some(code));
}
}
Some(Commands::Fetch(args)) => commands::fetch::run(args).await?,
Some(Commands::FindHash(args)) => commands::find_hash::run(args).await?,
Some(Commands::Get(args)) => commands::config::get(args)?,
Some(Commands::IgnoredBuilds(args)) => commands::ignored_builds::run(args).await?,
Some(Commands::Import(args)) => commands::import::run(args).await?,
Some(Commands::Init(args)) => commands::init::run(args).await?,
Some(Commands::Install(args)) => {
run_install_command(args, effective_filter.clone(), cli.workspace_root).await?;
}
Some(Commands::InstallTest(args)) => {
if let Some(code) = commands::install_test::run(args).await? {
return Ok(Some(code));
}
}
Some(Commands::La(mut args)) | Some(Commands::Ll(mut args)) => {
args.long = true;
commands::list::run(args, effective_filter.clone()).await?;
}
Some(Commands::Licenses(args)) => commands::licenses::run(args).await?,
Some(Commands::Link(args)) => commands::link::run(args).await?,
Some(Commands::List(args)) => commands::list::run(args, effective_filter.clone()).await?,
Some(Commands::Login(args)) => commands::login::run(args).await?,
Some(Commands::Logout(args)) => commands::logout::run(args).await?,
Some(Commands::Node(args)) => {
if let Some(code) = commands::node::run(args).await? {
return Ok(Some(code));
}
}
Some(Commands::Outdated(args)) => {
if let Some(code) = commands::outdated::run(args, effective_filter.clone()).await? {
return Ok(Some(code));
}
}
Some(Commands::Owner(args)) => {
return Ok(Some(commands::npm_fallback::run("owner", &args)?));
}
Some(Commands::Pack(args)) => commands::pack::run(args).await?,
Some(Commands::Patch(args)) => commands::patch::run(args).await?,
Some(Commands::PatchCommit(args)) => commands::patch_commit::run(args).await?,
Some(Commands::PatchRemove(args)) => commands::patch_remove::run(args).await?,
Some(Commands::Peers(args)) => {
if let Some(code) = commands::peers::run(args).await? {
return Ok(Some(code));
}
}
Some(Commands::Pkg(args)) => {
return Ok(Some(commands::npm_fallback::run("pkg", &args)?));
}
Some(Commands::Prefix(args)) => commands::prefix::run(args).await?,
Some(Commands::Prune(args)) => commands::prune::run(args).await?,
#[cfg(feature = "publish")]
Some(Commands::Publish(args)) => {
commands::publish::run(args, effective_filter.clone()).await?
}
Some(Commands::Purge(args)) => {
if let Some(code) = commands::clean::run_purge(args).await? {
return Ok(Some(code));
}
}
Some(Commands::Query(args)) => commands::query::run(args, effective_filter.clone()).await?,
Some(Commands::Rebuild(args)) => {
commands::rebuild::run(args, effective_filter.clone()).await?
}
Some(Commands::Remove(args)) => {
commands::remove::run(args, effective_filter.clone()).await?
}
Some(Commands::Recursive(args)) => {
let argv = commands::recursive::argv(
args,
commands::recursive::RecursiveGlobals {
filters: effective_filter.clone(),
color: cli.color,
no_color: cli.no_color,
},
)?;
// The reconstructed argv may carry pre-subcommand-positioned
// flags that moved off `global = true` (e.g. `--registry`,
// `--frozen-lockfile`). Run the same lift-pass we use on the
// outer argv so the nested clap parse sees them after the
// subcommand.
let nested_argv: Vec<OsString> =
lift_per_subcommand_flags(argv.into_iter().map(OsString::from).collect());
let nested = Cli::try_parse_from(nested_argv).into_diagnostic()?;
let nested_filter = compute_effective_filter(&nested);
match nested.command {
Some(Commands::Add(args)) => {
commands::add::run(args, nested_filter).await?;
}
Some(Commands::Deploy(args)) => commands::deploy::run(args, nested_filter).await?,
Some(Commands::Exec(args)) => {
if let Some(code) = commands::exec::run(args, nested_filter).await? {
return Ok(Some(code));
}
}
Some(Commands::Install(args)) => {
run_install_command(args, nested_filter, nested.workspace_root).await?;
}
Some(Commands::List(args)) => commands::list::run(args, nested_filter).await?,
Some(Commands::La(mut args)) | Some(Commands::Ll(mut args)) => {
args.long = true;
commands::list::run(args, nested_filter).await?;
}
Some(Commands::Outdated(args)) => {
if let Some(code) = commands::outdated::run(args, nested_filter).await? {
return Ok(Some(code));
}
}
#[cfg(feature = "publish")]
Some(Commands::Publish(args)) => {
commands::publish::run(args, nested_filter).await?
}
Some(Commands::Rebuild(args)) => {
commands::rebuild::run(args, nested_filter).await?
}
Some(Commands::Remove(args)) => commands::remove::run(args, nested_filter).await?,
Some(Commands::Restart(args)) => {
if let Some(code) = commands::restart::run(args, nested_filter).await? {
return Ok(Some(code));
}
}
Some(Commands::Run(args)) => {
if let Some(code) = commands::run::run(args, nested_filter).await? {
return Ok(Some(code));
}
}
Some(Commands::Start(args)) => {
if let Some(code) = run_script_lifecycle("start", args, &nested_filter).await? {
return Ok(Some(code));
}
}
Some(Commands::Stop(args)) => {
if let Some(code) = run_script_lifecycle("stop", args, &nested_filter).await? {
return Ok(Some(code));
}
}
Some(Commands::Test(args)) => {
if let Some(code) = run_script_lifecycle("test", args, &nested_filter).await? {
return Ok(Some(code));
}
}
Some(Commands::Update(args)) => {
if let Some(code) = commands::update::run(args, nested_filter).await? {
return Ok(Some(code));
}
}
Some(Commands::Why(args)) => commands::why::run(args, nested_filter).await?,
Some(Commands::External(args)) => {
let script = &args[0];
let script_args: Vec<String> = args[1..].to_vec();
if let Some(code) = commands::run::run_script(
script,
&script_args,
false,
false,
&nested_filter,
)
.await?
{
return Ok(Some(code));
}
}
Some(_) | None => {
return Err(miette::miette!(
code = aube_codes::errors::ERR_AUBE_RECURSIVE_NOT_SUPPORTED,
"{} recursive: command does not support recursive execution",
aube_util::embedder().name,
));
}
}
}
Some(Commands::Restart(args)) => {
if let Some(code) = commands::restart::run(args, effective_filter.clone()).await? {
return Ok(Some(code));
}
}
Some(Commands::Root(args)) => commands::root::run(args).await?,
Some(Commands::Run(args)) => {
if let Some(code) = commands::run::run(args, effective_filter.clone()).await? {
return Ok(Some(code));
}
}
Some(Commands::Runtime(args)) => commands::runtime::run(args).await?,
Some(Commands::Sbom(args)) => commands::sbom::run(args).await?,
Some(Commands::Search(args)) => {
return Ok(Some(commands::npm_fallback::run("search", &args)?));
}
Some(Commands::Set(args)) => commands::config::set(args)?,
Some(Commands::SetScript(args)) => {
return Ok(Some(commands::npm_fallback::run("set-script", &args)?));
}
Some(Commands::Sponsors(args)) => commands::sponsors::run(args).await?,
Some(Commands::Stage(args)) => {
return Ok(Some(commands::npm_fallback::run("stage", &args)?));
}
Some(Commands::Start(args)) => {
if let Some(code) = run_script_lifecycle("start", args, &effective_filter).await? {
return Ok(Some(code));
}
}
Some(Commands::Stop(args)) => {
if let Some(code) = run_script_lifecycle("stop", args, &effective_filter).await? {
return Ok(Some(code));
}
}
Some(Commands::Store(args)) => commands::store::run(args).await?,
Some(Commands::Test(args)) => {
if let Some(code) = run_script_lifecycle("test", args, &effective_filter).await? {
return Ok(Some(code));
}
}
Some(Commands::Token(args)) => {
return Ok(Some(commands::npm_fallback::run("token", &args)?));
}
Some(Commands::Trust(args)) => commands::trust::run(args).await?,
Some(Commands::Undeprecate(args)) => commands::undeprecate::run(args).await?,
Some(Commands::Unlink(args)) => commands::unlink::run(args).await?,
Some(Commands::Unpublish(args)) => commands::unpublish::run(args).await?,
Some(Commands::Update(args)) => {
if let Some(code) = commands::update::run(args, effective_filter.clone()).await? {
return Ok(Some(code));
}
}
Some(Commands::Version(args)) => commands::version::run(args).await?,
Some(Commands::View(args)) => commands::view::run(args).await?,
Some(Commands::Whoami(args)) => {
return Ok(Some(commands::npm_fallback::run("whoami", &args)?));
}
Some(Commands::Why(args)) => commands::why::run(args, effective_filter.clone()).await?,
Some(Commands::External(args)) => {
// Implicit run: `aube dev` = `aube run dev`.
//
// External is clap's catch-all, so a typo like `aube fooefjwol`
// lands here too. If the name isn't an actual script in the
// local `package.json` (or there's no `package.json` at all),
// print `aube --help` and bail instead of routing it into the
// script runner and surfacing a confusing "script not found"
// or "failed to read package.json" — the user typed something
// we don't recognize and help is the most useful reply.
//
// The pre-check only fires when *no* workspace filter is
// active: `-r` / `-F` fan implicit scripts out across
// sub-packages, and the script may live in one of the
// matched workspaces while the root `package.json` has no
// `scripts` entry at all. In that mode we hand off to
// `run_script` unchanged and let the filtered runner
// produce its own per-package diagnostics.
let script = &args[0];
let script_args: Vec<String> = args[1..].to_vec();
if effective_filter.is_empty() {
let initial_cwd = crate::dirs::cwd()?;
let script_exists = crate::dirs::find_project_root(&initial_cwd)
.and_then(|cwd| {
aube_manifest::PackageJson::from_path(&cwd.join("package.json")).ok()
})
.map(|m| m.scripts.contains_key(script))
.unwrap_or(false);
if !script_exists {
use clap::CommandFactory;
let mut cmd = Cli::command();
cmd.print_help().ok();
eprintln!();
return Err(miette::miette!(
code = aube_codes::errors::ERR_AUBE_UNKNOWN_COMMAND,
"unknown command: {script}"
));
}
}
if let Some(code) =
commands::run::run_script(script, &script_args, false, false, &effective_filter)
.await?
{
return Ok(Some(code));
}
}
None => {
// Bare `aube` prints `--help` and exits 0, matching pnpm.
// pnpm's bare invocation does not run an install; users who
// want that behavior should type `aube install` explicitly.
use clap::CommandFactory;
let mut cmd = Cli::command();
cmd.print_help().ok();
println!();
}
}
Ok(None)
}
fn should_print_top_level_version(cli: &Cli) -> bool {
cli.version && !matches!(cli.command, Some(Commands::Node(_)))
}
/// Run a lifecycle script (`start` / `stop` / `test` / `restart`).
///
/// `ScriptArgs` carries the moved-off-global `LockfileArgs` /
/// `NetworkArgs` / `VirtualStoreArgs` flattens for these commands, so we
/// drain them into the process-global slots before delegating to the
/// shared `run_script` helper. Auto-install (triggered by `run_script`
/// when the named script doesn't exist locally) reads the slots through
/// `ensure_installed`.
async fn run_script_lifecycle(
name: &str,
args: commands::run::ScriptArgs,
filter: &aube_workspace::selector::EffectiveFilter,
) -> miette::Result<Option<i32>> {
args.network.install_overrides();
args.lockfile.install_overrides();
args.virtual_store.install_overrides();
commands::run::run_script(name, &args.args, args.no_install, false, filter).await
}
async fn run_install_command(
args: commands::install::InstallArgs,
filter: aube_workspace::selector::EffectiveFilter,
workspace_root_already: bool,
) -> miette::Result<()> {
// `-w` on install is a short alias for the global
// `--workspace-root` flag. Handle the chdir here when the global
// flag wasn't already set.
if args.workspace_root_short && !workspace_root_already {
let start = std::env::current_dir()
.into_diagnostic()
.wrap_err("failed to read current dir")?;
let root = commands::find_workspace_root(&start)?;
if root != start {
std::env::set_current_dir(&root)
.into_diagnostic()
.wrap_err_with(|| format!("failed to change directory to {}", root.display()))?;
}
crate::dirs::set_cwd(&root)?;
}
args.network.install_overrides();
args.lockfile.install_overrides();
args.virtual_store.install_overrides();
let global_frozen = args.lockfile.frozen_override();
let global_gvs = args.virtual_store.flags();
// Match `install::run`'s precedence so settings here resolve from
// the same root the install will operate against. Workspace-first
// means `aube install` from inside a member loads `.npmrc` /
// workspace yaml from the workspace root, not the member; without
// this the two diverged when both roots existed.
let cwd = crate::dirs::workspace_or_project_root()?;
let files = commands::FileSources::load(&cwd);
let raw_ws = aube_manifest::workspace::load_raw(&cwd)
.into_diagnostic()
.wrap_err("failed to load workspace config")?;
let env = aube_settings::values::capture_env();
let cli_flags = args.to_cli_flag_bag(global_frozen, global_gvs);
let ctx = files.ctx(&raw_ws, &env, &cli_flags);
let yaml_prefer_frozen = aube_settings::resolved::prefer_frozen_lockfile(&ctx);
let mut opts = args.into_options(global_frozen, yaml_prefer_frozen, cli_flags, env);
opts.workspace_filter = filter;
commands::install::run(opts).await?;
Ok(())
}
#[cfg(test)]
mod cli_spec_tests {
use super::*;
#[test]
fn install_accepts_subcommand_registry_flag() {
let cli = Cli::try_parse_from([
"aube",
"install",
"--registry",
"https://registry.example.com/",
])
.expect("install --registry should parse");
let Some(Commands::Install(install_args)) = cli.command else {
panic!("expected install subcommand");
};
assert_eq!(
install_args.network.registry.as_deref(),
Some("https://registry.example.com/")
);
}
#[test]
fn pre_subcommand_registry_lifts_to_install() {
// pnpm-compat: `--registry=URL install` continues to parse via
// `lift_per_subcommand_flags`, which shifts the flag past the
// subcommand before clap sees argv.
let argv = lift_per_subcommand_flags(
[
"aube",
"--registry",
"https://registry.example.com/",
"install",
]
.into_iter()
.map(OsString::from)
.collect(),
);
let cli = Cli::try_parse_from(argv)
.expect("pre-subcommand --registry should still parse via the rewriter");
let Some(Commands::Install(install_args)) = cli.command else {
panic!("expected install subcommand");
};
assert_eq!(
install_args.network.registry.as_deref(),
Some("https://registry.example.com/")
);
}
#[test]
fn dlx_accepts_allow_build_before_command() {
let cli =
Cli::try_parse_from(["aube", "dlx", "--allow-build=esbuild", "vite", "--version"])
.expect("dlx --allow-build should parse");
let Some(Commands::Dlx(dlx_args)) = cli.command else {
panic!("expected dlx subcommand");
};
assert_eq!(dlx_args.allow_build, ["esbuild"]);
assert_eq!(dlx_args.params, ["vite", "--version"]);
}
#[test]
fn dlx_rejects_empty_allow_build_value() {
let err = match Cli::try_parse_from(["aube", "dlx", "--allow-build=", "vite"]) {
Ok(_) => panic!("empty --allow-build should fail"),
Err(err) => err,
};
assert!(
err.to_string()
.contains("The --allow-build flag is missing a package name"),
"{err}"
);
}
#[test]
fn add_accepts_dangerously_allow_all_builds_after_package() {
let cli = Cli::try_parse_from([
"aube",
"add",
"--global",
"opencode-ai@1.17.13",
"--dangerously-allow-all-builds",
])
.expect("add --dangerously-allow-all-builds should parse after a package");
let Some(Commands::Add(add_args)) = cli.command else {
panic!("expected add subcommand");
};
assert!(add_args.global);
assert!(add_args.dangerously_allow_all_builds);
assert_eq!(add_args.packages, ["opencode-ai@1.17.13"]);
}
#[test]
fn add_rejects_deny_build_with_dangerously_allow_all_builds() {
let err = match Cli::try_parse_from([
"aube",
"add",
"some-package",
"--deny-build=some-package",
"--dangerously-allow-all-builds",
]) {
Ok(_) => panic!("deny-build should conflict with dangerously-allow-all-builds"),
Err(err) => err,
};
assert!(
err.to_string().contains(
"'--deny-build=<PKG>' cannot be used with '--dangerously-allow-all-builds'"
),
"{err}"
);
}
#[test]
fn lifter_does_not_eat_lifted_flag_as_kept_flag_value() {
// Regression: `aube --dir /tmp --frozen-lockfile install` would
// previously lose `--frozen-lockfile` if `--dir`'s value was
// omitted because the rewriter unconditionally consumed the next
// token as the kept flag's value.
let argv = lift_per_subcommand_flags(
["aube", "--dir", "--frozen-lockfile", "install"]
.into_iter()
.map(OsString::from)
.collect(),
);
// After the lift, `--frozen-lockfile` should sit after `install`,
// NOT have been consumed as `--dir`'s value.
let strs: Vec<&str> = argv.iter().filter_map(|t| t.to_str()).collect();
let install_idx = strs
.iter()
.position(|s| *s == "install")
.expect("install subcommand should survive the lift");
assert!(
strs[install_idx + 1..].contains(&"--frozen-lockfile"),
"--frozen-lockfile should land after the subcommand: {strs:?}"
);
}
#[test]
fn short_command_aliases_parse() {
let cli = Cli::try_parse_from(["aube", "a", "react"]).expect("a should parse as add");
assert!(matches!(cli.command, Some(Commands::Add(_))));
let cli =
Cli::try_parse_from(["aube", "x", "vitest", "--run"]).expect("x should parse as exec");
let Some(Commands::Exec(args)) = cli.command else {
panic!("x should dispatch to exec");
};
assert_eq!(args.bin, "vitest");
assert_eq!(args.args, vec!["--run"]);
let cli = Cli::try_parse_from(["aube", "w", "react"]).expect("w should parse as why");
assert!(matches!(cli.command, Some(Commands::Why(_))));
}
#[test]
fn bin_accepts_workspace_root_flag() {
// pnpm parity: `aube bin -w` / `--workspace-root` prints the
// workspace-root bin dir. See discussion #988.
for flag in ["-w", "--workspace-root", "--workspace"] {
let cli = Cli::try_parse_from(["aube", "bin", flag])
.unwrap_or_else(|e| panic!("`aube bin {flag}` should parse: {e}"));
let Some(Commands::Bin(args)) = cli.command else {
panic!("`aube bin {flag}` should dispatch to bin");
};
assert!(args.workspace_root, "{flag} should set workspace_root");
assert!(!args.global);
}
}
#[test]
fn bin_global_conflicts_with_workspace_root() {
assert!(
Cli::try_parse_from(["aube", "bin", "-g", "-w"]).is_err(),
"`aube bin -g -w` should be rejected as conflicting"
);
}
#[test]
fn node_subcommand_forwards_version_flag() {
let cli = Cli::try_parse_from(rewrite_multicall_argv(vec![
OsString::from("aube"),
OsString::from("node"),
OsString::from("--version"),
]))
.expect("node --version parses");
assert!(!should_print_top_level_version(&cli));
let Some(Commands::Node(args)) = cli.command else {
panic!("expected node subcommand");
};
assert_eq!(args.args, vec![OsString::from("--version")]);
}
#[test]
fn node_subcommand_forwards_help_flag() {
let cli = Cli::try_parse_from(rewrite_multicall_argv(vec![
OsString::from("aube"),
OsString::from("node"),
OsString::from("--help"),
]))
.expect("node --help parses");
let Some(Commands::Node(args)) = cli.command else {
panic!("expected node subcommand");
};
assert_eq!(args.args, vec![OsString::from("--help")]);
}
}
#[cfg(test)]
mod multicall_tests {
use super::*;
fn os(strs: &[&str]) -> Vec<OsString> {
strs.iter().map(OsString::from).collect()
}
fn temp_shim(name: &str) -> tempfile::TempDir {
let dir = tempfile::tempdir().expect("temp dir should be created");
std::fs::write(dir.path().join(name), "#!/tmp/aube.exe\n").expect("shim should be written");
dir
}
#[test]
fn aube_passes_through_unchanged() {
assert_eq!(
rewrite_multicall_argv(os(&["aube", "install"])),
os(&["aube", "install"])
);
}
#[test]
fn aubr_rewrites_to_run() {
assert_eq!(
rewrite_multicall_argv(os(&["aubr", "build"])),
os(&["aube", "run", "build"])
);
}
#[test]
fn aubx_rewrites_to_dlx() {
assert_eq!(
rewrite_multicall_argv(os(&["aubx", "cowsay", "hi"])),
os(&["aube", "dlx", "cowsay", "hi"])
);
}
#[test]
fn node_shim_rewrites_to_node_subcommand() {
assert_eq!(
rewrite_multicall_argv(os(&["node", "--version"])),
os(&["aube", "node", "--", "--version"])
);
assert_eq!(
rewrite_multicall_argv(os(&["aube", "node", "--version"])),
os(&["aube", "node", "--", "--version"])
);
assert_eq!(
rewrite_multicall_argv(os(&["aube", "__aube-shim", "node", "--version"])),
os(&["aube", "node", "--", "--version"])
);
}
#[test]
fn package_manager_version_flags_rewrite_to_aube_version() {
assert_eq!(
rewrite_multicall_argv(os(&["pnpm", "--version"])),
os(&["aube", "--version"])
);
assert_eq!(
rewrite_multicall_argv(os(&["npm", "-v"])),
os(&["aube", "--version"])
);
assert_eq!(
rewrite_multicall_argv(os(&["npx", "-v"])),
os(&["aube", "--version"])
);
assert_eq!(
rewrite_multicall_argv(os(&["pnpx", "--version"])),
os(&["aube", "--version"])
);
}
#[test]
fn pnpm_and_pnpx_shims_rewrite_to_aube_surfaces() {
assert_eq!(
rewrite_multicall_argv(os(&["pnpm", "install", "--frozen-lockfile"])),
os(&["aube", "install", "--frozen-lockfile"])
);
assert_eq!(
rewrite_multicall_argv(os(&["pnpx", "cowsay", "hi"])),
os(&["aube", "dlx", "cowsay", "hi"])
);
assert_eq!(
rewrite_multicall_argv(os(&[
"aube",
"__aube-shim",
"pnpm",
"install",
"--frozen-lockfile",
])),
os(&["aube", "install", "--frozen-lockfile"])
);
}
#[test]
fn dispatcher_marker_rejects_unknown_tool_names() {
assert_eq!(
rewrite_multicall_argv(os(&["aube", "__aube-shim", "shell", "arg"])),
os(&["aube", "__aube-shim", "shell", "arg"])
);
}
#[test]
fn npm_install_rewrites_to_install_or_add() {
assert_eq!(
rewrite_multicall_argv(os(&["npm", "install"])),
os(&["aube", "install"])
);
assert_eq!(
rewrite_multicall_argv(os(&["npm", "i", "-D", "vitest"])),
os(&["aube", "add", "-D", "vitest"])
);
assert_eq!(
rewrite_multicall_argv(os(&["npm", "install", "--registry", "https://r.test"])),
os(&["aube", "install", "--registry", "https://r.test"])
);
assert_eq!(
rewrite_multicall_argv(os(&["npm", "install", "--workspace", "app"])),
os(&["aube", "install", "--workspace", "app"])
);
assert_eq!(
rewrite_multicall_argv(os(&["npm", "install", "--"])),
os(&["aube", "install", "--"])
);
assert_eq!(
rewrite_multicall_argv(os(&["npm", "install", "--", "vitest"])),
os(&["aube", "add", "--", "vitest"])
);
}
#[test]
fn npm_common_commands_rewrite_to_aube() {
assert_eq!(
rewrite_multicall_argv(os(&["npm", "ci"])),
os(&["aube", "ci"])
);
assert_eq!(
rewrite_multicall_argv(os(&["npm", "run", "build"])),
os(&["aube", "run", "build"])
);
assert_eq!(
rewrite_multicall_argv(os(&["npm", "rm", "react"])),
os(&["aube", "remove", "react"])
);
assert_eq!(
rewrite_multicall_argv(os(&["npx", "vite", "--version"])),
os(&["aube", "dlx", "vite", "--version"])
);
}
#[test]
fn yarn_common_commands_rewrite_to_aube() {
assert_eq!(
rewrite_multicall_argv(os(&["yarn"])),
os(&["aube", "install"])
);
assert_eq!(
rewrite_multicall_argv(os(&["yarn", "add", "react"])),
os(&["aube", "add", "react"])
);
assert_eq!(
rewrite_multicall_argv(os(&["yarnpkg", "remove", "react"])),
os(&["aube", "remove", "react"])
);
}
#[test]
fn absolute_path_and_exe_suffix_are_handled() {
// argv[0] can be an absolute path (exec-style invocation) or carry
// a `.exe` suffix on Windows. `Path::file_stem` takes care of both
// so dispatch stays purely basename-driven.
assert_eq!(
rewrite_multicall_argv(os(&["/usr/local/bin/aubr", "test"])),
os(&["aube", "run", "test"])
);
assert_eq!(
rewrite_multicall_argv(os(&["aubx.exe", "pkg"])),
os(&["aube", "dlx", "pkg"])
);
}
#[test]
fn bare_shim_invocation_passes_through_to_subcommand() {
// `aubr` with no further args becomes `aube run`, which clap
// parses as the `run` subcommand with no positional — same as
// the user typing `aube run` directly.
assert_eq!(rewrite_multicall_argv(os(&["aubr"])), os(&["aube", "run"]));
}
#[test]
fn version_flag_short_circuits_to_top_level() {
// `aubr --version` / `aubx --version` should print the aube
// version, not trip the `run` / `dlx` parsers.
assert_eq!(
rewrite_multicall_argv(os(&["aubr", "--version"])),
os(&["aube", "--version"])
);
assert_eq!(
rewrite_multicall_argv(os(&["aubx", "--version"])),
os(&["aube", "--version"])
);
assert_eq!(
rewrite_multicall_argv(os(&["aubr", "-V"])),
os(&["aube", "-V"])
);
assert_eq!(
rewrite_multicall_argv(os(&["aubx.exe", "-V"])),
os(&["aube", "-V"])
);
}
#[test]
fn npm_interpreter_shim_path_is_dropped() {
let dir = temp_shim("aube");
let shim = dir.path().join("aube");
let shim_os = shim.clone().into_os_string();
assert_eq!(
rewrite_multicall_argv(vec![
OsString::from("aube.exe"),
shim.into_os_string(),
OsString::from("--version"),
]),
vec![shim_os, OsString::from("--version")]
);
}
#[test]
fn npm_interpreter_shim_preserves_multicall_dispatch() {
let dir = temp_shim("aubr");
let shim = dir.path().join("aubr");
assert_eq!(
rewrite_multicall_argv(vec![
OsString::from("aubr.exe"),
shim.into_os_string(),
OsString::from("build"),
]),
os(&["aube", "run", "build"])
);
}
#[test]
fn extract_config_overrides_strips_equals_form() {
let mut argv = os(&["aube", "install", "--config.strict-dep-builds=true"]);
let parsed = extract_config_overrides(&mut argv);
assert_eq!(argv, os(&["aube", "install"]));
assert_eq!(
parsed,
vec![("strict-dep-builds".to_string(), "true".to_string())]
);
}
#[test]
fn extract_config_overrides_strips_bool_form() {
let mut argv = os(&["aube", "--config.strictDepBuilds", "install"]);
let parsed = extract_config_overrides(&mut argv);
assert_eq!(argv, os(&["aube", "install"]));
assert_eq!(
parsed,
vec![("strictDepBuilds".to_string(), "true".to_string())]
);
}
#[test]
fn extract_config_overrides_handles_multiple_and_preserves_order() {
let mut argv = os(&[
"aube",
"--config.foo=1",
"install",
"--config.bar=two",
"--config.foo=3",
]);
let parsed = extract_config_overrides(&mut argv);
assert_eq!(argv, os(&["aube", "install"]));
assert_eq!(
parsed,
vec![
("foo".to_string(), "1".to_string()),
("bar".to_string(), "two".to_string()),
("foo".to_string(), "3".to_string()),
]
);
}
#[test]
fn extract_config_overrides_stops_at_double_dash() {
let mut argv = os(&["aube", "exec", "--", "node", "--config.foo=should-stay"]);
let parsed = extract_config_overrides(&mut argv);
assert!(parsed.is_empty());
assert_eq!(
argv,
os(&["aube", "exec", "--", "node", "--config.foo=should-stay"])
);
}
#[test]
fn extract_config_overrides_preserves_argv_when_absent() {
let mut argv = os(&["aube", "install", "--frozen-lockfile"]);
let parsed = extract_config_overrides(&mut argv);
assert!(parsed.is_empty());
assert_eq!(argv, os(&["aube", "install", "--frozen-lockfile"]));
}
}
#[cfg(test)]
mod package_manager_guard_tests {
use super::*;
#[test]
fn run_like_commands_warn_instead_of_erroring() {
let run = Cli::try_parse_from(["aube", "run", "test"]).expect("run should parse");
let test = Cli::try_parse_from(["aube", "test"]).expect("test should parse");
assert_eq!(
package_manager_guard_mode(run.command.as_ref()),
PackageManagerGuardMode::WarnAndSkipAutoInstall
);
assert_eq!(
package_manager_guard_mode(test.command.as_ref()),
PackageManagerGuardMode::WarnAndSkipAutoInstall
);
}
#[test]
fn install_still_errors_on_mismatch() {
let cli = Cli::try_parse_from(["aube", "install"]).expect("install should parse");
assert_eq!(
package_manager_guard_mode(cli.command.as_ref()),
PackageManagerGuardMode::Error
);
}
#[test]
fn install_test_still_errors_on_mismatch() {
let cli = Cli::try_parse_from(["aube", "install-test"]).expect("install-test should parse");
assert_eq!(
package_manager_guard_mode(cli.command.as_ref()),
PackageManagerGuardMode::Error
);
}
#[test]
fn prefix_skips_package_manager_guard() {
let cli = Cli::try_parse_from(["aube", "prefix"]).expect("prefix should parse");
assert!(!command_needs_package_manager_guard(cli.command.as_ref()));
}
#[test]
fn package_manager_strict_mode_parses_canonical_spellings() {
for (input, expected) in [
("off", PackageManagerStrictMode::Off),
("warn", PackageManagerStrictMode::Warn),
("error", PackageManagerStrictMode::Error),
(" ERROR\n", PackageManagerStrictMode::Error),
] {
assert_eq!(PackageManagerStrictMode::parse(input), Some(expected));
}
}
#[test]
fn package_manager_strict_mode_parses_bool_back_compat() {
// `true`/`false` (and the shell-style `1`/`0` admitted by the
// generic bool parser) need to keep working so projects on the
// pre-tri-state default don't break.
for (input, expected) in [
("true", PackageManagerStrictMode::Error),
("false", PackageManagerStrictMode::Off),
("1", PackageManagerStrictMode::Error),
("0", PackageManagerStrictMode::Off),
] {
assert_eq!(PackageManagerStrictMode::parse(input), Some(expected));
}
}
#[test]
fn package_manager_strict_mode_returns_none_for_typos() {
// Caller turns `None` into a startup warning + default. The
// unit test pins the precondition: parse must NOT silently
// coerce a typo to the default.
assert!(PackageManagerStrictMode::parse("errror").is_none());
assert!(PackageManagerStrictMode::parse("warning").is_none());
assert!(PackageManagerStrictMode::parse("").is_none());
}
}
#[cfg(test)]
mod cli_ordering_tests {
use super::*;
use clap::CommandFactory;
use std::collections::BTreeMap;
/// Validate that aube's CLI commands and arguments are ordered:
/// - Subcommands alphabetical by name
/// - Short flags alphabetical by short option
/// - Long-only flags alphabetical by long name *within each help-heading
/// bucket* (the unheaded default counts as one bucket)
///
/// We can't use `clap_sort::assert_sorted` directly because flags from
/// flattened `cli_args::*Args` groups carry their own `help_heading`
/// (e.g. "Lockfile", "Network", "Virtual store") and clap-sort enforces
/// strict alphabetical across the full long-only set, which would
/// require interleaving group flags between per-command flags. The
/// help-grouped layout is the whole point of the move, so we sort
/// within heading buckets instead.
#[test]
fn test_cli_ordering() {
check_command_sorted(&Cli::command(), &[]);
}
fn check_command_sorted(cmd: &clap::Command, path: &[&str]) {
let mut current_path: Vec<&str> = path.to_vec();
current_path.push(cmd.get_name());
// Subcommands alphabetical
let names: Vec<_> = cmd.get_subcommands().map(|s| s.get_name()).collect();
let mut sorted = names.clone();
sorted.sort();
assert!(
names == sorted,
"Subcommands in '{}' are not sorted alphabetically!\nActual: {:?}\nExpected: {:?}",
current_path.join(" "),
names,
sorted,
);
// Short flags alphabetical, long-only alphabetical within heading.
let mut shorts: Vec<char> = Vec::new();
let mut by_heading: BTreeMap<Option<&str>, Vec<&str>> = BTreeMap::new();
for arg in cmd.get_arguments() {
if let Some(s) = arg.get_short() {
shorts.push(s);
} else if let Some(l) = arg.get_long() {
by_heading
.entry(arg.get_help_heading())
.or_default()
.push(l);
}
}
let mut sorted_shorts = shorts.clone();
sorted_shorts.sort_by_key(|c| (c.to_ascii_lowercase(), c.is_uppercase()));
assert!(
shorts == sorted_shorts,
"Short flags in '{}' are not sorted!\nActual: {:?}\nExpected: {:?}",
current_path.join(" "),
shorts,
sorted_shorts,
);
for (heading, longs) in &by_heading {
let mut sorted_longs = longs.clone();
sorted_longs.sort();
assert!(
longs == &sorted_longs,
"Long-only flags under heading {:?} in '{}' are not sorted!\nActual: {:?}\nExpected: {:?}",
heading,
current_path.join(" "),
longs,
sorted_longs,
);
}
for sub in cmd.get_subcommands() {
check_command_sorted(sub, ¤t_path);
}
}
}