cgx-core 0.0.6

Core library for cgx, the Rust equivalent of uvx or npx for running Rust crates quickly and easily
Documentation
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
use crate::{
    Result,
    cache::Cache,
    cargo::{CargoMetadataOptions, CargoRunner, CargoVerbosity, Metadata},
    cli::CliArgs,
    config::Config,
    downloader::DownloadedCrate,
    error,
    resolver::ResolvedSource,
};
use cargo_metadata::Target;
use snafu::ResultExt;
use std::{borrow::Cow, path::PathBuf, sync::Arc};

/// Which executable within a crate to build.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub enum BuildTarget {
    /// No specific target was specified which means build the one and only binary target, or fail
    /// if there are more than one.  Note that as of this writing, the "default" flag on binaries
    /// isn't stabilized and thus isn't supported here, so if there are multiple binaries and one
    /// was not explicitly selected, then this will fail.
    #[default]
    DefaultBin,

    /// A specific binary target to build.
    Bin(String),

    /// A specific example target to build.
    Example(String),
}

/// Options that control how a crate is built.
///
/// These options map to flags passed to `cargo build` (or `cargo install`).
/// They are orthogonal to the crate identity and location (see [`crate::CrateSpec`]),
/// focusing instead on build configuration, feature selection, and compilation settings.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct BuildOptions {
    /// Features to activate (corresponds to `--features`).
    pub features: Vec<String>,

    /// Activate all available features (corresponds to `--all-features`).
    pub all_features: bool,

    /// Do not activate the `default` feature (corresponds to `--no-default-features`).
    pub no_default_features: bool,

    /// Build profile to use (corresponds to `--profile`).
    ///
    /// When `None`, the default release profile is used.
    /// Use `Some("dev")` for debug builds.
    pub profile: Option<String>,

    /// Target triple for cross-compilation (corresponds to `--target`).
    pub target: Option<String>,

    /// Require that `Cargo.lock` remains unchanged (corresponds to `--locked`).
    pub locked: bool,

    /// Run without accessing the network (corresponds to `--offline`).
    pub offline: bool,

    /// Number of parallel jobs for compilation (corresponds to `-j`/`--jobs`).
    ///
    /// When `None`, cargo uses its default (number of CPUs).
    pub jobs: Option<usize>,

    /// Ignore `rust-version` specification in packages (corresponds to `--ignore-rust-version`).
    pub ignore_rust_version: bool,

    /// Which executable within the crate to build.
    pub build_target: BuildTarget,

    /// Rust toolchain override to use for this build (e.g., "nightly", "1.70.0", "stable").
    ///
    /// When set, cargo will be invoked with `+{toolchain}` prefix, allowing rustup to
    /// select the appropriate toolchain.
    pub toolchain: Option<String>,

    /// Verbosity level for cargo build output.
    ///
    /// Controls the `-v` flags passed to cargo build commands.
    pub cargo_verbosity: CargoVerbosity,
}

impl Default for BuildOptions {
    fn default() -> Self {
        Self {
            features: Vec::new(),
            all_features: false,
            no_default_features: false,
            profile: None,
            target: None,
            locked: true,
            offline: false,
            jobs: None,
            ignore_rust_version: false,
            build_target: BuildTarget::default(),
            toolchain: None,
            cargo_verbosity: CargoVerbosity::default(),
        }
    }
}

impl BuildOptions {
    /// Load build options from config and CLI args, with proper precedence.
    pub fn load(config: &Config, args: &CliArgs) -> Result<Self> {
        // Parse features from CLI string (space or comma separated)
        let features = if let Some(features_str) = &args.features {
            Self::parse_features(features_str)
        } else {
            Vec::new()
        };

        // Profile: CLI --debug maps to "dev", otherwise use explicit --profile value
        let profile = if args.debug {
            Some("dev".to_string())
        } else {
            args.profile.clone()
        };

        // Build target: --bin, --example, or default
        let build_target = match (&args.bin, &args.example) {
            (Some(_), Some(_)) => {
                unreachable!("BUG: clap should enforce mutual exclusivity");
            }
            (Some(bin_name), None) => BuildTarget::Bin(bin_name.clone()),
            (None, Some(example_name)) => BuildTarget::Example(example_name.clone()),
            (None, None) => BuildTarget::default(),
        };

        // Locked/offline: --frozen implies both
        // --unlocked overrides everything to set locked=false
        // Priority: --unlocked > --frozen/--locked > config > true (default)
        let locked = if args.unlocked {
            false
        } else {
            args.locked || args.frozen || config.locked
        };
        let offline = args.offline || args.frozen || config.offline;

        // Toolchain: CLI args take precedence over config
        let toolchain = args.toolchain.clone().or_else(|| config.toolchain.clone());

        Ok(BuildOptions {
            features,
            all_features: args.all_features,
            no_default_features: args.no_default_features,
            profile,
            target: args.target.clone(),
            locked,
            offline,
            jobs: args.jobs,
            ignore_rust_version: args.ignore_rust_version,
            build_target,
            toolchain,
            cargo_verbosity: CargoVerbosity::from_count(args.verbose),
        })
    }

    /// Parse a feature string into a vector of feature names.
    ///
    /// Handles both comma-separated and space-separated features.
    fn parse_features(features_str: &str) -> Vec<String> {
        features_str
            .split(|c: char| c == ',' || c.is_whitespace())
            .filter(|s| !s.is_empty())
            .map(|s| s.to_string())
            .collect()
    }
}

pub trait CrateBuilder {
    /// List the targets in the given crate that can be build using [`Self::build`].
    ///
    /// [`Self::build`] can run any bin or example target in the crate.
    ///
    /// Returns a tuple of:
    /// - The default target, if any (i.e., the one that would be built if no explicit target is
    ///   specified)
    /// - A list of all binary targets
    /// - A list of all example targets
    fn list_targets(
        &self,
        krate: &DownloadedCrate,
        options: &BuildOptions,
    ) -> Result<(Option<Target>, Vec<Target>, Vec<Target>)>;

    /// Produce a compiled binary from the given crate, using the specified build options.
    ///
    /// Compiled crates are also cached, so this may or may not actually compile anything,
    /// depending on the state of the cache and the config.
    ///
    /// Returns the full path to the compiled binary on success.
    fn build(&self, krate: &DownloadedCrate, options: &BuildOptions) -> Result<PathBuf>;
}

pub(crate) fn create_builder(
    config: Config,
    cache: Cache,
    cargo_runner: Arc<dyn CargoRunner>,
) -> impl CrateBuilder {
    RealCrateBuilder {
        config,
        cache,
        cargo_runner,
    }
}

/// Builder which is responsible for compiling a specific binary target in a crate, from source.
struct RealCrateBuilder {
    config: Config,
    cache: Cache,
    cargo_runner: Arc<dyn CargoRunner>,
}

impl CrateBuilder for RealCrateBuilder {
    fn list_targets(
        &self,
        krate: &DownloadedCrate,
        options: &BuildOptions,
    ) -> Result<(Option<Target>, Vec<Target>, Vec<Target>)> {
        let metadata = self
            .cargo_runner
            .metadata(&krate.crate_path, &CargoMetadataOptions::from(options))?;

        Self::list_targets_internal(krate, &metadata)
    }

