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
//! sbom-tools: Semantic SBOM diff and analysis tool
//!
//! A format-agnostic SBOM comparison tool for `CycloneDX` and SPDX formats.
#![allow(
clippy::too_many_lines,
clippy::struct_excessive_bools,
clippy::needless_pass_by_value
)]
use anyhow::{Context, Result};
use clap::{Args, CommandFactory, Parser, Subcommand};
use clap_complete::{Shell, generate};
use sbom_tools::{
cli,
config::{
BehaviorConfig, DiffConfig, DiffPaths, EcosystemRulesConfig, EnrichmentConfig,
FilterConfig, GraphAwareDiffConfig, MatchingConfig, MatchingRulesPathConfig, MatrixConfig,
MultiDiffConfig, OutputConfig, QueryConfig, TimelineConfig, ViewConfig, WatchConfig,
},
pipeline::dirs,
reports::{ReportFormat, ReportType},
watch::parse_duration,
};
use std::io::{self, Write as _};
use std::path::{Path, PathBuf};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
/// Build long version string with format support info
const fn build_long_version() -> &'static str {
concat!(
env!("CARGO_PKG_VERSION"),
"\n\nSupported SBOM Formats:",
"\n CycloneDX: 1.4, 1.5, 1.6, 1.7 (JSON, XML)",
"\n SPDX: 2.2, 2.3 (JSON, tag-value, RDF/XML), 3.0 (JSON-LD)",
"\n\nOutput Formats:",
"\n tui, json, sarif, markdown, html, summary, table, side-by-side",
"\n\nFeatures:",
"\n Semantic diff, fuzzy matching, vulnerability tracking, license analysis"
)
}
#[derive(Parser)]
#[command(name = "sbom-tools")]
#[command(author = "Binarly.io")]
#[command(version, long_version = build_long_version())]
#[command(about = "Semantic SBOM diff and analysis tool", long_about = None)]
#[command(after_help = "EXIT CODES:
0 No changes detected (or --no-fail-on-change)
1 Changes detected / no query matches
2 Vulnerabilities introduced
3 Error occurred
4 VEX gaps found (--fail-on-vex-gap)
5 License policy violations found
EXAMPLES:
Comparing SBOMs:
sbom-tools diff old.cdx.json new.cdx.json # Interactive TUI
sbom-tools diff old.cdx.json new.cdx.json -o summary # Terminal summary
sbom-tools diff old.cdx.json new.cdx.json -o json > diff.json # JSON export
sbom-tools diff old.cdx.json new.cdx.json -o sarif # CI/CD SARIF
Enrichment (add vulnerability + EOL data before diffing):
sbom-tools diff old.json new.json --enrich-vulns --enrich-eol
sbom-tools view app.cdx.json --enrich-vulns --fail-on-vuln
CI/CD pipeline gates:
sbom-tools diff old.json new.json --fail-on-vuln --fail-on-change
sbom-tools diff old.json new.json --fail-on-vex-gap --vex vex.json
sbom-tools quality app.cdx.json --min-score 70
Fleet / multi-SBOM analysis:
sbom-tools diff-multi baseline.json device-*.json -o table
sbom-tools timeline v1.json v2.json v3.json --enrich-vulns
sbom-tools matrix *.cdx.json --cluster-threshold 0.9
Search and query:
sbom-tools query \"log4j\" --version \"<2.17.0\" fleet/*.json
sbom-tools query --affected-by CVE-2021-44228 *.json
Quality and compliance:
sbom-tools quality app.cdx.json --profile security --metrics
sbom-tools validate app.cdx.json --standard ntia,cra,eo14028
sbom-tools license-check app.cdx.json --strict
VEX operations:
sbom-tools vex status --sbom app.json --vex vex.json
sbom-tools vex apply --sbom app.json --vex vex.json -O enriched.json
SBOM operations (enrich, filter, merge):
sbom-tools enrich app.cdx.json --enrich-vulns --enrich-eol -O enriched.json
sbom-tools tailor app.cdx.json --exclude-ecosystems npm,pypi
sbom-tools merge primary.json secondary.json -O combined.json
Monitoring:
sbom-tools watch --dir ./sboms --enrich-vulns --exit-on-change
sbom-tools verify hash app.cdx.json --algorithm sha256
For more details on any command: sbom-tools <command> --help")]
struct Cli {
/// Enable verbose output
#[arg(short, long, global = true)]
verbose: bool,
/// Suppress non-essential output
#[arg(short, long, global = true)]
quiet: bool,
/// Disable colored output (also respects `NO_COLOR` env)
#[arg(long, global = true)]
no_color: bool,
/// Export filename template for TUI exports
///
/// Placeholders: {date}, {time}, {format}, {command}
#[arg(long, global = true)]
export_template: Option<String>,
/// Path to configuration file
#[arg(long, global = true)]
config: Option<PathBuf>,
#[command(subcommand)]
command: Commands,
}
// ============================================================================
// Command argument structs (extracted for readability)
// ============================================================================
/// Shared enrichment arguments for commands that support vulnerability/EOL data enrichment.
#[derive(Args, Debug)]
struct SharedEnrichmentArgs {
/// Enable OSV vulnerability enrichment
#[arg(long)]
enrich_vulns: bool,
/// Enable end-of-life detection via endoflife.date
#[arg(long)]
enrich_eol: bool,
/// Apply external VEX document(s) (OpenVEX format). Can be specified multiple times
#[arg(long = "vex", value_name = "PATH")]
vex: Vec<PathBuf>,
/// Cache directory for enrichment data
#[arg(long, alias = "cache-dir")]
vuln_cache_dir: Option<PathBuf>,
/// Cache TTL in hours
#[arg(long, alias = "cache-ttl", default_value = "24")]
vuln_cache_ttl: u64,
/// Bypass cache and fetch fresh data
#[arg(long, alias = "refresh")]
refresh_vulns: bool,
/// API timeout in seconds
#[arg(long, default_value = "30")]
api_timeout: u64,
/// Custom matching rules YAML file
#[arg(long)]
matching_rules: Option<PathBuf>,
}
impl SharedEnrichmentArgs {
fn to_enrichment_config(&self) -> EnrichmentConfig {
EnrichmentConfig {
enabled: self.enrich_vulns,
cache_dir: self
.vuln_cache_dir
.clone()
.or_else(|| Some(dirs::osv_cache_dir())),
cache_ttl_hours: self.vuln_cache_ttl,
bypass_cache: self.refresh_vulns,
timeout_secs: self.api_timeout,
enable_eol: self.enrich_eol,
vex_paths: self.vex.clone(),
..Default::default()
}
}
}
/// Arguments for the `diff` subcommand
#[derive(Parser)]
#[command(after_help = "EXAMPLES:
sbom-tools diff old.cdx.json new.cdx.json # Interactive TUI
sbom-tools diff old.json new.json -o summary --fail-on-vuln # CI gate
sbom-tools diff old.json new.json --enrich-vulns -o sarif # Enriched SARIF
sbom-tools diff old.json new.json --graph-diff --graph-max-depth 3
sbom-tools diff old.json new.json --vex vex.json --fail-on-vex-gap")]
struct DiffArgs {
/// Path to the old/baseline SBOM
old: PathBuf,
/// Path to the new SBOM
new: PathBuf,
/// Output format (auto detects TTY: tui if interactive, summary otherwise)
#[arg(short, long, default_value = "auto")]
output: ReportFormat,
/// Output file path (stdout if not specified)
#[arg(short = 'O', long)]
output_file: Option<PathBuf>,
/// Report types to include
#[arg(long, default_value = "all")]
reports: ReportType,
/// Fuzzy matching preset (strict, balanced, permissive)
#[arg(long, default_value = "balanced")]
fuzzy_preset: String,
/// Include unchanged components in output
#[arg(long)]
include_unchanged: bool,
/// Exit with code 2 if new vulnerabilities are introduced
#[arg(long)]
fail_on_vuln: bool,
/// Exit with code 1 if any changes detected (default for non-zero changes)
#[arg(long)]
fail_on_change: bool,
/// Only show items with changes (hide unchanged)
#[arg(long)]
only_changes: bool,
/// Filter by minimum severity (critical, high, medium, low)
#[arg(long)]
severity: Option<String>,
#[command(flatten)]
enrichment: SharedEnrichmentArgs,
/// Enable graph-aware diffing (detect reparenting, depth changes)
#[arg(long)]
graph_diff: bool,
/// Maximum depth for graph analysis (0 = unlimited, requires --graph-diff)
#[arg(long, default_value = "0")]
graph_max_depth: u32,
/// Minimum impact level to include in graph diff output (low, medium, high, critical)
#[arg(long, default_value = "low")]
graph_impact_threshold: String,
/// Comma-separated list of relationship types to include in graph diff
/// (e.g., "DependsOn,DevDependsOn"). Empty = all types.
#[arg(long)]
graph_relations: Option<String>,
/// Dry-run matching rules (show what would match without applying)
#[arg(long)]
dry_run_rules: bool,
/// Path to ecosystem rules configuration file (YAML/JSON)
#[arg(long, env = "SBOM_TOOLS_ECOSYSTEM_RULES")]
ecosystem_rules: Option<PathBuf>,
/// Disable ecosystem-specific name normalization
#[arg(long)]
no_ecosystem_rules: bool,
/// Exclude vulnerabilities with VEX status `not_affected` or fixed
#[arg(long, alias = "exclude-vex-not-affected")]
exclude_vex_resolved: bool,
/// Exit with error if introduced vulnerabilities lack VEX statements (CI gate)
#[arg(long)]
fail_on_vex_gap: bool,
/// Enable typosquat detection warnings
#[arg(long)]
detect_typosquats: bool,
/// Show detailed match explanations for each matched component
#[arg(long)]
explain_matches: bool,
/// Recommend optimal matching threshold based on the SBOMs
#[arg(long)]
recommend_threshold: bool,
/// Force streaming mode for large SBOM handling (reduces memory usage)
#[arg(long)]
streaming: bool,
/// Streaming threshold in MB. Files larger than this use streaming mode.
#[arg(long, default_value = "10")]
streaming_threshold: u64,
}
/// Arguments for the `view` subcommand
#[derive(Parser)]
#[command(after_help = "EXAMPLES:
sbom-tools view app.cdx.json # Interactive TUI
sbom-tools view app.cdx.json --enrich-vulns --fail-on-vuln # CI vuln check
sbom-tools view app.cdx.json -o json > components.json # Export
sbom-tools view app.cdx.json --vulnerable-only --severity high")]
struct ViewArgs {
/// Path to the SBOM file
sbom: PathBuf,
/// Output format (auto detects TTY: tui if interactive, summary otherwise)
#[arg(short, long, default_value = "auto")]
output: ReportFormat,
/// Output file path (stdout if not specified)
#[arg(short = 'O', long)]
output_file: Option<PathBuf>,
/// Validate against NTIA minimum elements
#[arg(long)]
validate_ntia: bool,
/// Filter by minimum vulnerability severity (critical, high, medium, low)
#[arg(long)]
severity: Option<String>,
/// Only show components with vulnerabilities
#[arg(long)]
vulnerable_only: bool,
/// Filter by ecosystem (e.g., npm, cargo, pypi, maven)
#[arg(long)]
ecosystem: Option<String>,
/// Exit with code 2 if any vulnerabilities are present in the SBOM
#[arg(long)]
fail_on_vuln: bool,
/// BOM type override (sbom, cbom). Auto-detected from content if omitted
#[arg(long, value_name = "TYPE")]
bom_type: Option<String>,
#[command(flatten)]
enrichment: SharedEnrichmentArgs,
}
/// Arguments for the `validate` subcommand
#[derive(Parser)]
#[command(after_help = "EXAMPLES:
sbom-tools validate app.cdx.json # NTIA minimum
sbom-tools validate app.cdx.json --standard cra,eo14028 # Multi-standard
sbom-tools validate app.cdx.json --standard ntia -o sarif # SARIF for CI
sbom-tools validate app.cdx.json --fail-on-warning # Strict CI gate")]
struct ValidateArgs {
/// Path to the SBOM file
sbom: PathBuf,
/// Compliance standard(s) to validate against (comma-separated: ntia, fda, cra, ssdf, eo14028)
#[arg(long, default_value = "ntia")]
standard: String,
/// Output format (auto detects TTY: tui if interactive, summary otherwise)
#[arg(short, long, default_value = "auto")]
output: ReportFormat,
/// Output file path (stdout if not specified)
#[arg(short = 'O', long)]
output_file: Option<PathBuf>,
/// Exit with non-zero code when warnings are found (not just errors)
#[arg(long)]
fail_on_warning: bool,
/// Output only a compact JSON summary (overrides --output)
#[arg(long)]
summary: bool,
}
/// Arguments for the `diff-multi` subcommand
#[derive(Parser)]
#[command(after_help = "EXAMPLES:
sbom-tools diff-multi baseline.json target1.json target2.json
sbom-tools diff-multi baseline.json devices/*.json -o table
sbom-tools diff-multi base.json t1.json t2.json --enrich-vulns --fail-on-vuln")]
struct DiffMultiArgs {
/// Path to the baseline SBOM
baseline: PathBuf,
/// Paths to target SBOMs to compare against baseline
#[arg(required = true)]
targets: Vec<PathBuf>,
/// Output format (auto detects TTY: tui if interactive, summary otherwise)
#[arg(short, long, default_value = "auto")]
output: ReportFormat,
/// Output file path (stdout if not specified)
#[arg(short = 'O', long)]
output_file: Option<PathBuf>,
/// Fuzzy matching preset (strict, balanced, permissive)
#[arg(long, default_value = "balanced")]
fuzzy_preset: String,
/// Include unchanged components in output
#[arg(long)]
include_unchanged: bool,
/// Enable graph-aware diffing for multi-comparisons
#[arg(long)]
graph_diff: bool,
/// Maximum depth for graph analysis (0 = unlimited, requires --graph-diff)
#[arg(long, default_value = "0")]
graph_max_depth: u32,
/// Minimum impact level for graph diff output (low, medium, high, critical)
#[arg(long, default_value = "low")]
graph_impact_threshold: String,
/// Relationship types to include in graph diff (comma-separated, e.g., "DependsOn,DevDependsOn")
#[arg(long)]
graph_relations: Option<String>,
/// Filter by minimum severity (critical, high, medium, low)
#[arg(long)]
severity: Option<String>,
/// Exit with code 2 if new vulnerabilities are introduced
#[arg(long)]
fail_on_vuln: bool,
/// Exit with code 1 if any changes detected
#[arg(long)]
fail_on_change: bool,
/// Exclude vulnerabilities with VEX status `not_affected` or fixed
#[arg(long)]
exclude_vex_resolved: bool,
/// Exit with error if introduced vulnerabilities lack VEX statements
#[arg(long)]
fail_on_vex_gap: bool,
#[command(flatten)]
enrichment: SharedEnrichmentArgs,
}
/// Arguments for the `timeline` subcommand
#[derive(Parser)]
#[command(after_help = "EXAMPLES:
sbom-tools timeline v1.0.json v1.1.json v1.2.json # Version evolution
sbom-tools timeline releases/*.json --enrich-vulns -o markdown # Vuln trend report
sbom-tools timeline *.json --fail-on-vuln --fail-on-change # CI gate")]
struct TimelineArgs {
/// Paths to SBOMs in chronological order (oldest first)
#[arg(required = true)]
sboms: Vec<PathBuf>,
/// Output format (auto detects TTY: tui if interactive, summary otherwise)
#[arg(short, long, default_value = "auto")]
output: ReportFormat,
/// Output file path (stdout if not specified)
#[arg(short = 'O', long)]
output_file: Option<PathBuf>,
/// Fuzzy matching preset (strict, balanced, permissive)
#[arg(long, default_value = "balanced")]
fuzzy_preset: String,
/// Enable graph-aware diffing for timeline analysis
#[arg(long)]
graph_diff: bool,
/// Maximum depth for graph analysis (0 = unlimited, requires --graph-diff)
#[arg(long, default_value = "0")]
graph_max_depth: u32,
/// Minimum impact level for graph diff output (low, medium, high, critical)
#[arg(long, default_value = "low")]
graph_impact_threshold: String,
/// Relationship types to include in graph diff (comma-separated, e.g., "DependsOn,DevDependsOn")
#[arg(long)]
graph_relations: Option<String>,
/// Filter by minimum severity (critical, high, medium, low)
#[arg(long)]
severity: Option<String>,
/// Exit with code 2 if new vulnerabilities are introduced
#[arg(long)]
fail_on_vuln: bool,
/// Exit with code 1 if any changes detected
#[arg(long)]
fail_on_change: bool,
/// Exclude vulnerabilities with VEX status `not_affected` or fixed
#[arg(long)]
exclude_vex_resolved: bool,
/// Exit with error if introduced vulnerabilities lack VEX statements
#[arg(long)]
fail_on_vex_gap: bool,
#[command(flatten)]
enrichment: SharedEnrichmentArgs,
}
/// Arguments for the `matrix` subcommand
#[derive(Parser)]
#[command(after_help = "EXAMPLES:
sbom-tools matrix v1.json v2.json v3.json # NxN comparison
sbom-tools matrix *.cdx.json --cluster-threshold 0.9 -o table # Clustering
sbom-tools matrix *.json --enrich-vulns --fail-on-vuln # CI with enrichment")]
struct MatrixArgs {
/// Paths to SBOMs to compare
#[arg(required = true)]
sboms: Vec<PathBuf>,
/// Output format (auto detects TTY: tui if interactive, summary otherwise)
#[arg(short, long, default_value = "auto")]
output: ReportFormat,
/// Output file path (stdout if not specified)
#[arg(short = 'O', long)]
output_file: Option<PathBuf>,
/// Fuzzy matching preset (strict, balanced, permissive)
#[arg(long, default_value = "balanced")]
fuzzy_preset: String,
/// Similarity threshold for clustering (0.0-1.0)
#[arg(long, default_value = "0.8")]
cluster_threshold: f64,
/// Enable graph-aware diffing for matrix comparison
#[arg(long)]
graph_diff: bool,
/// Maximum depth for graph analysis (0 = unlimited, requires --graph-diff)
#[arg(long, default_value = "0")]
graph_max_depth: u32,
/// Minimum impact level for graph diff output (low, medium, high, critical)
#[arg(long, default_value = "low")]
graph_impact_threshold: String,
/// Relationship types to include in graph diff (comma-separated, e.g., "DependsOn,DevDependsOn")
#[arg(long)]
graph_relations: Option<String>,
/// Filter by minimum severity (critical, high, medium, low)
#[arg(long)]
severity: Option<String>,
/// Exit with code 2 if new vulnerabilities are introduced
#[arg(long)]
fail_on_vuln: bool,
/// Exit with code 1 if any changes detected
#[arg(long)]
fail_on_change: bool,
/// Exclude vulnerabilities with VEX status `not_affected` or fixed
#[arg(long)]
exclude_vex_resolved: bool,
/// Exit with error if introduced vulnerabilities lack VEX statements
#[arg(long)]
fail_on_vex_gap: bool,
#[command(flatten)]
enrichment: SharedEnrichmentArgs,
}
/// Arguments for the `quality` subcommand
#[derive(Parser)]
#[command(after_help = "EXAMPLES:
sbom-tools quality app.cdx.json # Score overview
sbom-tools quality app.cdx.json --profile security --metrics # Detailed metrics
sbom-tools quality app.cdx.json --min-score 70 -o json # CI gate with export
sbom-tools quality app.cdx.json --recommendations # Improvement suggestions")]
struct QualityArgs {
/// Path to the SBOM file
sbom: PathBuf,
/// Scoring profile (minimal, standard, security, license-compliance, comprehensive)
#[arg(long, default_value = "standard")]
profile: String,
/// Output format (auto detects TTY: tui if interactive, summary otherwise)
#[arg(short, long, default_value = "auto")]
output: ReportFormat,
/// Output file path (stdout if not specified)
#[arg(short = 'O', long)]
output_file: Option<PathBuf>,
/// Show detailed recommendations
#[arg(long)]
recommendations: bool,
/// Show detailed metrics
#[arg(long)]
metrics: bool,
/// Fail if quality score is below threshold (0-100)
#[arg(long)]
min_score: Option<f32>,
}
/// Arguments for the `query` subcommand
#[derive(Parser)]
#[command(after_help = "EXAMPLES:
sbom-tools query log4j fleet/*.json # Search by name
sbom-tools query --affected-by CVE-2021-44228 *.json # Search by CVE
sbom-tools query --ecosystem npm --license GPL fleet/*.json # Multi-filter
sbom-tools query --version \"<2.0.0\" --enrich-vulns *.json # With enrichment")]
struct QueryArgs {
/// Positional arguments: [PATTERN] SBOM_FILES...
/// First argument is treated as search pattern if it doesn't look like a file path.
/// All remaining arguments are SBOM file paths.
#[arg(required = true)]
args: Vec<String>,
/// Filter by component name (substring)
#[arg(long)]
name: Option<String>,
/// Filter by PURL (substring)
#[arg(long)]
purl: Option<String>,
/// Filter by version (exact or semver range, e.g., "<2.17.0")
#[arg(long)]
version: Option<String>,
/// Filter by license (substring)
#[arg(long)]
license: Option<String>,
/// Filter by ecosystem (e.g., npm, maven, cargo)
#[arg(long)]
ecosystem: Option<String>,
/// Filter by supplier name (substring)
#[arg(long)]
supplier: Option<String>,
/// Filter by vulnerability ID (e.g., CVE-2021-44228)
#[arg(long)]
affected_by: Option<String>,
/// Filter by crypto asset type (algorithm, certificate, key, protocol)
#[arg(long)]
crypto_type: Option<String>,
/// Filter by algorithm family (substring, e.g., "AES", "RSA", "ML-KEM")
#[arg(long)]
algorithm_family: Option<String>,
/// Show only quantum-safe cryptographic assets
#[arg(long, conflicts_with = "quantum_vulnerable")]
quantum_safe: bool,
/// Show only quantum-vulnerable cryptographic assets
#[arg(long, conflicts_with = "quantum_safe")]
quantum_vulnerable: bool,
/// Output format (table, json, csv)
#[arg(short, long, default_value = "auto")]
output: ReportFormat,
/// Output file path (stdout if not specified)
#[arg(short = 'O', long)]
output_file: Option<PathBuf>,
#[command(flatten)]
enrichment: SharedEnrichmentArgs,
/// Maximum number of results to return
#[arg(long)]
limit: Option<usize>,
/// Group results by SBOM source
#[arg(long)]
group_by_sbom: bool,
}
/// Arguments for the `watch` subcommand
#[derive(Parser)]
#[command(after_help = "EXAMPLES:
sbom-tools watch --dir ./sboms # Monitor directory
sbom-tools watch --dir ./sboms --enrich-vulns --exit-on-change # CI mode
sbom-tools watch --dir ./sboms -i 30s --enrich-vulns -o json # Streaming JSON")]
struct WatchArgs {
/// Directories to watch for SBOM file changes
#[arg(long = "dir", short = 'd', required = true)]
dirs: Vec<PathBuf>,
/// Polling interval for file changes (e.g., 30s, 5m, 1h)
#[arg(long, short = 'i', default_value = "5m")]
interval: String,
/// Enrichment refresh interval (e.g., 1h, 6h, 1d)
#[arg(long, default_value = "6h")]
enrich_interval: String,
/// Output format (summary for human, json for NDJSON streaming)
#[arg(short, long, default_value = "auto")]
output: ReportFormat,
/// Output file path (stdout if not specified)
#[arg(short = 'O', long)]
output_file: Option<PathBuf>,
/// Optional webhook URL for alerts (requires enrichment feature)
#[arg(long)]
webhook: Option<String>,
#[command(flatten)]
enrichment: SharedEnrichmentArgs,
/// Debounce duration — wait after detecting a change before processing,
/// to coalesce rapid writes (e.g., 2s, 500ms). Use 0s to disable.
#[arg(long, default_value = "2s")]
debounce: String,
/// Exit after the first change is detected (CI mode)
#[arg(long)]
exit_on_change: bool,
/// Maximum number of diff snapshots to retain per SBOM
#[arg(long, default_value = "10")]
max_snapshots: usize,
/// Scan once and print discovered SBOMs, then exit (useful for testing watch configuration)
#[arg(long)]
dry_run: bool,
}
#[derive(Subcommand)]
enum Commands {
/// Compare two SBOMs
Diff(DiffArgs),
/// View a single SBOM
View(ViewArgs),
/// Validate an SBOM against a compliance standard
Validate(ValidateArgs),
/// Compare a baseline SBOM against multiple targets (1:N comparison)
DiffMulti(DiffMultiArgs),
/// Analyze SBOM evolution over time (timeline comparison)
Timeline(TimelineArgs),
/// Compare all SBOMs against each other (`NxN` matrix comparison)
Matrix(MatrixArgs),
/// Assess SBOM quality and completeness
Quality(QualityArgs),
/// Search for components across multiple SBOMs
Query(QueryArgs),
/// Standalone VEX (Vulnerability Exploitability eXchange) operations
Vex {
#[command(subcommand)]
action: VexAction,
},
/// Continuously monitor SBOMs for file changes and new vulnerabilities
Watch(WatchArgs),
/// Generate shell completions
Completions {
/// Shell to generate completions for
#[arg(value_enum)]
shell: Shell,
},
/// Generate JSON Schema for the config file format
ConfigSchema {
/// Write schema to file instead of stdout
#[arg(short, long)]
output: Option<PathBuf>,
},
/// Show, discover, or initialize configuration
Config {
#[command(subcommand)]
action: ConfigAction,
},
/// Verify SBOM integrity
Verify {
#[command(subcommand)]
action: VerifyAction,
},
/// Check license policy compliance
LicenseCheck(LicenseCheckArgs),
/// Enrich an SBOM with vulnerability and EOL data
#[cfg(feature = "enrichment")]
Enrich(EnrichArgs),
/// Tailor (filter) an SBOM by removing unwanted components
Tailor(TailorArgs),
/// Merge two SBOMs into one
Merge(MergeArgs),
/// Generate a man page and print it to stdout
Man,
}
/// Sub-subcommands for the `config` command
#[derive(Subcommand)]
enum ConfigAction {
/// Print current effective configuration (merged from defaults + file)
Show,
/// Print config file search paths and discovered config file
Path,
/// Generate an example .sbom-tools.yaml in the current directory
Init,
}
/// Sub-subcommands for the `vex` command
#[derive(Subcommand)]
enum VexAction {
/// Apply external VEX documents to an SBOM and output enriched vulnerability data
Apply(VexArgs),
/// Show VEX coverage summary (how many vulns have VEX statements)
Status(VexArgs),
/// Filter vulnerabilities by VEX state (for CI pipelines)
Filter(VexArgs),
}
/// Shared arguments for all VEX subcommands
#[derive(Parser)]
struct VexArgs {
/// Path to the SBOM file
sbom: PathBuf,
/// Apply external VEX document(s) (OpenVEX or CycloneDX VEX). Can be specified multiple times.
#[arg(long = "vex", value_name = "PATH")]
vex: Vec<PathBuf>,
/// Output format (json, summary, table)
#[arg(short, long, default_value = "auto")]
output: ReportFormat,
/// Output file path (stdout if not specified)
#[arg(short = 'O', long)]
output_file: Option<PathBuf>,
/// Only show actionable vulnerabilities (exclude NotAffected/Fixed).
/// For `filter`: exit code 1 if actionable vulns remain.
/// For `status`: exit code 1 if actionable vulns exist.
#[arg(long)]
actionable_only: bool,
/// Filter by VEX state (not_affected, affected, fixed, under_investigation, none)
#[arg(long, value_parser = validate_vex_state)]
state: Option<String>,
/// Enable OSV vulnerability enrichment before VEX overlay
#[arg(long)]
enrich_vulns: bool,
/// Enable end-of-life detection
#[arg(long)]
enrich_eol: bool,
/// Cache directory for enrichment data
#[arg(long)]
vuln_cache_dir: Option<PathBuf>,
/// Cache TTL in hours
#[arg(long, default_value = "24")]
vuln_cache_ttl: u64,
/// Bypass cache and fetch fresh data
#[arg(long)]
refresh_vulns: bool,
/// API timeout in seconds
#[arg(long, default_value = "30")]
api_timeout: u64,
}
/// Sub-subcommands for the `verify` command
#[derive(Subcommand)]
enum VerifyAction {
/// Verify file integrity against a hash value
Hash {
/// SBOM file to verify
file: PathBuf,
/// Expected hash (sha256:<hex>, sha512:<hex>, or bare hex)
#[arg(long)]
expected: Option<String>,
/// Read expected hash from a file (e.g., sbom.json.sha256)
#[arg(long, conflicts_with = "expected")]
hash_file: Option<PathBuf>,
},
/// Audit component hashes within an SBOM
AuditHashes {
/// SBOM file to audit
file: PathBuf,
/// Output format (table or json)
#[arg(
short = 'f',
long = "output",
alias = "format",
default_value = "table"
)]
format: String,
},
}
/// Arguments for the `license-check` subcommand
#[derive(Parser)]
#[command(after_help = "EXAMPLES:
sbom-tools license-check app.cdx.json # Default policy
sbom-tools license-check app.cdx.json --strict # Permissive-only
sbom-tools license-check app.cdx.json --policy policy.json # Custom policy
sbom-tools license-check app.cdx.json --check-propagation # Dep tree analysis")]
struct LicenseCheckArgs {
/// SBOM file to check
file: PathBuf,
/// Path to license policy config file (JSON)
#[arg(long)]
policy: Option<PathBuf>,
/// Check license propagation through dependency tree
#[arg(long)]
check_propagation: bool,
/// Use strict permissive-only policy (default is permissive)
#[arg(long)]
strict: bool,
/// Output format (table or json)
#[arg(
short = 'f',
long = "output",
alias = "format",
default_value = "table"
)]
output_format: String,
}
/// Arguments for the `enrich` subcommand
#[cfg(feature = "enrichment")]
#[derive(Parser)]
#[command(after_help = "EXAMPLES:
sbom-tools enrich app.cdx.json --enrich-vulns # Add OSV vulns
sbom-tools enrich app.cdx.json --enrich-vulns --enrich-eol # Vulns + EOL
sbom-tools enrich app.cdx.json --enrich-vulns -O enriched.json # Save to file
sbom-tools enrich app.cdx.json --vex vex.json --enrich-vulns # With VEX overlay")]
struct EnrichArgs {
/// SBOM file to enrich
file: PathBuf,
/// Output file (stdout if not specified)
#[arg(short = 'O', long)]
output_file: Option<PathBuf>,
#[command(flatten)]
enrichment: SharedEnrichmentArgs,
}
/// Arguments for the `tailor` subcommand
#[derive(Parser)]
#[command(after_help = "EXAMPLES:
sbom-tools tailor app.cdx.json --exclude-ecosystems npm # Remove npm deps
sbom-tools tailor app.cdx.json --include-name \"my-org/*\" # Keep only org pkgs
sbom-tools tailor app.cdx.json --strip-vulns -O clean.json # Remove vuln data
sbom-tools tailor app.cdx.json --include-types library,framework")]
struct TailorArgs {
/// SBOM file to tailor
file: PathBuf,
/// Output file (stdout if not specified)
#[arg(short = 'O', long)]
output_file: Option<PathBuf>,
/// Include only components matching this name pattern
#[arg(long)]
include_name: Option<String>,
/// Include only these component types (comma-separated)
#[arg(long)]
include_types: Option<String>,
/// Exclude these ecosystems (comma-separated)
#[arg(long)]
exclude_ecosystems: Option<String>,
/// Strip vulnerability data from output
#[arg(long)]
strip_vulns: bool,
/// Strip extension/property data
#[arg(long)]
strip_extensions: bool,
}
/// Arguments for the `merge` subcommand
#[derive(Parser)]
#[command(after_help = "EXAMPLES:
sbom-tools merge primary.json secondary.json # Merge to stdout
sbom-tools merge primary.json secondary.json -O combined.json # Merge to file
sbom-tools merge primary.json secondary.json --dedup purl # Deduplicate by PURL")]
struct MergeArgs {
/// Primary SBOM (provides document metadata)
primary: PathBuf,
/// Secondary SBOM to merge into primary
secondary: PathBuf,
/// Output file (stdout if not specified)
#[arg(short = 'O', long)]
output_file: Option<PathBuf>,
/// Deduplication strategy (name, purl, none)
#[arg(long, default_value = "name")]
dedup: String,
}
/// Validate VEX state filter values at the CLI boundary.
fn validate_vex_state(s: &str) -> std::result::Result<String, String> {
match s.to_lowercase().as_str() {
"not_affected"
| "notaffected"
| "affected"
| "fixed"
| "under_investigation"
| "underinvestigation"
| "in_triage"
| "none"
| "missing" => Ok(s.to_string()),
_ => Err(format!(
"unknown VEX state: '{s}'. Valid values: \
not_affected, affected, fixed, under_investigation, none"
)),
}
}
fn main() -> Result<()> {
let cli = Cli::parse();
// Initialize logging
let log_level = if cli.verbose { "debug" } else { "info" };
tracing_subscriber::registry()
.with(tracing_subscriber::EnvFilter::new(
std::env::var("RUST_LOG").unwrap_or_else(|_| log_level.to_string()),
))
.with(tracing_subscriber::fmt::layer().with_target(false))
.init();
// Dispatch to command handlers
match cli.command {
Commands::Diff(args) => {
let enrichment = args.enrichment.to_enrichment_config();
let config = DiffConfig {
paths: DiffPaths {
old: args.old,
new: args.new,
},
output: OutputConfig {
format: args.output,
file: args.output_file,
report_types: args.reports,
no_color: cli.no_color,
streaming: sbom_tools::config::StreamingConfig {
threshold_bytes: args.streaming_threshold * 1024 * 1024,
force: args.streaming,
disabled: false,
stream_stdin: true,
},
export_template: cli.export_template.clone(),
},
matching: MatchingConfig {
fuzzy_preset: args.fuzzy_preset.parse().unwrap_or_default(),
threshold: None,
include_unchanged: args.include_unchanged,
},
filtering: FilterConfig {
only_changes: args.only_changes,
min_severity: args.severity,
exclude_vex_resolved: args.exclude_vex_resolved,
fail_on_vex_gap: args.fail_on_vex_gap,
},
behavior: BehaviorConfig {
fail_on_vuln: args.fail_on_vuln,
fail_on_change: args.fail_on_change,
quiet: cli.quiet,
explain_matches: args.explain_matches,
recommend_threshold: args.recommend_threshold,
},
graph_diff: if args.graph_diff {
let mut gdc = GraphAwareDiffConfig::enabled();
gdc.max_depth = args.graph_max_depth;
if args.graph_impact_threshold != "low" {
gdc.impact_threshold = Some(args.graph_impact_threshold.clone());
}
if let Some(ref rels) = args.graph_relations {
gdc.relation_filter =
rels.split(',').map(|s| s.trim().to_string()).collect();
}
gdc
} else {
GraphAwareDiffConfig::default()
},
rules: MatchingRulesPathConfig {
rules_file: args.enrichment.matching_rules,
dry_run: args.dry_run_rules,
},
ecosystem_rules: EcosystemRulesConfig {
config_file: args.ecosystem_rules,
disabled: args.no_ecosystem_rules,
detect_typosquats: args.detect_typosquats,
},
enrichment,
};
let exit_code = cli::run_diff(config)?;
if exit_code != 0 {
std::process::exit(exit_code);
}
Ok(())
}
Commands::View(args) => {
let enrichment = args.enrichment.to_enrichment_config();
let config = ViewConfig {
sbom_path: args.sbom,
output: OutputConfig {
format: args.output,
file: args.output_file,
report_types: ReportType::All,
no_color: cli.no_color,
streaming: sbom_tools::config::StreamingConfig::default(),
export_template: cli.export_template.clone(),
},
validate_ntia: args.validate_ntia,
min_severity: args.severity,
vulnerable_only: args.vulnerable_only,
ecosystem_filter: args.ecosystem,
fail_on_vuln: args.fail_on_vuln,
bom_profile: args
.bom_type
.as_deref()
.and_then(sbom_tools::BomProfile::from_str_opt),
enrichment,
};
let exit_code = cli::run_view(config)?;
if exit_code != 0 {
std::process::exit(exit_code);
}
Ok(())
}
Commands::Validate(args) => cli::run_validate(
args.sbom,
args.standard,
args.output,
args.output_file,
args.fail_on_warning,
args.summary,
),
Commands::DiffMulti(args) => {
let enrichment = args.enrichment.to_enrichment_config();
let config = MultiDiffConfig {
baseline: args.baseline,
targets: args.targets,
output: OutputConfig {
format: args.output,
file: args.output_file,
no_color: cli.no_color,
export_template: cli.export_template.clone(),
..Default::default()
},
matching: MatchingConfig {
fuzzy_preset: args.fuzzy_preset.parse().unwrap_or_default(),
include_unchanged: args.include_unchanged,
..Default::default()
},
filtering: FilterConfig {
min_severity: args.severity,
exclude_vex_resolved: args.exclude_vex_resolved,
fail_on_vex_gap: args.fail_on_vex_gap,
..Default::default()
},
behavior: BehaviorConfig {
fail_on_vuln: args.fail_on_vuln,
fail_on_change: args.fail_on_change,
quiet: cli.quiet,
..Default::default()
},
graph_diff: if args.graph_diff {
let mut gdc = GraphAwareDiffConfig::enabled();
gdc.max_depth = args.graph_max_depth;
if args.graph_impact_threshold != "low" {
gdc.impact_threshold = Some(args.graph_impact_threshold.clone());
}
if let Some(ref rels) = args.graph_relations {
gdc.relation_filter =
rels.split(',').map(|s| s.trim().to_string()).collect();
}
gdc
} else {
GraphAwareDiffConfig::default()
},
rules: MatchingRulesPathConfig {
rules_file: args.enrichment.matching_rules,
..Default::default()
},
ecosystem_rules: Default::default(),
enrichment,
};
let exit_code = cli::run_diff_multi(config)?;
if exit_code != 0 {
std::process::exit(exit_code);
}
Ok(())
}
Commands::Timeline(args) => {
let enrichment = args.enrichment.to_enrichment_config();
let config = TimelineConfig {
sbom_paths: args.sboms,
output: OutputConfig {
format: args.output,
file: args.output_file,
no_color: cli.no_color,
export_template: cli.export_template.clone(),
..Default::default()
},
matching: MatchingConfig {
fuzzy_preset: args.fuzzy_preset.parse().unwrap_or_default(),
..Default::default()
},
filtering: FilterConfig {
min_severity: args.severity,
exclude_vex_resolved: args.exclude_vex_resolved,
fail_on_vex_gap: args.fail_on_vex_gap,
..Default::default()
},
behavior: BehaviorConfig {
fail_on_vuln: args.fail_on_vuln,
fail_on_change: args.fail_on_change,
quiet: cli.quiet,
..Default::default()
},
graph_diff: if args.graph_diff {
let mut gdc = GraphAwareDiffConfig::enabled();
gdc.max_depth = args.graph_max_depth;
if args.graph_impact_threshold != "low" {
gdc.impact_threshold = Some(args.graph_impact_threshold.clone());
}
if let Some(ref rels) = args.graph_relations {
gdc.relation_filter =
rels.split(',').map(|s| s.trim().to_string()).collect();
}
gdc
} else {
GraphAwareDiffConfig::default()
},
rules: MatchingRulesPathConfig {
rules_file: args.enrichment.matching_rules,
..Default::default()
},
ecosystem_rules: Default::default(),
enrichment,
};
let exit_code = cli::run_timeline(config)?;
if exit_code != 0 {
std::process::exit(exit_code);
}
Ok(())
}
Commands::Matrix(args) => {
let enrichment = args.enrichment.to_enrichment_config();
let config = MatrixConfig {
sbom_paths: args.sboms,
output: OutputConfig {
format: args.output,
file: args.output_file,
no_color: cli.no_color,
export_template: cli.export_template.clone(),
..Default::default()
},
matching: MatchingConfig {
fuzzy_preset: args.fuzzy_preset.parse().unwrap_or_default(),
..Default::default()
},
cluster_threshold: args.cluster_threshold,
filtering: FilterConfig {
min_severity: args.severity,
exclude_vex_resolved: args.exclude_vex_resolved,
fail_on_vex_gap: args.fail_on_vex_gap,
..Default::default()
},
behavior: BehaviorConfig {
fail_on_vuln: args.fail_on_vuln,
fail_on_change: args.fail_on_change,
quiet: cli.quiet,
..Default::default()
},
graph_diff: if args.graph_diff {
let mut gdc = GraphAwareDiffConfig::enabled();
gdc.max_depth = args.graph_max_depth;
if args.graph_impact_threshold != "low" {
gdc.impact_threshold = Some(args.graph_impact_threshold.clone());
}
if let Some(ref rels) = args.graph_relations {
gdc.relation_filter =
rels.split(',').map(|s| s.trim().to_string()).collect();
}
gdc
} else {
GraphAwareDiffConfig::default()
},
rules: MatchingRulesPathConfig {
rules_file: args.enrichment.matching_rules,
..Default::default()
},
ecosystem_rules: Default::default(),
enrichment,
};
let exit_code = cli::run_matrix(config)?;
if exit_code != 0 {
std::process::exit(exit_code);
}
Ok(())
}
Commands::Quality(args) => {
let exit_code = cli::run_quality(
args.sbom,
args.profile,
args.output,
args.output_file,
args.recommendations,
args.metrics,
args.min_score,
cli.no_color,
)?;
if exit_code != 0 {
std::process::exit(exit_code);
}
Ok(())
}
Commands::Query(args) => {
// Split positional args: first arg is pattern if it doesn't look like a file,
// otherwise all args are file paths
let (pattern, sbom_paths) = split_query_args(&args.args);
if sbom_paths.is_empty() {
anyhow::bail!("No SBOM files specified. Usage: sbom-tools query [PATTERN] FILE...");
}
let enrichment = args.enrichment.to_enrichment_config();
let quantum_safe_filter = if args.quantum_safe {
Some(true)
} else if args.quantum_vulnerable {
Some(false)
} else {
None
};
let filter = cli::QueryFilter {
pattern,
name: args.name,
purl: args.purl,
version: args.version,
license: args.license,
ecosystem: args.ecosystem,
supplier: args.supplier,
affected_by: args.affected_by,
crypto_type: args.crypto_type,
algorithm_family: args.algorithm_family,
quantum_safe: quantum_safe_filter,
};
let config = QueryConfig {
sbom_paths,
output: OutputConfig {
format: args.output,
file: args.output_file,
report_types: ReportType::All,
no_color: cli.no_color,
streaming: sbom_tools::config::StreamingConfig::default(),
export_template: None,
},
enrichment,
limit: args.limit,
group_by_sbom: args.group_by_sbom,
};
cli::run_query(config, filter)
}
Commands::Vex { action } => {
let (args, cli_action) = match action {
VexAction::Apply(args) => (args, cli::VexAction::Apply),
VexAction::Status(args) => (args, cli::VexAction::Status),
VexAction::Filter(args) => (args, cli::VexAction::Filter),
};
let enrichment = EnrichmentConfig {
enabled: args.enrich_vulns,
provider: "osv".to_string(),
cache_ttl_hours: args.vuln_cache_ttl,
max_concurrent: 10,
cache_dir: args.vuln_cache_dir.or_else(|| Some(dirs::osv_cache_dir())),
bypass_cache: args.refresh_vulns,
timeout_secs: args.api_timeout,
enable_eol: args.enrich_eol,
vex_paths: Vec::new(), // VEX paths handled separately
};
let config = sbom_tools::config::VexConfig {
sbom_path: args.sbom,
vex_paths: args.vex,
output_format: args.output,
output_file: args.output_file,
quiet: cli.quiet,
actionable_only: args.actionable_only,
filter_state: args.state,
enrichment,
};
let exit_code = cli::run_vex(config, cli_action)?;
if exit_code != 0 {
std::process::exit(exit_code);
}
Ok(())
}
Commands::Watch(args) => {
let enrichment = args.enrichment.to_enrichment_config();
let config = WatchConfig {
watch_dirs: args.dirs,
poll_interval: parse_duration(&args.interval)?,
enrich_interval: parse_duration(&args.enrich_interval)?,
debounce: parse_duration(&args.debounce)?,
output: OutputConfig {
format: args.output,
file: args.output_file,
report_types: ReportType::All,
no_color: cli.no_color,
streaming: sbom_tools::config::StreamingConfig::default(),
export_template: None,
},
enrichment,
webhook_url: args.webhook,
exit_on_change: args.exit_on_change,
max_snapshots: args.max_snapshots,
quiet: cli.quiet,
dry_run: args.dry_run,
};
cli::run_watch(config)
}
Commands::Completions { shell } => {
generate(shell, &mut Cli::command(), "sbom-tools", &mut io::stdout());
Ok(())
}
Commands::ConfigSchema { output } => {
let schema = sbom_tools::config::generate_json_schema();
match output {
Some(path) => {
std::fs::write(&path, &schema)?;
eprintln!("Schema written to {}", path.display());
}
None => {
println!("{schema}");
}
}
Ok(())
}
Commands::Config { action } => match action {
ConfigAction::Show => {
let (config, loaded_from) =
sbom_tools::config::load_or_default(cli.config.as_deref());
if let Some(path) = &loaded_from {
eprintln!("# Loaded from: {}", path.display());
} else {
eprintln!("# No config file found; showing defaults");
}
let yaml =
serde_yaml_ng::to_string(&config).context("failed to serialize config")?;
print!("{yaml}");
Ok(())
}
ConfigAction::Path => {
let search_paths: [Option<String>; 3] = [
std::env::current_dir()
.ok()
.map(|p| p.display().to_string()),
::dirs::config_dir().map(|p| p.join("sbom-tools").display().to_string()),
::dirs::home_dir().map(|p| p.display().to_string()),
];
eprintln!("Config file search paths (in order):");
for path in search_paths.into_iter().flatten() {
eprintln!(" {path}");
}
eprintln!();
eprintln!("Recognized file names:");
for name in &[
".sbom-tools.yaml",
".sbom-tools.yml",
"sbom-tools.yaml",
"sbom-tools.yml",
".sbom-toolsrc",
] {
eprintln!(" {name}");
}
eprintln!();
match sbom_tools::config::discover_config_file(cli.config.as_deref()) {
Some(path) => eprintln!("Active config file: {}", path.display()),
None => eprintln!("No config file found."),
}
Ok(())
}
ConfigAction::Init => {
let target = std::env::current_dir()
.context("cannot determine current directory")?
.join(".sbom-tools.yaml");
if target.exists() {
anyhow::bail!(
"{} already exists. Remove it first to re-initialize.",
target.display()
);
}
let content = sbom_tools::config::generate_full_example_config();
std::fs::write(&target, content)
.with_context(|| format!("failed to write {}", target.display()))?;
eprintln!("Created {}", target.display());
Ok(())
}
},
Commands::Verify { action } => {
let cli_action = match action {
VerifyAction::Hash {
file,
expected,
hash_file,
} => cli::VerifyAction::Hash {
file,
expected,
hash_file,
},
VerifyAction::AuditHashes { file, format } => {
cli::VerifyAction::AuditHashes { file, format }
}
};
let exit_code = cli::run_verify(cli_action, cli.quiet)?;
if exit_code != 0 {
std::process::exit(exit_code);
}
Ok(())
}
Commands::LicenseCheck(args) => {
let exit_code = cli::run_license_check(
&args.file,
args.policy.as_ref(),
args.check_propagation,
args.strict,
&args.output_format,
cli.quiet,
)?;
if exit_code != 0 {
std::process::exit(exit_code);
}
Ok(())
}
#[cfg(feature = "enrichment")]
Commands::Enrich(args) => {
let enrichment = args.enrichment.to_enrichment_config();
let exit_code =
cli::run_enrich(&args.file, args.output_file.as_ref(), enrichment, cli.quiet)?;
if exit_code != 0 {
std::process::exit(exit_code);
}
Ok(())
}
Commands::Tailor(args) => {
let config = sbom_tools::serialization::TailorConfig {
include_name_pattern: args.include_name,
include_types: args
.include_types
.map(|s| s.split(',').map(|t| t.trim().to_string()).collect())
.unwrap_or_default(),
exclude_ecosystems: args
.exclude_ecosystems
.map(|s| s.split(',').map(|e| e.trim().to_string()).collect())
.unwrap_or_default(),
strip_vulns: args.strip_vulns,
strip_extensions: args.strip_extensions,
..Default::default()
};
let exit_code =
cli::run_tailor(&args.file, args.output_file.as_ref(), config, cli.quiet)?;
if exit_code != 0 {
std::process::exit(exit_code);
}
Ok(())
}
Commands::Merge(args) => {
let dedup_strategy = match args.dedup.to_lowercase().as_str() {
"purl" => sbom_tools::serialization::DeduplicationStrategy::Purl,
"none" => sbom_tools::serialization::DeduplicationStrategy::None,
_ => sbom_tools::serialization::DeduplicationStrategy::Name,
};
let config = sbom_tools::serialization::MergeConfig { dedup_strategy };
let exit_code = cli::run_merge(
&args.primary,
&args.secondary,
args.output_file.as_ref(),
config,
cli.quiet,
)?;
if exit_code != 0 {
std::process::exit(exit_code);
}
Ok(())
}
Commands::Man => {
let cmd = Cli::command();
let man = clap_mangen::Man::new(cmd);
let mut buf = Vec::new();
man.render(&mut buf).context("failed to render man page")?;
io::stdout().write_all(&buf)?;
Ok(())
}
}
}
/// Split positional args into (optional pattern, file paths).
///
/// The first argument is treated as a search pattern unless it clearly looks
/// like a file path: contains a path separator, has a known SBOM file extension,
/// or is an existing file on disk.
fn split_query_args(args: &[String]) -> (Option<String>, Vec<PathBuf>) {
if args.is_empty() {
return (None, Vec::new());
}
let first = &args[0];
let looks_like_file = first.contains(std::path::MAIN_SEPARATOR)
|| first.contains('/')
|| has_sbom_extension(first)
|| Path::new(first).is_file();
if looks_like_file {
// All args are file paths
(None, args.iter().map(PathBuf::from).collect())
} else {
// First arg is pattern, rest are file paths
let pattern = Some(first.clone());
let paths = args[1..].iter().map(PathBuf::from).collect();
(pattern, paths)
}
}
/// Check if a string has a known SBOM file extension.
fn has_sbom_extension(s: &str) -> bool {
let lower = s.to_lowercase();
lower.ends_with(".json")
|| lower.ends_with(".xml")
|| lower.ends_with(".spdx")
|| lower.ends_with(".cdx")
|| lower.ends_with(".yaml")
|| lower.ends_with(".yml")
|| lower.ends_with(".rdf")
}