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
use crate::{
Result,
cli::CliArgs,
config::{Config, ToolConfig},
error,
git::GitSelector,
};
use semver::VersionReq;
use serde::{Deserialize, Serialize};
use snafu::{OptionExt, ResultExt};
use std::path::PathBuf;
use url::Url;
/// A specification of a crate that the user wants to execute.
///
/// Note that "crate" here doesn't necessarily mean "crate on Crates.io". We support various ways
/// of referring to a crate to run, which is why this enum type is needed. It abstracts away the
/// various ways the user might specify a crate to run. Ultimately all of these need to be
/// resolved to a path in the local filesystem, controlled by cgx, from which we can build and run.
///
/// ## Versioning
///
/// For crate specs that point to registries (which store multiple versions of a crate), the
/// default is to choose the latest version. If a version is specified, then the most recent
/// version that matches the specification is chosen. If no such version exists then an error
/// ocurrs.
///
/// For crate specs that point to local paths, forges, or git repos, there is no choice of
/// version; the version of the crate is whatever it is at the specified location. In those cases,
/// if the `version` field is present, it is validated against the version found at the location,
/// and if it's not compatible then an error ocurrs.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum CrateSpec {
/// A crate on Crates.io, specified by its name and optional version.
CratesIo {
name: String,
version: Option<VersionReq>,
},
/// A crate on some other registry, specified by its name and optional version.
Registry {
/// The registry source (either a named registry or a direct index URL)
source: RegistrySource,
name: String,
version: Option<VersionReq>,
},
/// A crate in a git repository, specified by the repository URL and optional branch, tag, or
/// commit hash.
///
/// The `name` field is optional. If omitted, it will be discovered from the repository
/// (which must contain exactly one crate). If the repository contains multiple crates,
/// the name must be specified.
///
/// If the `version` field is present, the crate found at the specified repo must have a
/// version that is compatible with the version specification or an error ocurrs.
Git {
repo: String,
selector: GitSelector,
name: Option<String>,
version: Option<VersionReq>,
},
/// A crate in a repo in some software Forge, specified by its repo, optional path within that
/// repo, and optional branch, tag, or commit hash.
///
/// The `name` field is optional. If omitted, it will be discovered from the repository
/// (which must contain exactly one crate). If the repository contains multiple crates,
/// the name must be specified.
Forge {
/// A repository within a software forge
forge: Forge,
/// A branch, tag, or commit hash within the repository
selector: GitSelector,
name: Option<String>,
version: Option<VersionReq>,
},
/// A crate in a local directory, specified by the path to the directory containing the crate's
/// `Cargo.toml` or a workspace `Cargo.toml` to which the crate belongs.
///
/// The `name` field is optional. If omitted, it will be discovered from the path
/// (which must contain exactly one crate). If the path contains multiple crates
/// (i.e., a workspace), the name must be specified.
LocalDir {
path: PathBuf,
name: Option<String>,
version: Option<VersionReq>,
},
}
impl CrateSpec {
/// Load a crate spec from the command line, respecting config-based overrides.
///
/// This method applies config-based transformations and overrides:
/// 1. Alias resolution: Maps short names to full crate names (e.g., `rg` → `ripgrep`)
/// 2. Tool pinning: Applies version pinning from config for known tools
/// 3. Default registry: Uses config's default registry when no registry specified
///
/// Priority order for version selection:
/// 1. CLI `--version` flag (highest)
/// 2. `@version` suffix in crate name
/// 3. Config tool pinning
/// 4. Latest version (lowest)
pub fn load(config: &Config, args: &CliArgs) -> Result<Self> {
// Parse the base crate spec from CLI args, including special cargo handling
let (name, at_version) = if let Some(crate_spec) = &args.crate_spec {
if crate_spec == "cargo" && !args.args.is_empty() {
// Special case: `cgx cargo deny` -> crate name is `cargo-deny`
let subcommand = &args.args[0];
let (subcommand_name, subcommand_version) = Self::parse_crate_name_and_version(subcommand)?;
let cargo_crate_name = format!("cargo-{}", subcommand_name);
(Some(cargo_crate_name), subcommand_version)
} else {
let (n, v) = Self::parse_crate_name_and_version(crate_spec)?;
(Some(n), v)
}
} else {
(None, None)
};
// Apply alias resolution from config
let name = name.map(|n| config.aliases.get(&n).cloned().unwrap_or(n));
// Reconcile version from @version syntax and --version flag
let flag_version = args
.version
.as_ref()
.filter(|v| !v.is_empty())
.map(|s| s.as_str());
let cli_version = match (at_version.as_deref(), flag_version) {
(Some(at_ver), Some(flag_ver)) => {
if at_ver != flag_ver {
return error::ConflictingVersionsSnafu {
at_version: at_ver,
flag_version: flag_ver,
}
.fail();
}
Some(
VersionReq::parse(at_ver)
.with_context(|_| error::InvalidVersionReqSnafu { version: at_ver })?,
)
}
(Some(at_ver), None) => Some(
VersionReq::parse(at_ver)
.with_context(|_| error::InvalidVersionReqSnafu { version: at_ver })?,
),
(None, Some(flag_ver)) => Some(
VersionReq::parse(flag_ver)
.with_context(|_| error::InvalidVersionReqSnafu { version: flag_ver })?,
),
(None, None) => None,
};
// Apply tool pinning from config if no CLI version specified
let version = if cli_version.is_none() {
if let Some(ref tool_name) = name {
config
.tools
.get(tool_name)
.and_then(|tool_config| match tool_config {
ToolConfig::Version(v) | ToolConfig::Detailed { version: Some(v), .. } => {
VersionReq::parse(v).ok()
}
ToolConfig::Detailed { version: None, .. } => None,
})
} else {
None
}
} else {
cli_version
};
// Construct GitSelector from CLI flags
let git_selector = match (&args.branch, &args.tag, &args.rev) {
(Some(branch), None, None) => GitSelector::Branch(branch.clone()),
(None, Some(tag), None) => GitSelector::Tag(tag.clone()),
(None, None, Some(rev)) => GitSelector::Commit(rev.clone()),
(None, None, None) => GitSelector::DefaultBranch,
_ => unreachable!("BUG: clap should enforce mutual exclusivity"),
};
let is_git_source = args.git.is_some() || args.github.is_some() || args.gitlab.is_some();
if !matches!(git_selector, GitSelector::DefaultBranch) && !is_git_source {
return error::GitSelectorWithoutGitSourceSnafu.fail();
}
// Construct the appropriate CrateSpec variant based on source flags
if let Some(git_url) = &args.git {
if let Some(forge) = Forge::try_parse_from_url(git_url) {
Ok(CrateSpec::Forge {
forge,
selector: git_selector.clone(),
name,
version,
})
} else {
Ok(CrateSpec::Git {
repo: git_url.clone(),
selector: git_selector.clone(),
name,
version,
})
}
} else if let Some(registry) = &args.registry {
let name = name.context(error::MissingCrateParameterSnafu)?;
Ok(CrateSpec::Registry {
source: RegistrySource::Named(registry.clone()),
name,
version,
})
} else if let Some(index_str) = &args.index {
let name = name.context(error::MissingCrateParameterSnafu)?;
let index_url =
Url::parse(index_str).with_context(|_| error::InvalidUrlSnafu { url: index_str })?;
Ok(CrateSpec::Registry {
source: RegistrySource::IndexUrl(index_url),
name,
version,
})
} else if let Some(path) = &args.path {
Ok(CrateSpec::LocalDir {
path: path.clone(),
name,
version,
})
} else if let Some(github_repo) = &args.github {
let (owner, repo) = Self::parse_owner_repo(github_repo)?;
let custom_url = if let Some(url_str) = &args.github_url {
Some(Url::parse(url_str).with_context(|_| error::InvalidUrlSnafu { url: url_str })?)
} else {
None
};
Ok(CrateSpec::Forge {
forge: Forge::GitHub {
custom_url,
owner,
repo,
},
selector: git_selector.clone(),
name,
version,
})
} else if let Some(gitlab_repo) = &args.gitlab {
let (owner, repo) = Self::parse_owner_repo(gitlab_repo)?;
let custom_url = if let Some(url_str) = &args.gitlab_url {
Some(Url::parse(url_str).with_context(|_| error::InvalidUrlSnafu { url: url_str })?)
} else {
None
};
Ok(CrateSpec::Forge {
forge: Forge::GitLab {
custom_url,
owner,
repo,
},
selector: git_selector.clone(),
name,
version,
})
} else {
// No CLI source flags - check tool config, then default_registry, then crates.io
// First check if tool config specifies a source
if let Some(ref tool_name) = name {
if let Some(tool_config) = config.tools.get(tool_name) {
match tool_config {
ToolConfig::Detailed {
git: Some(git_url),
branch,
tag,
rev,
..
} => {
// Tool config specifies git source
let selector = match (branch.as_ref(), tag.as_ref(), rev.as_ref()) {
(Some(b), None, None) => GitSelector::Branch(b.clone()),
(None, Some(t), None) => GitSelector::Tag(t.clone()),
(None, None, Some(r)) => GitSelector::Commit(r.clone()),
_ => GitSelector::DefaultBranch,
};
if let Some(forge) = Forge::try_parse_from_url(git_url) {
return Ok(CrateSpec::Forge {
forge,
selector,
name,
version,
});
} else {
return Ok(CrateSpec::Git {
repo: git_url.clone(),
selector,
name,
version,
});
}
}
ToolConfig::Detailed {
registry: Some(reg), ..
} => {
// Tool config specifies registry
let name = name.context(error::MissingCrateParameterSnafu)?;
return Ok(CrateSpec::Registry {
source: RegistrySource::Named(reg.clone()),
name,
version,
});
}
ToolConfig::Detailed { path: Some(p), .. } => {
// Tool config specifies local path
return Ok(CrateSpec::LocalDir {
path: p.clone(),
name,
version,
});
}
_ => {
// Tool config doesn't specify source - fall through to defaults
}
}
}
}
// No tool config source - use default_registry or crates.io
// At this point all of the possible configurations in which an explicit crate name is
// optional have been eliminated, so we require a crate name.
let name = name.context(error::MissingCrateParameterSnafu)?;
if let Some(ref default_registry) = config.default_registry {
// Use config's default registry
Ok(CrateSpec::Registry {
source: RegistrySource::Named(default_registry.clone()),
name,
version,
})
} else {
// Use crates.io
Ok(CrateSpec::CratesIo { name, version })
}
}
}
/// Parse a crate name that may include an @version suffix.
///
/// Examples:
/// - `"ripgrep"` → `("ripgrep", None)`
/// - `"ripgrep@14"` → `("ripgrep", Some("14"))`
fn parse_crate_name_and_version(spec: &str) -> Result<(String, Option<String>)> {
if let Some((name, version)) = spec.split_once('@') {
Ok((name.to_string(), Some(version.to_string())))
} else {
Ok((spec.to_string(), None))
}
}
/// Parse owner/repo format used by GitHub and GitLab.
fn parse_owner_repo(repo_str: &str) -> Result<(String, String)> {
if let Some((owner, repo)) = repo_str.split_once('/') {
if owner.is_empty() || repo.is_empty() {
return error::InvalidRepoFormatSnafu { repo: repo_str }.fail();
}
Ok((owner.to_string(), repo.to_string()))
} else {
error::InvalidRepoFormatSnafu { repo: repo_str }.fail()
}
}
/// Get the arguments that should be passed to the executed binary.
///
/// For the special case of `cgx cargo <subcommand>`, the first argument is consumed
/// as part of the crate spec (to form `cargo-<subcommand>`), so we skip it.
/// Otherwise, all trailing args are passed to the binary.
pub fn get_binary_args(args: &CliArgs) -> Vec<std::ffi::OsString> {
let skip = if args.crate_spec.as_deref() == Some("cargo") && !args.args.is_empty() {
// Skip the first arg (the cargo subcommand name)
1
} else {
0
};
args.args
.iter()
.skip(skip)
.map(std::ffi::OsString::from)
.collect()
}
}
/// Specifies how to identify a registry source.
///
/// Registries can be specified either by a named configuration in `.cargo/config.toml` or by
/// directly providing the index URL.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum RegistrySource {
/// A named registry configured in `.cargo/config.toml` (corresponds to `--registry`).
Named(String),
/// A direct registry index URL (corresponds to `--index`).
IndexUrl(Url),
}
/// Supported software forges where crates can be hosted
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Forge {
GitHub {
/// Custom URL for Github Enterprise instances; None for github.com
custom_url: Option<Url>,
owner: String,
repo: String,
},
GitLab {
/// Custom URL for self-hosted GitLab instances; None for gitlab.com
custom_url: Option<Url>,
owner: String,
repo: String,
},
}
impl Forge {
/// Convert this forge reference into a git URL
pub fn git_url(&self) -> String {
match self {
Forge::GitHub {
custom_url,
owner,
repo,
} => {
let base = custom_url
.as_ref()
.map_or("https://github.com", |u| u.as_str().trim_end_matches('/'));
format!("{}/{}/{}.git", base, owner, repo)
}
Forge::GitLab {
custom_url,
owner,
repo,
} => {
let base = custom_url
.as_ref()
.map_or("https://gitlab.com", |u| u.as_str().trim_end_matches('/'));
format!("{}/{}/{}.git", base, owner, repo)
}
}
}
/// Attempt to parse a URL into a reference to a repo in a forge
///
/// When a known forge like Github or Gitlab is used, treating it as a forge as opposed to a
/// generic Git URL is important because we can use that forge's API to look for binary
/// releases for the crate, which if found will dramatically speed up installation.
///
/// Only HTTPS urls are recognized, and only URLs that point to the root of a repository, on
/// the forges that we have API support for.
pub fn try_parse_from_url(git_url: &str) -> Option<Self> {
let url = Url::parse(git_url).ok()?;
if url.scheme() != "https" {
return None;
}
let host = url.host_str()?;
let path = url.path();
let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
if segments.len() != 2 {
return None;
}
let owner = segments[0].to_string();
let mut repo = segments[1].to_string();
if repo.ends_with(".git") {
repo = repo[..repo.len() - 4].to_string();
}
match host {
"github.com" => Some(Forge::GitHub {
custom_url: None,
owner,
repo,
}),
"gitlab.com" => Some(Forge::GitLab {
custom_url: None,
owner,
repo,
}),
_other => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
cli::CliArgs,
config::{Config, ToolConfig},
};
use assert_matches::assert_matches;
/// Test that config aliases are resolved before processing the crate spec.
///
/// Simulated config:
/// ```toml
/// [aliases]
/// rg = "ripgrep"
/// ```
///
/// Command: `cgx rg`
///
/// Expected: Alias `rg` resolves to `ripgrep`, producing a crates.io spec for ripgrep.
#[test]
fn test_alias_resolution() {
let mut config = Config::default();
config.aliases.insert("rg".to_string(), "ripgrep".to_string());
let args = CliArgs::parse_from_test_args(["rg"]);
let spec = CrateSpec::load(&config, &args).unwrap();
assert_matches!(
spec,
CrateSpec::CratesIo { ref name, .. } if name == "ripgrep"
);
}
/// Test that tools can be pinned to specific versions using simple string syntax.
///
/// Simulated config:
/// ```toml
/// [tools]
/// ripgrep = "14.0"
/// ```
///
/// Command: `cgx ripgrep`
///
/// Expected: Uses pinned version 14.0 from config.
#[test]
fn test_tool_version_pinning_simple() {
let mut config = Config::default();
config
.tools
.insert("ripgrep".to_string(), ToolConfig::Version("14.0".to_string()));
let args = CliArgs::parse_from_test_args(["ripgrep"]);
let spec = CrateSpec::load(&config, &args).unwrap();
assert_matches!(
spec,
CrateSpec::CratesIo { ref name, version: Some(ref v) }
if name == "ripgrep" && v == &VersionReq::parse("14.0").unwrap()
);
}
/// Test that tools can be pinned to specific versions using detailed table syntax.
///
/// Simulated config:
/// ```toml
/// [tools]
/// ripgrep = { version = "14.0" }
/// ```
///
/// Command: `cgx ripgrep`
///
/// Expected: Uses pinned version 14.0 from detailed config.
#[test]
fn test_tool_version_pinning_detailed() {
let mut config = Config::default();
config.tools.insert(
"ripgrep".to_string(),
ToolConfig::Detailed {
version: Some("14.0".to_string()),
features: None,
registry: None,
git: None,
branch: None,
tag: None,
rev: None,
path: None,
},
);
let args = CliArgs::parse_from_test_args(["ripgrep"]);
let spec = CrateSpec::load(&config, &args).unwrap();
assert_matches!(
spec,
CrateSpec::CratesIo { ref name, version: Some(ref v) }
if name == "ripgrep" && v == &VersionReq::parse("14.0").unwrap()
);
}
/// Test that tools can specify a custom registry in config.
///
/// Simulated config:
/// ```toml
/// [tools]
/// my-tool = { version = "1.0", registry = "my-registry" }
/// ```
///
/// Command: `cgx my-tool`
///
/// Expected: Produces [`CrateSpec::Registry`] with the specified registry name.
/// This should behave as if the user had run `cgx my-tool --registry my-registry --version
/// 1.0`.
#[test]
fn test_tool_with_registry() {
let mut config = Config::default();
config.tools.insert(
"my-tool".to_string(),
ToolConfig::Detailed {
version: Some("1.0".to_string()),
registry: Some("my-registry".to_string()),
features: None,
git: None,
branch: None,
tag: None,
rev: None,
path: None,
},
);
let args = CliArgs::parse_from_test_args(["my-tool"]);
let spec = CrateSpec::load(&config, &args).unwrap();
assert_matches!(
spec,
CrateSpec::Registry {
source: RegistrySource::Named(ref reg),
ref name,
version: Some(ref v)
} if reg == "my-registry" && name == "my-tool" && v == &VersionReq::parse("1.0").unwrap()
);
}
/// Test that tools can specify a git URL in config.
///
/// Simulated config:
/// ```toml
/// [tools]
/// my-tool = { git = "https://example.com/repo.git" }
/// ```
///
/// Command: `cgx my-tool`
///
/// Expected: Produces [`CrateSpec::Git`] with the specified repo URL.
/// This should behave as if the user had run `cgx my-tool --git https://example.com/repo.git`.
#[test]
fn test_tool_with_git_url() {
let mut config = Config::default();
config.tools.insert(
"my-tool".to_string(),
ToolConfig::Detailed {
version: None,
git: Some("https://example.com/repo.git".to_string()),
branch: None,
registry: None,
features: None,
tag: None,
rev: None,
path: None,
},
);
let args = CliArgs::parse_from_test_args(["my-tool"]);
let spec = CrateSpec::load(&config, &args).unwrap();
assert_matches!(
spec,
CrateSpec::Git {
ref repo,
selector: GitSelector::DefaultBranch,
name: Some(ref n),
version: None
} if repo == "https://example.com/repo.git" && n == "my-tool"
);
}
/// Test that GitHub URLs in config are recognized and produce [`CrateSpec::Forge`] variants.
///
/// Simulated config:
/// ```toml
/// [tools]
/// my-tool = { git = "https://github.com/owner/repo.git" }
/// ```
///
/// Command: `cgx my-tool`
///
/// Expected: Produces [`CrateSpec::Forge`] with GitHub forge, enabling potential use of
/// GitHub Releases API for binary downloads.
#[test]
fn test_tool_with_github_url() {
let mut config = Config::default();
config.tools.insert(
"my-tool".to_string(),
ToolConfig::Detailed {
version: None,
git: Some("https://github.com/owner/repo.git".to_string()),
tag: None,
registry: None,
features: None,
branch: None,
rev: None,
path: None,
},
);
let args = CliArgs::parse_from_test_args(["my-tool"]);
let spec = CrateSpec::load(&config, &args).unwrap();
assert_matches!(
spec,
CrateSpec::Forge {
forge: Forge::GitHub { custom_url: None, ref owner, ref repo },
selector: GitSelector::DefaultBranch,
name: Some(ref n),
version: None
} if owner == "owner" && repo == "repo" && n == "my-tool"
);
}
/// Test that GitLab URLs in config are recognized and produce [`CrateSpec::Forge`] variants.
///
/// Simulated config:
/// ```toml
/// [tools]
/// my-tool = { git = "https://gitlab.com/owner/repo.git" }
/// ```
///
/// Command: `cgx my-tool`
///
/// Expected: Produces [`CrateSpec::Forge`] with GitLab forge, enabling potential use of
/// GitLab Releases API for binary downloads.
#[test]
fn test_tool_with_gitlab_url() {
let mut config = Config::default();
config.tools.insert(
"my-tool".to_string(),
ToolConfig::Detailed {
version: None,
git: Some("https://gitlab.com/owner/repo.git".to_string()),
tag: None,
registry: None,
features: None,
branch: None,
rev: None,
path: None,
},
);
let args = CliArgs::parse_from_test_args(["my-tool"]);
let spec = CrateSpec::load(&config, &args).unwrap();
assert_matches!(
spec,
CrateSpec::Forge {
forge: Forge::GitLab { custom_url: None, ref owner, ref repo },
selector: GitSelector::DefaultBranch,
name: Some(ref n),
version: None
} if owner == "owner" && repo == "repo" && n == "my-tool"
);
}
/// Test that tools can specify a local filesystem path in config.
///
/// Simulated config:
/// ```toml
/// [tools]
/// my-tool = { path = "/some/path" }
/// ```
///
/// Command: `cgx my-tool`
///
/// Expected: Produces [`CrateSpec::LocalDir`] with the specified path.
/// This should behave as if the user had run `cgx my-tool --path /some/path`.
#[test]
fn test_tool_with_path() {
let mut config = Config::default();
config.tools.insert(
"my-tool".to_string(),
ToolConfig::Detailed {
version: None,
path: Some(PathBuf::from("/some/path")),
registry: None,
features: None,
git: None,
branch: None,
tag: None,
rev: None,
},
);
let args = CliArgs::parse_from_test_args(["my-tool"]);
let spec = CrateSpec::load(&config, &args).unwrap();
assert_matches!(
spec,
CrateSpec::LocalDir {
ref path,
name: Some(ref n),
version: None
} if path == &PathBuf::from("/some/path") && n == "my-tool"
);
}
/// Test that tools can specify git + branch selector in config.
///
/// Simulated config:
/// ```toml
/// [tools]
/// my-tool = { git = "https://example.com/repo.git", branch = "develop" }
/// ```
///
/// Command: `cgx my-tool`
///
/// Expected: Produces [`CrateSpec::Git`] with [`GitSelector::Branch`].
/// Equivalent to: `cgx my-tool --git https://example.com/repo.git --branch develop`.
#[test]
fn test_tool_with_git_and_branch() {
let mut config = Config::default();
config.tools.insert(
"my-tool".to_string(),
ToolConfig::Detailed {
version: None,
git: Some("https://example.com/repo.git".to_string()),
branch: Some("develop".to_string()),
registry: None,
features: None,
tag: None,
rev: None,
path: None,
},
);
let args = CliArgs::parse_from_test_args(["my-tool"]);
let spec = CrateSpec::load(&config, &args).unwrap();
assert_matches!(
spec,
CrateSpec::Git {
ref repo,
selector: GitSelector::Branch(ref b),
name: Some(ref n),
version: None
} if repo == "https://example.com/repo.git" && b == "develop" && n == "my-tool"
);
}
/// Test that tools can specify git + tag selector in config.
///
/// Simulated config:
/// ```toml
/// [tools]
/// my-tool = { git = "https://example.com/repo.git", tag = "v1.0.0" }
/// ```
///
/// Command: `cgx my-tool`
///
/// Expected: Produces [`CrateSpec::Git`] with [`GitSelector::Tag`].
/// Equivalent to: `cgx my-tool --git https://example.com/repo.git --tag v1.0.0`.
#[test]
fn test_tool_with_git_and_tag() {
let mut config = Config::default();
config.tools.insert(
"my-tool".to_string(),
ToolConfig::Detailed {
version: None,
git: Some("https://example.com/repo.git".to_string()),
tag: Some("v1.0.0".to_string()),
registry: None,
features: None,
branch: None,
rev: None,
path: None,
},
);
let args = CliArgs::parse_from_test_args(["my-tool"]);
let spec = CrateSpec::load(&config, &args).unwrap();
assert_matches!(
spec,
CrateSpec::Git {
ref repo,
selector: GitSelector::Tag(ref t),
name: Some(ref n),
version: None
} if repo == "https://example.com/repo.git" && t == "v1.0.0" && n == "my-tool"
);
}
/// Test that tools can specify git + rev (commit) selector in config.
///
/// Simulated config:
/// ```toml
/// [tools]
/// my-tool = { git = "https://example.com/repo.git", rev = "abc123" }
/// ```
///
/// Command: `cgx my-tool`
///
/// Expected: Produces [`CrateSpec::Git`] with [`GitSelector::Commit`].
/// Equivalent to: `cgx my-tool --git https://example.com/repo.git --rev abc123`.
#[test]
fn test_tool_with_git_and_rev() {
let mut config = Config::default();
config.tools.insert(
"my-tool".to_string(),
ToolConfig::Detailed {
version: None,
git: Some("https://example.com/repo.git".to_string()),
rev: Some("abc123".to_string()),
registry: None,
features: None,
branch: None,
tag: None,
path: None,
},
);
let args = CliArgs::parse_from_test_args(["my-tool"]);
let spec = CrateSpec::load(&config, &args).unwrap();
assert_matches!(
spec,
CrateSpec::Git {
ref repo,
selector: GitSelector::Commit(ref c),
name: Some(ref n),
version: None
} if repo == "https://example.com/repo.git" && c == "abc123" && n == "my-tool"
);
}
/// Test that CLI `--version` flag takes precedence over config tool version.
///
/// Simulated config:
/// ```toml
/// [tools]
/// ripgrep = "14.0"
/// ```
///
/// Command: `cgx ripgrep --version 13.0`
///
/// Expected: Uses version 13.0 from CLI, not 14.0 from config.
#[test]
fn test_cli_version_flag_overrides_config() {
let mut config = Config::default();
config
.tools
.insert("ripgrep".to_string(), ToolConfig::Version("14.0".to_string()));
let args = CliArgs::parse_from_test_args(["--version", "13.0", "ripgrep"]);
let spec = CrateSpec::load(&config, &args).unwrap();
assert_matches!(
spec,
CrateSpec::CratesIo { ref name, version: Some(ref v) }
if name == "ripgrep" && v == &VersionReq::parse("13.0").unwrap()
);
}
/// Test that CLI `@version` syntax takes precedence over config tool version.
///
/// Simulated config:
/// ```toml
/// [tools]
/// ripgrep = "14.0"
/// ```
///
/// Command: `cgx ripgrep@13.0`
///
/// Expected: Uses version 13.0 from CLI, not 14.0 from config.
#[test]
fn test_cli_at_version_overrides_config() {
let mut config = Config::default();
config
.tools
.insert("ripgrep".to_string(), ToolConfig::Version("14.0".to_string()));
let args = CliArgs::parse_from_test_args(["ripgrep@13.0"]);
let spec = CrateSpec::load(&config, &args).unwrap();
assert_matches!(
spec,
CrateSpec::CratesIo { ref name, version: Some(ref v) }
if name == "ripgrep" && v == &VersionReq::parse("13.0").unwrap()
);
}
/// Test that CLI `--registry` flag takes precedence over config git source.
///
/// Simulated config:
/// ```toml
/// [tools]
/// my-tool = { version = "1.0", git = "https://github.com/owner/repo.git" }
/// ```
///
/// Command: `cgx my-tool --registry other-registry`
///
/// Expected: Uses registry from CLI, ignoring git source from config.
/// Version 1.0 from config is preserved.
#[test]
fn test_cli_registry_overrides_config_git() {
let mut config = Config::default();
config.tools.insert(
"my-tool".to_string(),
ToolConfig::Detailed {
version: Some("1.0".to_string()),
git: Some("https://github.com/owner/repo.git".to_string()),
registry: None,
features: None,
branch: None,
tag: None,
rev: None,
path: None,
},
);
let args = CliArgs::parse_from_test_args(["--registry", "other-registry", "my-tool"]);
let spec = CrateSpec::load(&config, &args).unwrap();
assert_matches!(
spec,
CrateSpec::Registry {
source: RegistrySource::Named(ref reg),
ref name,
version: Some(ref v)
} if reg == "other-registry"
&& name == "my-tool"
&& v == &VersionReq::parse("1.0").unwrap()
);
}
/// Test that CLI `--git` flag takes precedence over config registry source.
///
/// Simulated config:
/// ```toml
/// [tools]
/// my-tool = { version = "1.0", registry = "my-registry" }
/// ```
///
/// Command: `cgx my-tool --git https://example.com/repo.git`
///
/// Expected: Uses git from CLI, ignoring registry from config.
/// Version 1.0 from config is preserved.
#[test]
fn test_cli_git_overrides_config_registry() {
let mut config = Config::default();
config.tools.insert(
"my-tool".to_string(),
ToolConfig::Detailed {
version: Some("1.0".to_string()),
registry: Some("my-registry".to_string()),
git: None,
features: None,
branch: None,
tag: None,
rev: None,
path: None,
},
);
let args = CliArgs::parse_from_test_args(["--git", "https://example.com/repo.git", "my-tool"]);
let spec = CrateSpec::load(&config, &args).unwrap();
assert_matches!(
spec,
CrateSpec::Git {
ref repo,
selector: GitSelector::DefaultBranch,
name: Some(ref n),
version: Some(ref v)
} if repo == "https://example.com/repo.git"
&& n == "my-tool"
&& v == &VersionReq::parse("1.0").unwrap()
);
}
/// Test that alias resolution happens first, then tool config is applied.
///
/// Simulated config:
/// ```toml
/// [aliases]
/// rg = "ripgrep"
///
/// [tools]
/// ripgrep = "14.0"
/// ```
///
/// Command: `cgx rg`
///
/// Expected: Alias `rg` resolves to `ripgrep`, then tool config for `ripgrep` applies,
/// resulting in version 14.0 from crates.io.
#[test]
fn test_alias_with_tool_config() {
let mut config = Config::default();
config.aliases.insert("rg".to_string(), "ripgrep".to_string());
config
.tools
.insert("ripgrep".to_string(), ToolConfig::Version("14.0".to_string()));
let args = CliArgs::parse_from_test_args(["rg"]);
let spec = CrateSpec::load(&config, &args).unwrap();
assert_matches!(
spec,
CrateSpec::CratesIo { ref name, version: Some(ref v) }
if name == "ripgrep" && v == &VersionReq::parse("14.0").unwrap()
);
}
/// Test that a tool with only version uses the [`Config::default_registry`] if one is
/// configured.
///
/// Simulated config:
/// ```toml
/// default_registry = "my-default-registry"
///
/// [tools]
/// my-tool = "1.0"
/// ```
///
/// Command: `cgx my-tool`
///
/// Expected: Since no explicit source is specified in the tool config, uses the
/// [`Config::default_registry`] instead of crates.io.
#[test]
fn test_default_registry_with_simple_tool() {
let config = Config {
default_registry: Some("my-default-registry".to_string()),
tools: [("my-tool".to_string(), ToolConfig::Version("1.0".to_string()))]
.into_iter()
.collect(),
..Default::default()
};
let args = CliArgs::parse_from_test_args(["my-tool"]);
let spec = CrateSpec::load(&config, &args).unwrap();
assert_matches!(
spec,
CrateSpec::Registry {
source: RegistrySource::Named(ref reg),
ref name,
version: Some(ref v)
} if reg == "my-default-registry"
&& name == "my-tool"
&& v == &VersionReq::parse("1.0").unwrap()
);
}
/// Test that tool-specific registry takes precedence over [`Config::default_registry`].
///
/// Simulated config:
/// ```toml
/// default_registry = "default-registry"
///
/// [tools]
/// my-tool = { version = "1.0", registry = "tool-registry" }
/// ```
///
/// Command: `cgx my-tool`
///
/// Expected: Uses `tool-registry` from tool config, not `default-registry`.
#[test]
fn test_tool_registry_overrides_default_registry() {
let config = Config {
default_registry: Some("default-registry".to_string()),
tools: [(
"my-tool".to_string(),
ToolConfig::Detailed {
version: Some("1.0".to_string()),
registry: Some("tool-registry".to_string()),
features: None,
git: None,
branch: None,
tag: None,
rev: None,
path: None,
},
)]
.into_iter()
.collect(),
..Default::default()
};
let args = CliArgs::parse_from_test_args(["my-tool"]);
let spec = CrateSpec::load(&config, &args).unwrap();
assert_matches!(
spec,
CrateSpec::Registry {
source: RegistrySource::Named(ref reg),
ref name,
version: Some(ref v)
} if reg == "tool-registry"
&& name == "my-tool"
&& v == &VersionReq::parse("1.0").unwrap()
);
}
/// Test that features-only config doesn't change the [`CrateSpec`] variant.
///
/// Simulated config:
/// ```toml
/// [tools]
/// my-tool = { features = ["feat1", "feat2"] }
/// ```
///
/// Command: `cgx my-tool`
///
/// Expected: Produces [`CrateSpec::CratesIo`] (the default).
/// Features affect [`crate::cli::BuildOptions`], not [`CrateSpec`].
#[test]
fn test_tool_with_only_features() {
let mut config = Config::default();
config.tools.insert(
"my-tool".to_string(),
ToolConfig::Detailed {
version: None,
features: Some(vec!["feat1".to_string(), "feat2".to_string()]),
registry: None,
git: None,
branch: None,
tag: None,
rev: None,
path: None,
},
);
let args = CliArgs::parse_from_test_args(["my-tool"]);
let spec = CrateSpec::load(&config, &args).unwrap();
assert_matches!(
spec,
CrateSpec::CratesIo { ref name, version: None }
if name == "my-tool"
);
}
}