    fn build(&self, krate: &DownloadedCrate, options: &BuildOptions) -> Result<PathBuf> {
        // Gather metadata about the crate in its current source form.
        // The act of building will re-gather the metadata after the build, but this is needed to
        // resolve target and package information before building.
        let metadata = self
            .cargo_runner
            .metadata(&krate.crate_path, &CargoMetadataOptions::from(options))?;

        // If the user has not specified an explicit binary target, attempt to resolve it now.
        // If the crate has multiple (or no) binary targets, this is the time to fail fast.
        // Plus the cache needs to know the actual binary name, not DefaultBin.
        let options: Cow<'_, BuildOptions> = if matches!(options.build_target, BuildTarget::DefaultBin) {
            Cow::Owned(BuildOptions {
                build_target: Self::resolve_binary_target(krate, options, &metadata)?,
                ..options.clone()
            })
        } else {
            Cow::Borrowed(options)
        };

        // Crates resolved from local sources are, by definition, local.  Not only does that mean
        // that they are on a local filesystem (and presumably fast to access), but it also means
        // that their source contents are mutable.  Even if we wanted to cache them, we would need
        // a way to detect if any changes had occurred since the last build (basically what `cargo
        // build` does), and that doesn't seem worth it.  So local crates are always built directly
        // from their sources, and never cached
        if matches!(krate.resolved.source, ResolvedSource::LocalDir { .. }) {
            let (binary_path, _sbom) = self.build_uncached(krate, options.as_ref(), &metadata)?;
            return Ok(binary_path);
        }

        self.cache
            .get_or_build_binary(&krate.resolved, options.as_ref(), || {
                self.build_uncached(krate, options.as_ref(), &metadata)
            })
    }
}

impl RealCrateBuilder {
    /// List the targets in the given crate that can be build using [`Self::build`].
    ///
    /// Unlike the public [`CrateBuilder::list_targets`], this internal version takes the cargo
    /// metadata as an argument, allowing it to be reused and avoid redundant metadata queries.
    fn list_targets_internal(
        krate: &DownloadedCrate,
        metadata: &Metadata,
    ) -> Result<(Option<Target>, Vec<Target>, Vec<Target>)> {
        // Find the crate package in metadata
        let package = metadata
            .packages
            .iter()
            .find(|p| p.name.as_str() == krate.resolved.name)
            .ok_or_else(|| {
                error::PackageNotFoundInWorkspaceSnafu {
                    name: krate.resolved.name.clone(),
                    available: metadata
                        .packages
                        .iter()
                        .map(|p| p.name.to_string())
                        .collect::<Vec<_>>(),
                }
                .build()
            })?;

        // Get all bin and example targets in the package, since those are the only kinds that we
        // support running with `cgx`
        let bin_targets: Vec<_> = package
            .targets
            .iter()
            .filter(|t| {
                t.kind
                    .iter()
                    .any(|k| matches!(k, cargo_metadata::TargetKind::Bin))
            })
            .cloned()
            .collect();
        let example_targets: Vec<_> = package
            .targets
            .iter()
            .filter(|t| {
                t.kind
                    .iter()
                    .any(|k| matches!(k, cargo_metadata::TargetKind::Example))
            })
            .cloned()
            .collect();

        // If an explicit bin was specified in `default_run`, use that as the default target
        let default = package.default_run.as_ref().and_then(|default_run| {
            bin_targets
                .iter()
                .find(|t| t.name == default_run.as_str())
                .cloned()
        });

        Ok((default, bin_targets, example_targets))
    }

    /// Resolve [`BuildTarget`] to an actual binary name before building or caching.
    ///
    /// This not only validates that, if an explicit target was specified, that it actually exists,
    /// but also resolves the `DefaultBin` case to a specific binary name.
    ///
    /// Returns an explicit [`BuildTarget`] guaranteed not to be `DefaultBin`, or an error if
    /// resolution fails.
    fn resolve_binary_target(
        krate: &DownloadedCrate,
        options: &BuildOptions,
        metadata: &Metadata,
    ) -> Result<BuildTarget> {
        let (default, bins, examples) = Self::list_targets_internal(krate, metadata)?;

        // If no explicit target was specified but the crate package has `default_run`, use that
        let build_target = if matches!(options.build_target, BuildTarget::DefaultBin) {
            if let Some(default) = default {
                BuildTarget::Bin(default.name.clone())
            } else {
                BuildTarget::DefaultBin
            }
        } else {
            options.build_target.clone()
        };

        // Select a specific build target.  There are a few possible permutations here:
        // - The user didn't explicitly ask for a particular target, but the package has a
        // `default_run`, so act like the user specified that explicitly and proceed further.
        // - The user specified an explicit bin or example; just need to verify that it's in the
        // runnable targets, fail if it's not, then we're good
        // - The user didn't explicitly ask for a particular target, and the package does not have
        // a `default_run`.  If the package has exactly one binary, use that.  If it has no
        // binaries, fail.  If it has multiple binaries, fail.

        match build_target {
            BuildTarget::DefaultBin => {
                // No explicit target, no default_run - must have exactly one binary
                match bins.len() {
                    0 => {
                        // No binary targets - this will fail later when cargo tries to build
                        error::NoPackageBinariesSnafu {
                            krate: krate.resolved.name.clone(),
                        }
                        .fail()
                    }
                    1 => {
                        // Exactly one binary, use it
                        Ok(BuildTarget::Bin(bins[0].name.clone()))
                    }
                    _ => {
                        // Multiple binaries - ambiguous
                        error::AmbiguousBinaryTargetSnafu {
                            package: krate.resolved.name.clone(),
                            available: bins.iter().map(|t| t.name.clone()).collect::<Vec<_>>(),
                        }
                        .fail()
                    }
                }
            }
            BuildTarget::Bin(ref name) => {
                // Explicit binary target - verify it exists
                if bins.iter().any(|t| t.name == *name) {
                    Ok(build_target)
                } else {
                    error::RunnableTargetNotFoundSnafu {
                        kind: "binary",
                        package: krate.resolved.name.clone(),
                        target: name.clone(),
                        available: bins.iter().map(|t| t.name.clone()).collect::<Vec<_>>(),
                    }
                    .fail()
                }
            }
            BuildTarget::Example(ref name) => {
                // Explicit example target - verify it exists
                if examples.iter().any(|t| t.name == *name) {
                    Ok(build_target)
                } else {
                    error::RunnableTargetNotFoundSnafu {
                        kind: "example",
                        package: krate.resolved.name.clone(),
                        target: name.clone(),
                        available: bins.iter().map(|t| t.name.clone()).collect::<Vec<_>>(),
                    }
                    .fail()
                }
            }
        }
    }

    /// Build the crate from source as-is, as well as the SBOM for the as-built crate, without any
    /// caching.
    ///
    /// Uses metadata previously gathered from the crate to resolve the package name containing the
    /// crate, but beware that the act of building can and often does modify the metadata,
    /// particularly if there is no Cargo.lock in the source package or if it's out of date and
    /// needs to be updated.
    ///
    /// ## Cargo.lock handling
    ///
    /// We control whether cargo uses locked dependencies via two mechanisms:
    ///
    /// - File presence (`prepare_build_dir`): If options.locked is false, we delete Cargo.lock before
    ///   building, forcing cargo to resolve dependencies fresh.
    ///
    /// - --locked flag (passed to `cargo build` in cargo.rs): If options.locked is true, cargo.rs
    ///   passes --locked to `cargo build`, making it strictly honor the Cargo.lock and fail if
    ///   inconsistent.
    ///
    /// This two-part approach mimics `cargo install` behavior:
    /// - `cargo install --locked`: keeps Cargo.lock + enforces strict adherence (via
    ///   `ws.set_ignore_lock(false)`)
    /// - `cargo install`: ignores/regenerates Cargo.lock with latest compatible versions
    ///
    /// ## Returns
    ///
    /// Returns a tuple of (`binary_path`, `sbom`) where `sbom` is generated from metadata
    /// read from the build directory AFTER the build completes. This ensures the SBOM
    /// reflects the actual dependencies that were resolved and built, not what was
    /// in the source directory's Cargo.lock.
    fn build_uncached(
        &self,
        krate: &DownloadedCrate,
        options: &BuildOptions,
        metadata: &Metadata,
    ) -> Result<(PathBuf, crate::sbom::CycloneDx)> {
        let build_dir = self.prepare_build_dir(krate, options)?;

        let package_name = Self::resolve_package_name(metadata, &krate.resolved.name)?;

        let binary_path = self
            .cargo_runner
            .build(&build_dir, package_name.as_deref(), options)?;

        // Re-read metadata from the build directory AFTER building. This is critical for accurate
        // SBOM generation: if --unlocked was used, Cargo.lock was deleted from the build dir and
        // cargo created a new one with freshly resolved dependencies. Even absent `--unlocked`, if
        // the crate didn't ship with a Cargo.lock or it was outdated, the act of building will
        // update the lock file and resolve potentially different dependencies when building the
        // crate.  Since the SBOM must reflect those actual dependencies, not the stale ones from
        // the source directory, we need to re-read the metadata here.
        let metadata = self
            .cargo_runner
            .metadata(&build_dir, &CargoMetadataOptions::from(options))?;

        // Generate SBOM from the post-build metadata
        let sbom = crate::sbom::generate_sbom(&metadata, &krate.resolved, options)?;

        Ok((binary_path, sbom))
    }

    /// Prepare a build directory from which the crate can be build.
    ///
    /// If the crate is in a local path, then that path is returned directly, meaning what we will
    /// do is equivalent to running `cargo build --release` in that directory.
    ///
    /// For all other crates (e.g., from crates.io or git), a temporary directory is created in the
    /// build dir, and the crate's source files are copied there.  This ensures that any build
    /// artifacts (e.g., `target` directory) are created in a location that is not under the
    /// user's source tree. The temporary directory is not automatically deleted, but is left
    /// for inspection.
    ///
    /// TODO: Fix this so that build dirs are cleaned up after successful builds.
    fn prepare_build_dir(&self, krate: &DownloadedCrate, options: &BuildOptions) -> Result<PathBuf> {
        if let ResolvedSource::LocalDir { .. } = krate.resolved.source {
            return Ok(krate.crate_path.clone());
        }

        std::fs::create_dir_all(&self.config.build_dir).with_context(|_| error::IoSnafu {
            path: self.config.build_dir.clone(),
        })?;

        let temp_dir = tempfile::Builder::new()
            .prefix(&format!("cgx-build-{}", &krate.resolved.name))
            .tempdir_in(&self.config.build_dir)
            .with_context(|_| error::TempDirCreationSnafu {
                parent: self.config.build_dir.clone(),
            })?;

        let temp_path = temp_dir.path().to_path_buf();
        crate::helpers::copy_source_tree(&krate.crate_path, &temp_path)?;

        // If locked is false (--unlocked was passed), delete Cargo.lock
        // to force cargo to resolve dependencies fresh
        if !options.locked {
            let lock_path = temp_path.join("Cargo.lock");
            if lock_path.exists() {
                std::fs::remove_file(&lock_path).with_context(|_| error::IoSnafu { path: lock_path })?;
            }
        }

        let _ = temp_dir.keep();
        Ok(temp_path)
    }

    /// Given metadata for a workspace and the name of a crate, determine the appropriate
    /// `--package` argument to pass to cargo, if any.
    ////
    /// If the workspace has zero or one members, then no `--package` argument is needed, so
    /// `Ok(None)` is returned.  If the workspace has multiple members, then the crate name must
    /// match one of them, and `Ok(Some(name))` is returned.  If it does not match any, then an
    /// error is returned.
    fn resolve_package_name(metadata: &Metadata, crate_name: &str) -> Result<Option<String>> {
        let workspace_members: Vec<_> = metadata
            .workspace_packages()
            .iter()
            .map(|p| p.name.as_str())
            .collect();

        match workspace_members.len() {
            0 | 1 => Ok(None),
            _ => {
                if workspace_members.iter().any(|name| *name == crate_name) {
                    Ok(Some(crate_name.to_string()))
                } else {
                    error::PackageNotFoundInWorkspaceSnafu {
                        name: crate_name.to_string(),
                        available: workspace_members
                            .into_iter()
                            .map(String::from)
                            .collect::<Vec<_>>(),
                    }
                    .fail()
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        cargo::find_cargo,
        error::Error,
        resolver::{ResolvedCrate, ResolvedSource},
        testdata::CrateTestCase,
    };
    use assert_matches::assert_matches;
    use semver::Version;
    use std::{fs, path::Path};

    fn test_builder() -> (RealCrateBuilder, tempfile::TempDir) {
        crate::logging::init_test_logging();

        let (temp_dir, config) = crate::config::create_test_env();

        fs::create_dir_all(&config.cache_dir).unwrap();
        fs::create_dir_all(&config.bin_dir).unwrap();
        fs::create_dir_all(&config.build_dir).unwrap();

        let cache = Cache::new(config.clone());
        let cargo_runner = Arc::new(find_cargo().unwrap());

        let builder = RealCrateBuilder {
            config,
            cache,
            cargo_runner,
        };

        (builder, temp_dir)
    }

    /// Type of fake source to create for testing
    #[derive(Debug, Clone)]
    enum FakeSourceType {
        Registry { version: String },
        Git { url: String, rev: String },
        LocalDir,
    }

    /// Create a fake [`DownloadedCrate`] from a [`TestCase`] for testing different source types
    fn fake_downloaded_crate(
        tc: &CrateTestCase,
        source_type: FakeSourceType,
        package_name: Option<&str>,
    ) -> DownloadedCrate {
        let (resolved_source, crate_path) = match &source_type {
            FakeSourceType::Registry { .. } => {
                // Registry sources only contain the specific crate, not the whole workspace
                let path = if let Some(pkg) = package_name {
                    tc.path().join(pkg)
                } else {
                    tc.path().to_path_buf()
                };
                (ResolvedSource::CratesIo, path)
            }
            FakeSourceType::Git { url, rev } => {
                // Git sources can contain workspaces
                (
                    ResolvedSource::Git {
                        repo: url.clone(),
                        commit: rev.clone(),
                    },
                    tc.path().to_path_buf(),
                )
            }
            FakeSourceType::LocalDir => {
                // LocalDir sources use the path directly
                let path = tc.path().to_path_buf();
                (ResolvedSource::LocalDir { path: path.clone() }, path)
            }
        };

        let name = package_name.unwrap_or(tc.name).to_string();
        let version = match &source_type {
            FakeSourceType::Registry { version } => Version::parse(version).unwrap(),
            _ => Version::parse("0.1.0").unwrap(),
        };

        DownloadedCrate {
            resolved: ResolvedCrate {
                name,
                version,
                source: resolved_source,
            },
            crate_path,
        }
    }

    /// Read the SBOM file for a built binary from the cache
    fn read_sbom_for_binary(binary_path: &Path) -> PathBuf {
        // SBOM is stored at same level as binary with name "sbom.cyclonedx.json"
        binary_path.parent().unwrap().join("sbom.cyclonedx.json")
    }

    /// Get the expected binary name for the current platform.
    ///
    /// On Windows, appends ".exe" extension. On Unix, returns the name unchanged.
    fn expected_bin_name(base_name: &str) -> String {
        format!("{}{}", base_name, std::env::consts::EXE_SUFFIX)
    }

    /// Assert that two builds resulted in a cache hit (same path, same mtime)
    fn assert_cache_hit(path1: &Path, path2: &Path) {
        assert_eq!(
            path1,
            path2,
            "Cache hit expected: paths should be identical\n  path1: {}\n  path2: {}",
            path1.display(),
            path2.display()
        );

        let mtime1 = fs::metadata(path1).unwrap().modified().unwrap();
        let mtime2 = fs::metadata(path2).unwrap().modified().unwrap();

        assert_eq!(
            mtime1,
            mtime2,
            "Cache hit expected: modification times should be identical\n  path1: {}\n  path2: {}",
            path1.display(),
            path2.display()
        );
    }

    /// Assert that two builds resulted in a cache miss (different path OR different mtime)
    fn assert_cache_miss(path1: &Path, path2: &Path) {
        let paths_differ = path1 != path2;
        let mtimes_differ = if path1.exists() && path2.exists() {
            let mtime1 = fs::metadata(path1).unwrap().modified().unwrap();
            let mtime2 = fs::metadata(path2).unwrap().modified().unwrap();
            mtime1 != mtime2
        } else {
            true
        };

        assert!(
            paths_differ || mtimes_differ,
            "Cache miss expected: paths or mtimes should differ\n  path1: {}\n  path2: {}\n  paths_differ: \
             {}\n  mtimes_differ: {}",
            path1.display(),
            path2.display(),
            paths_differ,
            mtimes_differ
        );
    }

    /// Output from running the timestamp test binary.
    #[derive(Debug)]
    struct TimestampOutput {
        build_timestamp: String,
        features: Vec<String>,
    }

    /// Run the timestamp binary and parse its output.
    fn run_timestamp_binary(path: &Path) -> TimestampOutput {
        let output = std::process::Command::new(path)
            .output()
            .unwrap_or_else(|e| panic!("Failed to execute timestamp binary at {}: {}", path.display(), e));

        assert!(
            output.status.success(),
            "Timestamp binary failed with status {}: {}",
            output.status,
            String::from_utf8_lossy(&output.stderr)
        );

        let stdout = String::from_utf8_lossy(&output.stdout);

        let mut build_timestamp = None;
        let mut features = Vec::new();

        for line in stdout.lines() {
            if let Some(ts) = line.strip_prefix("Built at: ") {
                build_timestamp = Some(ts.to_string());
            }
            if let Some(feat_str) = line.strip_prefix("Features enabled: ") {
                if feat_str != "none" {
                    features = feat_str.split(", ").map(|s| s.to_string()).collect();
                }
            }
        }

        TimestampOutput {
            build_timestamp: build_timestamp.expect("No 'Built at:' line in timestamp output"),
            features,
        }
    }

    /// Assert that two builds hit cache by comparing timestamps (should be identical).
    fn assert_cache_hit_by_timestamp(output1: &TimestampOutput, output2: &TimestampOutput) {
        assert_eq!(
            output1.build_timestamp, output2.build_timestamp,
            "Cache hit expected: build timestamps should match\n  ts1: {}\n  ts2: {}",
            output1.build_timestamp, output2.build_timestamp
        );
    }

    /// Assert that two builds missed cache by comparing timestamps (should differ).
    fn assert_cache_miss_by_timestamp(output1: &TimestampOutput, output2: &TimestampOutput) {
        assert_ne!(
            output1.build_timestamp, output2.build_timestamp,
            "Cache miss expected: build timestamps should differ\n  ts1: {}\n  ts2: {}",
            output1.build_timestamp, output2.build_timestamp
        );
    }

    mod smoke_tests {
        use super::*;

        #[test]
        fn builds_all_testcases_with_bins() {
            let (builder, _temp) = test_builder();
            let cargo = find_cargo().unwrap();

            for tc in CrateTestCase::all() {
                let metadata_opts = CargoMetadataOptions::default();
                let metadata = cargo.metadata(tc.path(), &metadata_opts).unwrap();

                let workspace_pkgs = metadata.workspace_packages();
                let buildable_packages: Vec<_> = workspace_pkgs
                    .iter()
                    .filter(|pkg| {
                        pkg.targets.iter().any(|t| {
                            t.kind
                                .iter()
                                .any(|k| matches!(k, cargo_metadata::TargetKind::Bin))
                        })
                    })
                    .collect();

                if buildable_packages.is_empty() {
                    continue;
                }

                for pkg in buildable_packages {
                    let krate = fake_downloaded_crate(
                        &tc,
                        FakeSourceType::Registry {
                            version: "1.0.0".to_string(),
                        },
                        Some(&pkg.name),
                    );

                    let options = BuildOptions {
                        profile: Some("dev".to_string()),
                        ..Default::default()
                    };

                    let result = builder.build(&krate, &options);

                    if let Ok(binary) = result {
                        assert!(binary.exists(), "Binary missing for {}/{}", tc.name, pkg.name);

                        let binary_name = binary.file_name().unwrap().to_str().unwrap();

                        // Determine expected binary name based on package metadata
                        let bin_targets: Vec<_> = pkg
                            .targets
                            .iter()
                            .filter(|t| {
                                t.kind
                                    .iter()
                                    .any(|k| matches!(k, cargo_metadata::TargetKind::Bin))
                            })
                            .collect();

                        let expected_name = if bin_targets.len() == 1 {
                            // Single binary - use its name
                            bin_targets[0].name.as_str()
                        } else if let Some(ref default_run) = pkg.default_run {
                            // Multiple binaries with default - use default
                            default_run.as_str()
                        } else {
                            // Multiple binaries without default - should have failed
                            panic!(
                                "Build succeeded for {}/{} but should have failed due to ambiguous binary \
                                 target",
                                tc.name, pkg.name
                            );
                        };

                        assert_eq!(
                            binary_name,
                            expected_bin_name(expected_name),
                            "Wrong binary name for {}/{}: expected '{}', got '{}'",
                            tc.name,
                            pkg.name,
                            expected_name,
                            binary_name
                        );
                    }
                }
            }
        }

        #[test]
        fn simple_bin_no_deps_from_registry() {
            let (builder, _temp) = test_builder();
            let tc = CrateTestCase::simple_bin_no_deps();
            let krate = fake_downloaded_crate(
                &tc,
                FakeSourceType::Registry {
                    version: "1.0.0".to_string(),
                },
                None,
            );

            let options = BuildOptions {
                profile: Some("dev".to_string()),
                ..Default::default()
            };

            let binary = builder.build(&krate, &options).unwrap();

            assert!(binary.exists());
            assert!(binary.is_file());
            assert!(binary.starts_with(&builder.config.bin_dir));

            let binary_name = binary.file_name().unwrap().to_str().unwrap();
            assert_eq!(binary_name, expected_bin_name("simple-bin-no-deps"));
        }
    }

    mod binary_selection {
        use super::*;

        #[test]
        fn default_bin_selected_automatically() {
            let (builder, _temp) = test_builder();
            let tc = CrateTestCase::single_crate_multiple_bins_with_default();
            let krate = fake_downloaded_crate(
                &tc,
                FakeSourceType::Registry {
                    version: "1.0.0".to_string(),
                },
                None,
            );

            let options = BuildOptions {
                profile: Some("dev".to_string()),
                build_target: BuildTarget::DefaultBin,
                ..Default::default()
            };

            let binary = builder.build(&krate, &options).unwrap();
            assert!(binary.exists());
            let binary_name = binary.file_name().unwrap().to_str().unwrap();
            assert_eq!(
                binary_name,
                expected_bin_name("bin1"),
                "Should build bin1 or the crate's default binary, got: {}",
                binary_name
            );
        }

        #[test]
        fn explicit_bin_overrides_default() {
            let (builder, _temp) = test_builder();
            let tc = CrateTestCase::single_crate_multiple_bins_with_default();
            let krate = fake_downloaded_crate(
                &tc,
                FakeSourceType::Registry {
                    version: "1.0.0".to_string(),
                },
                None,
            );

            let options = BuildOptions {
                profile: Some("dev".to_string()),
                build_target: BuildTarget::Bin("bin2".to_string()),
                ..Default::default()
            };

            let binary = builder.build(&krate, &options).unwrap();
            assert!(binary.exists());
            let binary_name = binary.file_name().unwrap().to_str().unwrap();
            assert_eq!(binary_name, expected_bin_name("bin2"));
        }

        #[test]
        fn multiple_bins_without_default_fails() {
            let (builder, _temp) = test_builder();
            let tc = CrateTestCase::single_crate_multiple_bins();
            let krate = fake_downloaded_crate(
                &tc,
                FakeSourceType::Registry {
                    version: "1.0.0".to_string(),
                },
                None,
            );

            let options = BuildOptions {
                profile: Some("dev".to_string()),
                ..Default::default()
            };

            let result = builder.build(&krate, &options);

            assert_matches!(
                result,
                Err(Error::AmbiguousBinaryTarget { ref package, ref available })
                    if package == "single-crate-multiple-bins"
                        && available.len() == 2
                        && available.contains(&"bin1".to_string())
                        && available.contains(&"bin2".to_string())
            );
        }
    }

    mod workspace_handling {
        use super::*;

        #[test]
        fn workspace_with_correct_package_succeeds() {
            let (builder, _temp) = test_builder();
            let tc = CrateTestCase::workspace_multiple_bin_crates();
            let krate = fake_downloaded_crate(
                &tc,
                FakeSourceType::Git {
                    url: "https://github.com/example/test.git".to_string(),
                    rev: "abc123".to_string(),
                },
                Some("bin1"),
            );

            let options = BuildOptions {
                profile: Some("dev".to_string()),
                ..Default::default()
            };

            let binary = builder.build(&krate, &options).unwrap();
            assert!(binary.exists());

            let binary_name = binary.file_name().unwrap().to_str().unwrap();
            assert_eq!(binary_name, expected_bin_name("bin1"));
        }

        #[test]
        fn workspace_with_wrong_package_fails() {
            let (builder, _temp) = test_builder();
            let tc = CrateTestCase::workspace_multiple_bin_crates();

            let krate = DownloadedCrate {
                resolved: ResolvedCrate {
                    name: "nonexistent-package".to_string(),
                    version: Version::parse("1.0.0").unwrap(),
                    source: ResolvedSource::CratesIo,
                },
                crate_path: tc.path().to_path_buf(),
            };

            let options = BuildOptions {
                profile: Some("dev".to_string()),
                ..Default::default()
            };

            let result = builder.build(&krate, &options);

            assert_matches!(
                result,
                Err(Error::PackageNotFoundInWorkspace { ref name, ref available })
                    if name == "nonexistent-package" && !available.is_empty()
            );
        }
    }

    mod cache_functional {
        use super::*;

        #[test]
        fn identical_builds_hit_cache() {
            let (builder, _temp) = test_builder();
            let tc = CrateTestCase::timestamp();

            let krate1 = fake_downloaded_crate(
                &tc,
                FakeSourceType::Registry {
                    version: "1.0.0".to_string(),
                },
                None,
            );
            let options = BuildOptions {
                profile: Some("dev".to_string()),
                ..Default::default()
            };

            let binary1 = builder.build(&krate1, &options).unwrap();
            let binary1_name = binary1.file_name().unwrap().to_str().unwrap();
            assert_eq!(binary1_name, expected_bin_name("timestamp"));
            let output1 = run_timestamp_binary(&binary1);

            std::thread::sleep(std::time::Duration::from_millis(100));

            let krate2 = fake_downloaded_crate(
                &tc,
                FakeSourceType::Registry {
                    version: "1.0.0".to_string(),
                },
                None,
            );

            let binary2 = builder.build(&krate2, &options).unwrap();
            let binary2_name = binary2.file_name().unwrap().to_str().unwrap();
            assert_eq!(binary2_name, expected_bin_name("timestamp"));
            let output2 = run_timestamp_binary(&binary2);

            assert_cache_hit_by_timestamp(&output1, &output2);
            assert_cache_hit(&binary1, &binary2);
        }

        #[test]
        fn different_profile_cache_miss() {
            let (builder, _temp) = test_builder();
            let tc = CrateTestCase::timestamp();

            let krate1 = fake_downloaded_crate(
                &tc,
                FakeSourceType::Registry {
                    version: "1.0.0".to_string(),
                },
                None,
            );
            let options1 = BuildOptions {
                profile: Some("dev".to_string()),
                ..Default::default()
            };
            let binary1 = builder.build(&krate1, &options1).unwrap();
            let binary1_name = binary1.file_name().unwrap().to_str().unwrap();
            assert_eq!(binary1_name, expected_bin_name("timestamp"));
            let output1 = run_timestamp_binary(&binary1);

            let krate2 = fake_downloaded_crate(
                &tc,
                FakeSourceType::Registry {
                    version: "1.0.0".to_string(),
                },
                None,
            );
            let options2 = BuildOptions {
                profile: Some("release".to_string()),
                ..Default::default()
            };
            let binary2 = builder.build(&krate2, &options2).unwrap();
            let binary2_name = binary2.file_name().unwrap().to_str().unwrap();
            assert_eq!(binary2_name, expected_bin_name("timestamp"));
            let output2 = run_timestamp_binary(&binary2);

            assert_cache_miss_by_timestamp(&output1, &output2);
            assert_cache_miss(&binary1, &binary2);
        }

        #[test]
        fn different_target_cache_miss() {
            let (builder, _temp) = test_builder();
            let tc = CrateTestCase::simple_bin_no_deps();

            let krate1 = fake_downloaded_crate(
                &tc,
                FakeSourceType::Registry {
                    version: "1.0.0".to_string(),
                },
                None,
            );
            let options1 = BuildOptions {
                profile: Some("dev".to_string()),
                target: None,
                ..Default::default()
            };
            let binary1 = builder.build(&krate1, &options1).unwrap();
            let binary1_name = binary1.file_name().unwrap().to_str().unwrap();
            assert_eq!(binary1_name, expected_bin_name("simple-bin-no-deps"));

            let krate2 = fake_downloaded_crate(
                &tc,
                FakeSourceType::Registry {
                    version: "1.0.0".to_string(),
                },
                None,
            );
            let options2 = BuildOptions {
                profile: Some("dev".to_string()),
                target: Some(build_context::TARGET.to_string()),
                ..Default::default()
            };
            let binary2 = builder.build(&krate2, &options2).unwrap();
            let binary2_name = binary2.file_name().unwrap().to_str().unwrap();
            assert_eq!(binary2_name, expected_bin_name("simple-bin-no-deps"));

            assert_cache_miss(&binary1, &binary2);
        }
    }

    mod dependency_resolution {
        use super::*;
        use crate::sbom::tests::get_sbom_component_version;

        #[test]
        fn locked_vs_unlocked_produces_different_cache_entries() {
            let (builder, _temp) = test_builder();
            let tc = CrateTestCase::stale_serde();

            let krate1 = fake_downloaded_crate(
                &tc,
                FakeSourceType::Registry {
                    version: "1.0.0".to_string(),
                },
                None,
            );
            let options1 = BuildOptions {
                profile: Some("dev".to_string()),
                locked: true,
                ..Default::default()
            };
            let binary1 = builder.build(&krate1, &options1).unwrap();
            let binary1_name = binary1.file_name().unwrap().to_str().unwrap();
            assert_eq!(binary1_name, expected_bin_name("stale-serde"));
            let sbom1 = read_sbom_for_binary(&binary1);

            assert_eq!(
                get_sbom_component_version(&sbom1, "serde"),
                Some("1.0.5".to_string()),
                "With --locked, should use old serde from Cargo.lock"
            );

            let krate2 = fake_downloaded_crate(
                &tc,
                FakeSourceType::Registry {
                    version: "1.0.0".to_string(),
                },
                None,
            );
            let options2 = BuildOptions {
                profile: Some("dev".to_string()),
                locked: false,
                ..Default::default()
            };
            let binary2 = builder.build(&krate2, &options2).unwrap();
            let binary2_name = binary2.file_name().unwrap().to_str().unwrap();
            assert_eq!(binary2_name, expected_bin_name("stale-serde"));
            let sbom2 = read_sbom_for_binary(&binary2);

            let version = get_sbom_component_version(&sbom2, "serde").unwrap();
            assert_ne!(
                version, "1.0.5",
                "Without --locked, should resolve to newer serde"
            );
            assert!(version.starts_with("1.0."), "Should still be serde 1.0.x");

            crate::sbom::tests::assert_sboms_ne(&sbom1, &sbom2);
            assert_cache_miss(&binary1, &binary2);
        }

        #[test]
        fn same_locked_flag_produces_cache_hit() {
            let (builder, _temp) = test_builder();
            let tc = CrateTestCase::stale_serde();

            let krate1 = fake_downloaded_crate(
                &tc,
                FakeSourceType::Registry {
                    version: "1.0.0".to_string(),
                },
                None,
            );
            let options = BuildOptions {
                profile: Some("dev".to_string()),
                locked: true,
                ..Default::default()
            };

            let binary1 = builder.build(&krate1, &options).unwrap();
            let binary1_name = binary1.file_name().unwrap().to_str().unwrap();
            assert_eq!(binary1_name, expected_bin_name("stale-serde"));

            let krate2 = fake_downloaded_crate(
                &tc,
                FakeSourceType::Registry {
                    version: "1.0.0".to_string(),
                },
                None,
            );

            let binary2 = builder.build(&krate2, &options).unwrap();
            let binary2_name = binary2.file_name().unwrap().to_str().unwrap();
            assert_eq!(binary2_name, expected_bin_name("stale-serde"));

            assert_cache_hit(&binary1, &binary2);
        }

        #[test]
        fn different_features_different_dependencies() {
            let (builder, _temp) = test_builder();
            let tc = CrateTestCase::timestamp();

            let krate1 = fake_downloaded_crate(
                &tc,
                FakeSourceType::Registry {
                    version: "1.0.0".to_string(),
                },
                None,
            );
            let options1 = BuildOptions {
                profile: Some("dev".to_string()),
                ..Default::default()
            };
            let binary1 = builder.build(&krate1, &options1).unwrap();
            let binary1_name = binary1.file_name().unwrap().to_str().unwrap();
            assert_eq!(binary1_name, expected_bin_name("timestamp"));
            let sbom1 = read_sbom_for_binary(&binary1);
            let output1 = run_timestamp_binary(&binary1);

            let krate2 = fake_downloaded_crate(
                &tc,
                FakeSourceType::Registry {
                    version: "1.0.0".to_string(),
                },
                None,
            );
            let options2 = BuildOptions {
                profile: Some("dev".to_string()),
                features: vec!["frobnulator".to_string()],
                no_default_features: true,
                ..Default::default()
            };
            let binary2 = builder.build(&krate2, &options2).unwrap();
            let binary2_name = binary2.file_name().unwrap().to_str().unwrap();
            assert_eq!(binary2_name, expected_bin_name("timestamp"));
            let sbom2 = read_sbom_for_binary(&binary2);
            let output2 = run_timestamp_binary(&binary2);

            assert!(output1.features.contains(&"gonkolator".to_string()));
            assert!(output2.features.contains(&"frobnulator".to_string()));

            crate::sbom::tests::assert_sboms_ne(&sbom1, &sbom2);
            assert_cache_miss_by_timestamp(&output1, &output2);
        }

        #[test]
        fn all_features_includes_all_dependencies() {
            let (builder, _temp) = test_builder();
            let tc = CrateTestCase::timestamp();

            let krate = fake_downloaded_crate(
                &tc,
                FakeSourceType::Registry {
                    version: "1.0.0".to_string(),
                },
                None,
            );
            let options = BuildOptions {
                profile: Some("dev".to_string()),
                all_features: true,
                ..Default::default()
            };

            let binary = builder.build(&krate, &options).unwrap();
            let binary_name = binary.file_name().unwrap().to_str().unwrap();
            assert_eq!(binary_name, expected_bin_name("timestamp"));
            let output = run_timestamp_binary(&binary);

            assert!(
                output.features.contains(&"gonkolator".to_string()),
                "Should have gonkolator"
            );
            assert!(
                output.features.contains(&"frobnulator".to_string()),
                "Should have frobnulator"
            );
        }

        #[test]
        fn default_is_locked_true() {
            let (builder, _temp) = test_builder();
            let tc = CrateTestCase::stale_serde();

            let krate = fake_downloaded_crate(
                &tc,
                FakeSourceType::Registry {
                    version: "1.0.0".to_string(),
                },
                None,
            );
            let options = BuildOptions::default();

            let binary = builder.build(&krate, &options).unwrap();
            let sbom = read_sbom_for_binary(&binary);

            assert_eq!(
                get_sbom_component_version(&sbom, "serde"),
                Some("1.0.5".to_string()),
                "Default (locked=true) should honor Cargo.lock"
            );
        }

        #[test]
        fn frozen_honors_cargo_lock_and_is_offline() {
            let (builder, _temp) = test_builder();
            let tc = CrateTestCase::stale_serde();

            let krate = fake_downloaded_crate(
                &tc,
                FakeSourceType::Registry {
                    version: "1.0.0".to_string(),
                },
                None,
            );
            let options = BuildOptions {
                profile: Some("dev".to_string()),
                locked: true,
                offline: true,
                ..Default::default()
            };

            let binary = builder.build(&krate, &options).unwrap();
            let sbom = read_sbom_for_binary(&binary);

            assert_eq!(
                get_sbom_component_version(&sbom, "serde"),
                Some("1.0.5".to_string()),
                "Frozen should honor Cargo.lock"
            );

            assert!(options.offline, "Frozen should set offline mode");
        }
    }

    mod source_types {
        use super::*;

        #[test]
        fn local_dir_never_cached() {
            let (builder, _temp) = test_builder();
            let tc = CrateTestCase::simple_bin_no_deps();

            let krate = fake_downloaded_crate(&tc, FakeSourceType::LocalDir, None);

            let options = BuildOptions {
                profile: Some("dev".to_string()),
                ..Default::default()
            };

            let binary = builder.build(&krate, &options).unwrap();

            assert!(!binary.starts_with(&builder.config.bin_dir));
            assert!(binary.starts_with(tc.path()));

            let binary_name = binary.file_name().unwrap().to_str().unwrap();
            assert_eq!(binary_name, expected_bin_name("simple-bin-no-deps"));

            let sbom_path = read_sbom_for_binary(&binary);
            assert!(!sbom_path.exists());
        }

        #[test]
        fn registry_source_cached_with_sbom() {
            let (builder, _temp) = test_builder();
            let tc = CrateTestCase::simple_bin_no_deps();

            let krate1 = fake_downloaded_crate(
                &tc,
                FakeSourceType::Registry {
                    version: "1.0.0".to_string(),
                },
                None,
            );
            let options = BuildOptions {
                profile: Some("dev".to_string()),
                ..Default::default()
            };

            let binary1 = builder.build(&krate1, &options).unwrap();

            assert!(binary1.starts_with(&builder.config.bin_dir));

            let binary1_name = binary1.file_name().unwrap().to_str().unwrap();
            assert_eq!(binary1_name, expected_bin_name("simple-bin-no-deps"));

            let sbom_path = read_sbom_for_binary(&binary1);
            assert!(sbom_path.exists());

            let krate2 = fake_downloaded_crate(
                &tc,
                FakeSourceType::Registry {
                    version: "1.0.0".to_string(),
                },
                None,
            );
            let binary2 = builder.build(&krate2, &options).unwrap();
            let binary2_name = binary2.file_name().unwrap().to_str().unwrap();
            assert_eq!(binary2_name, expected_bin_name("simple-bin-no-deps"));

            assert_cache_hit(&binary1, &binary2);
        }

        #[test]
        fn git_source_cached_with_sbom() {
            let (builder, _temp) = test_builder();
            let tc = CrateTestCase::simple_bin_no_deps();

            let krate1 = fake_downloaded_crate(
                &tc,
                FakeSourceType::Git {
                    url: "https://github.com/example/test.git".to_string(),
                    rev: "abc123".to_string(),
                },
                None,
            );
            let options = BuildOptions {
                profile: Some("dev".to_string()),
                ..Default::default()
            };

            let binary1 = builder.build(&krate1, &options).unwrap();

            assert!(binary1.starts_with(&builder.config.bin_dir));

            let binary1_name = binary1.file_name().unwrap().to_str().unwrap();
            assert_eq!(binary1_name, expected_bin_name("simple-bin-no-deps"));

            let sbom_path = read_sbom_for_binary(&binary1);
            assert!(sbom_path.exists());

            let krate2 = fake_downloaded_crate(
                &tc,
                FakeSourceType::Git {
                    url: "https://github.com/example/test.git".to_string(),
                    rev: "abc123".to_string(),
                },
                None,
            );
            let binary2 = builder.build(&krate2, &options).unwrap();
            let binary2_name = binary2.file_name().unwrap().to_str().unwrap();
            assert_eq!(binary2_name, expected_bin_name("simple-bin-no-deps"));

            assert_cache_hit(&binary1, &binary2);
        }
    }

    mod proc_macro_detection {
        use super::*;

        #[test]
        fn proc_macro_marked_as_build_dep() {
            let (builder, _temp) = test_builder();
            let tc = CrateTestCase::proc_macro_dep();

            let krate = fake_downloaded_crate(
                &tc,
                FakeSourceType::Registry {
                    version: "1.0.0".to_string(),
                },
                None,
            );
            let options = BuildOptions {
                profile: Some("dev".to_string()),
                ..Default::default()
            };

            let binary = builder.build(&krate, &options).unwrap();
            let binary_name = binary.file_name().unwrap().to_str().unwrap();
            assert_eq!(binary_name, expected_bin_name("proc-macro-dep"));

            let sbom_path = read_sbom_for_binary(&binary);

            let json_str = fs::read_to_string(&sbom_path).unwrap();
            let bom: serde_cyclonedx::cyclonedx::v_1_4::CycloneDx = serde_json::from_str(&json_str).unwrap();

            let components = bom.components.unwrap();
            let serde_derive = components
                .iter()
                .find(|c| c.name.as_str() == "serde_derive")
                .expect("serde_derive should be in components");

            if let Some(ref props) = serde_derive.properties {
                let has_build_kind = props.iter().any(|p| {
                    p.name.as_deref() == Some("cdx:rustc:dependency_kind")
                        && p.value.as_deref() == Some("build")
                });
                assert!(has_build_kind, "proc-macro should be marked as build dependency");
            } else {
                panic!("proc-macro should have dependency_kind property");
            }
        }
    }

    mod build_options {
        use super::*;

        mod features_parsing {
            use super::*;

            /// Test that an empty features string produces an empty vec.
            #[test]
            fn empty_features_string() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["--features", "", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert!(options.features.is_empty());
            }

            /// Test parsing a single feature.
            #[test]
            fn single_feature() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["--features", "feat1", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert_eq!(options.features, vec!["feat1"]);
            }

            /// Test parsing comma-separated features.
            #[test]
            fn comma_separated_features() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["--features", "feat1,feat2", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert_eq!(options.features, vec!["feat1", "feat2"]);
            }

            /// Test parsing space-separated features.
            #[test]
            fn space_separated_features() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["--features", "feat1 feat2", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert_eq!(options.features, vec!["feat1", "feat2"]);
            }

            /// Test parsing features with mixed separators (commas and spaces).
            #[test]
            fn mixed_separator_features() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["--features", "feat1, feat2 feat3", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert_eq!(options.features, vec!["feat1", "feat2", "feat3"]);
            }

            /// Test that leading and trailing whitespace is handled correctly.
            #[test]
            fn whitespace_handling() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["--features", " feat1 , feat2 ", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert_eq!(options.features, vec!["feat1", "feat2"]);
            }

            /// Test that when no features flag is provided, features vec is empty.
            #[test]
            fn no_features_flag() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert!(options.features.is_empty());
            }
        }

        mod profile_selection {
            use super::*;

            /// Test that `--debug` flag maps to "dev" profile.
            #[test]
            fn debug_flag_maps_to_dev() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["--debug", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert_eq!(options.profile, Some("dev".to_string()));
            }

            /// Test that `--profile` flag sets the profile explicitly.
            #[test]
            fn explicit_profile() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["--profile", "custom", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert_eq!(options.profile, Some("custom".to_string()));
            }

            /// Test that when neither flag is provided, profile is None.
            #[test]
            fn no_profile_specified() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert_eq!(options.profile, None);
            }
        }

        mod build_target_selection {
            use super::*;

            /// Test that no flags produces [`BuildTarget::DefaultBin`].
            #[test]
            fn default_bin_when_no_flags() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert_eq!(options.build_target, BuildTarget::DefaultBin);
            }

            /// Test that `--bin` flag produces [`BuildTarget::Bin`].
            #[test]
            fn explicit_bin() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["--bin", "foo", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert_eq!(options.build_target, BuildTarget::Bin("foo".to_string()));
            }

            /// Test that `--example` flag produces [`BuildTarget::Example`].
            #[test]
            fn explicit_example() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["--example", "bar", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert_eq!(options.build_target, BuildTarget::Example("bar".to_string()));
            }
        }

        mod locked_offline_precedence {
            use super::*;

            /// Test that with no config and no CLI flags, locked defaults to true and offline to
            /// false.
            #[test]
            fn no_config_no_cli() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert!(options.locked, "Default should be locked=true");
                assert!(!options.offline);
            }

            /// Test that config.locked=true sets locked when no CLI flag is provided.
            #[test]
            fn config_locked_true() {
                let config = Config {
                    locked: true,
                    ..Default::default()
                };
                let args = CliArgs::parse_from_test_args(["tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert!(options.locked);
                assert!(!options.offline);
            }

            /// Test that config.offline=true sets offline when no CLI flag is provided.
            #[test]
            fn config_offline_true() {
                let config = Config {
                    offline: true,
                    ..Default::default()
                };
                let args = CliArgs::parse_from_test_args(["tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert!(options.locked, "Default should be locked=true");
                assert!(options.offline);
            }

            /// Test that config can set both locked and offline.
            #[test]
            fn config_both_true() {
                let config = Config {
                    locked: true,
                    offline: true,
                    ..Default::default()
                };
                let args = CliArgs::parse_from_test_args(["tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert!(options.locked);
                assert!(options.offline);
            }

            /// Test that CLI `--locked` flag overrides config.
            #[test]
            fn cli_locked_overrides_config() {
                let config = Config {
                    locked: false,
                    ..Default::default()
                };
                let args = CliArgs::parse_from_test_args(["--locked", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert!(options.locked);
                assert!(!options.offline);
            }

            /// Test that CLI `--offline` flag overrides config.
            #[test]
            fn cli_offline_overrides_config() {
                let config = Config {
                    offline: false,
                    ..Default::default()
                };
                let args = CliArgs::parse_from_test_args(["--offline", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert!(options.locked, "Default should be locked=true");
                assert!(options.offline);
            }

            /// Test that CLI `--frozen` flag sets both locked and offline.
            #[test]
            fn cli_frozen_sets_both() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["--frozen", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert!(options.locked);
                assert!(options.offline);
            }

            /// Test that `--frozen` overrides config.locked=false.
            #[test]
            fn frozen_overrides_config_locked_false() {
                let config = Config {
                    locked: false,
                    offline: false,
                    ..Default::default()
                };
                let args = CliArgs::parse_from_test_args(["--frozen", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert!(options.locked);
                assert!(options.offline);
            }

            /// Test that `--frozen` overrides config.offline=false.
            #[test]
            fn frozen_overrides_config_offline_false() {
                let config = Config {
                    offline: false,
                    ..Default::default()
                };
                let args = CliArgs::parse_from_test_args(["--frozen", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert!(options.locked);
                assert!(options.offline);
            }

            /// Test that `--frozen` still works when config already has values set.
            #[test]
            fn frozen_with_config_values_set() {
                let config = Config {
                    locked: true,
                    offline: true,
                    ..Default::default()
                };
                let args = CliArgs::parse_from_test_args(["--frozen", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert!(options.locked);
                assert!(options.offline);
            }

            #[test]
            fn unlocked_sets_locked_false() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["--unlocked", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert!(!options.locked, "unlocked should set locked=false");
            }

            #[test]
            fn explicit_locked_is_true() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["--locked", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert!(options.locked);
            }

            #[test]
            fn unlocked_overrides_config_locked() {
                let config = Config {
                    locked: true,
                    ..Default::default()
                };
                let args = CliArgs::parse_from_test_args(["--unlocked", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert!(!options.locked, "unlocked should override config");
            }
        }

        mod toolchain_precedence {
            use super::*;

            /// Test that with no config and no CLI flag, toolchain is None.
            #[test]
            fn no_config_no_cli() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert_eq!(options.toolchain, None);
            }

            /// Test that config.toolchain is used when no CLI flag is provided.
            #[test]
            fn config_toolchain_used() {
                let config = Config {
                    toolchain: Some("stable".to_string()),
                    ..Default::default()
                };
                let args = CliArgs::parse_from_test_args(["tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert_eq!(options.toolchain, Some("stable".to_string()));
            }

            /// Test that CLI `+toolchain` syntax overrides config.
            #[test]
            fn cli_toolchain_overrides_config() {
                let config = Config {
                    toolchain: Some("stable".to_string()),
                    ..Default::default()
                };
                let args = CliArgs::parse_from_test_args(["+nightly", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert_eq!(options.toolchain, Some("nightly".to_string()));
            }
        }

        mod direct_passthrough {
            use super::*;

            /// Test that `--all-features` flag is passed through.
            #[test]
            fn all_features() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["--all-features", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert!(options.all_features);
            }

            /// Test that `--no-default-features` flag is passed through.
            #[test]
            fn no_default_features() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["--no-default-features", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert!(options.no_default_features);
            }

            /// Test that `--target` flag is passed through.
            #[test]
            fn target() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["--target", "x86_64-unknown-linux-gnu", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert_eq!(options.target, Some("x86_64-unknown-linux-gnu".to_string()));
            }

            /// Test that `--jobs` flag is passed through.
            #[test]
            fn jobs() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["--jobs", "4", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert_eq!(options.jobs, Some(4));
            }

            /// Test that `--ignore-rust-version` flag is passed through.
            #[test]
            fn ignore_rust_version() {
                let config = Config::default();
                let args = CliArgs::parse_from_test_args(["--ignore-rust-version", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();

                assert!(options.ignore_rust_version);
            }

            /// Test that `-v` flags are converted to [`CargoVerbosity`].
            #[test]
            fn cargo_verbosity() {
                let config = Config::default();

                let args = CliArgs::parse_from_test_args(["tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();
                assert_eq!(options.cargo_verbosity, CargoVerbosity::Normal);

                let args = CliArgs::parse_from_test_args(["-v", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();
                assert_eq!(options.cargo_verbosity, CargoVerbosity::Verbose);

                let args = CliArgs::parse_from_test_args(["-vv", "tool"]);
                let options = BuildOptions::load(&config, &args).unwrap();
                assert_eq!(options.cargo_verbosity, CargoVerbosity::VeryVerbose);
            }
        }
    }
}