Skip to content

Commit 41cef47

Browse files
committed
Auto merge of #12677 - weihanglo:registry-or-index, r=hi-rustin
refactor: use `RegistryOrIndex` enum to replace two booleans
2 parents 4c10811 + 11754e9 commit 41cef47

File tree

24 files changed

+186
-95
lines changed

24 files changed

+186
-95
lines changed

src/bin/cargo/commands/init.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ pub fn cli() -> Command {
77
.about("Create a new cargo package in an existing directory")
88
.arg(Arg::new("path").action(ArgAction::Set).default_value("."))
99
.arg_new_opts()
10-
.arg(opt("registry", "Registry to use").value_name("REGISTRY"))
10+
.arg_registry("Registry to use")
1111
.arg_quiet()
1212
.after_help(color_print::cstr!(
1313
"Run `<cyan,bold>cargo help init</>` for more detailed information.\n"

src/bin/cargo/commands/install.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -154,10 +154,11 @@ pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult {
154154
} else if krates.is_empty() {
155155
from_cwd = true;
156156
SourceId::for_path(config.cwd())?
157-
} else if let Some(index) = args.get_one::<String>("index") {
158-
SourceId::for_registry(&index.into_url()?)?
159-
} else if let Some(registry) = args.registry(config)? {
160-
SourceId::alt_registry(config, &registry)?
157+
} else if let Some(reg_or_index) = args.registry_or_index(config)? {
158+
match reg_or_index {
159+
ops::RegistryOrIndex::Registry(r) => SourceId::alt_registry(config, &r)?,
160+
ops::RegistryOrIndex::Index(url) => SourceId::for_registry(&url)?,
161+
}
161162
} else {
162163
SourceId::crates_io(config)?
163164
};

src/bin/cargo/commands/login.rs

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
1-
use crate::command_prelude::*;
2-
31
use cargo::ops;
2+
use cargo::ops::RegistryOrIndex;
3+
4+
use crate::command_prelude::*;
45

56
pub fn cli() -> Command {
67
subcommand("login")
78
.about("Log in to a registry.")
89
.arg(Arg::new("token").action(ArgAction::Set))
9-
.arg(opt("registry", "Registry to use").value_name("REGISTRY"))
10+
.arg_registry("Registry to use")
1011
.arg(
1112
Arg::new("args")
1213
.help("Arguments for the credential provider (unstable)")
@@ -20,7 +21,12 @@ pub fn cli() -> Command {
2021
}
2122

2223
pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult {
23-
let registry = args.registry(config)?;
24+
let reg = args.registry_or_index(config)?;
25+
assert!(
26+
!matches!(reg, Some(RegistryOrIndex::Index(..))),
27+
"must not be index URL"
28+
);
29+
2430
let extra_args = args
2531
.get_many::<String>("args")
2632
.unwrap_or_default()
@@ -29,7 +35,7 @@ pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult {
2935
ops::registry_login(
3036
config,
3137
args.get_one::<String>("token").map(|s| s.as_str().into()),
32-
registry.as_deref(),
38+
reg.as_ref(),
3339
&extra_args,
3440
)?;
3541
Ok(())

src/bin/cargo/commands/logout.rs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,25 @@
1-
use crate::command_prelude::*;
21
use cargo::ops;
2+
use cargo::ops::RegistryOrIndex;
3+
4+
use crate::command_prelude::*;
35

46
pub fn cli() -> Command {
57
subcommand("logout")
68
.about("Remove an API token from the registry locally")
7-
.arg(opt("registry", "Registry to use").value_name("REGISTRY"))
9+
.arg_registry("Registry to use")
810
.arg_quiet()
911
.after_help(color_print::cstr!(
1012
"Run `<cyan,bold>cargo help logout</>` for more detailed information.\n"
1113
))
1214
}
1315

1416
pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult {
15-
let registry = args.registry(config)?;
16-
ops::registry_logout(config, registry.as_deref())?;
17+
let reg = args.registry_or_index(config)?;
18+
assert!(
19+
!matches!(reg, Some(RegistryOrIndex::Index(..))),
20+
"must not be index URL"
21+
);
22+
23+
ops::registry_logout(config, reg)?;
1724
Ok(())
1825
}

src/bin/cargo/commands/new.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ pub fn cli() -> Command {
77
.about("Create a new cargo package at <path>")
88
.arg(Arg::new("path").action(ArgAction::Set).required(true))
99
.arg_new_opts()
10-
.arg(opt("registry", "Registry to use").value_name("REGISTRY"))
10+
.arg_registry("Registry to use")
1111
.arg_quiet()
1212
.after_help(color_print::cstr!(
1313
"Run `<cyan,bold>cargo help new</>` for more detailed information.\n"

src/bin/cargo/commands/owner.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,29 +24,27 @@ pub fn cli() -> Command {
2424
.short('r'),
2525
)
2626
.arg(flag("list", "List owners of a crate").short('l'))
27-
.arg(opt("index", "Registry index to modify owners for").value_name("INDEX"))
27+
.arg_index("Registry index URL to modify owners for")
28+
.arg_registry("Registry to modify owners for")
2829
.arg(opt("token", "API token to use when authenticating").value_name("TOKEN"))
29-
.arg(opt("registry", "Registry to use").value_name("REGISTRY"))
3030
.arg_quiet()
3131
.after_help(color_print::cstr!(
3232
"Run `<cyan,bold>cargo help owner</>` for more detailed information.\n"
3333
))
3434
}
3535

3636
pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult {
37-
let registry = args.registry(config)?;
3837
let opts = OwnersOptions {
3938
krate: args.get_one::<String>("crate").cloned(),
4039
token: args.get_one::<String>("token").cloned().map(Secret::from),
41-
index: args.get_one::<String>("index").cloned(),
40+
reg_or_index: args.registry_or_index(config)?,
4241
to_add: args
4342
.get_many::<String>("add")
4443
.map(|xs| xs.cloned().collect()),
4544
to_remove: args
4645
.get_many::<String>("remove")
4746
.map(|xs| xs.cloned().collect()),
4847
list: args.flag("list"),
49-
registry,
5048
};
5149
ops::modify_owners(config, &opts)?;
5250
Ok(())

src/bin/cargo/commands/publish.rs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ pub fn cli() -> Command {
66
subcommand("publish")
77
.about("Upload a package to the registry")
88
.arg_dry_run("Perform all checks without uploading")
9-
.arg_index()
10-
.arg(opt("registry", "Registry to publish to").value_name("REGISTRY"))
9+
.arg_index("Registry index URL to upload the package to")
10+
.arg_registry("Registry to upload the package to")
1111
.arg(opt("token", "Token to use when uploading").value_name("TOKEN"))
1212
.arg(flag(
1313
"no-verify",
@@ -30,7 +30,7 @@ pub fn cli() -> Command {
3030
}
3131

3232
pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult {
33-
let registry = args.registry(config)?;
33+
let reg_or_index = args.registry_or_index(config)?;
3434
let ws = args.workspace(config)?;
3535
if ws.root_maybe().is_embedded() {
3636
return Err(anyhow::format_err!(
@@ -39,7 +39,6 @@ pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult {
3939
)
4040
.into());
4141
}
42-
let index = args.index()?;
4342

4443
ops::publish(
4544
&ws,
@@ -48,15 +47,14 @@ pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult {
4847
token: args
4948
.get_one::<String>("token")
5049
.map(|s| s.to_string().into()),
51-
index,
50+
reg_or_index,
5251
verify: !args.flag("no-verify"),
5352
allow_dirty: args.flag("allow-dirty"),
5453
to_publish: args.packages_from_flags()?,
5554
targets: args.targets()?,
5655
jobs: args.jobs()?,
5756
keep_going: args.keep_going(),
5857
dry_run: args.dry_run(),
59-
registry,
6058
cli_features: args.cli_features()?,
6159
},
6260
)?;

src/bin/cargo/commands/search.rs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,16 @@ pub fn cli() -> Command {
1515
)
1616
.value_name("LIMIT"),
1717
)
18-
.arg_index()
19-
.arg(opt("registry", "Registry to use").value_name("REGISTRY"))
18+
.arg_index("Registry index URL to search packages in")
19+
.arg_registry("Registry to search packages in")
2020
.arg_quiet()
2121
.after_help(color_print::cstr!(
2222
"Run `<cyan,bold>cargo help search</>` for more detailed information.\n"
2323
))
2424
}
2525

2626
pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult {
27-
let registry = args.registry(config)?;
28-
let index = args.index()?;
27+
let reg_or_index = args.registry_or_index(config)?;
2928
let limit = args.value_of_u32("limit")?;
3029
let limit = min(100, limit.unwrap_or(10));
3130
let query: Vec<&str> = args
@@ -34,6 +33,6 @@ pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult {
3433
.map(String::as_str)
3534
.collect();
3635
let query: String = query.join("+");
37-
ops::search(&query, config, index, limit, registry)?;
36+
ops::search(&query, config, reg_or_index, limit)?;
3837
Ok(())
3938
}

src/bin/cargo/commands/yank.rs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ pub fn cli() -> Command {
1616
"undo",
1717
"Undo a yank, putting a version back into the index",
1818
))
19-
.arg(opt("index", "Registry index to yank from").value_name("INDEX"))
20-
.arg(opt("registry", "Registry to use").value_name("REGISTRY"))
19+
.arg_index("Registry index URL to yank from")
20+
.arg_registry("Registry to yank from")
2121
.arg(opt("token", "API token to use when authenticating").value_name("TOKEN"))
2222
.arg_quiet()
2323
.after_help(color_print::cstr!(
@@ -26,8 +26,6 @@ pub fn cli() -> Command {
2626
}
2727

2828
pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult {
29-
let registry = args.registry(config)?;
30-
3129
let (krate, version) = resolve_crate(
3230
args.get_one::<String>("crate").map(String::as_str),
3331
args.get_one::<String>("version").map(String::as_str),
@@ -41,9 +39,8 @@ pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult {
4139
krate.map(|s| s.to_string()),
4240
version.map(|s| s.to_string()),
4341
args.get_one::<String>("token").cloned().map(Secret::from),
44-
args.get_one::<String>("index").cloned(),
42+
args.registry_or_index(config)?,
4543
args.flag("undo"),
46-
registry,
4744
)?;
4845
Ok(())
4946
}

src/cargo/ops/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ pub use self::registry::yank;
3030
pub use self::registry::OwnersOptions;
3131
pub use self::registry::PublishOpts;
3232
pub use self::registry::RegistryCredentialConfig;
33+
pub use self::registry::RegistryOrIndex;
3334
pub use self::resolve::{
3435
add_overrides, get_resolved_packages, resolve_with_previous, resolve_ws, resolve_ws_with_opts,
3536
WorkspaceResolve,

src/cargo/ops/registry/login.rs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,23 @@ use cargo_credential::Secret;
1616

1717
use super::get_source_id;
1818
use super::registry;
19+
use super::RegistryOrIndex;
1920

2021
pub fn registry_login(
2122
config: &Config,
2223
token_from_cmdline: Option<Secret<&str>>,
23-
reg: Option<&str>,
24+
reg_or_index: Option<&RegistryOrIndex>,
2425
args: &[&str],
2526
) -> CargoResult<()> {
26-
let source_ids = get_source_id(config, None, reg)?;
27-
28-
let login_url = match registry(config, token_from_cmdline.clone(), None, reg, false, None) {
27+
let source_ids = get_source_id(config, reg_or_index)?;
28+
29+
let login_url = match registry(
30+
config,
31+
token_from_cmdline.clone(),
32+
reg_or_index,
33+
false,
34+
None,
35+
) {
2936
Ok((registry, _)) => Some(format!("{}/me", registry.host())),
3037
Err(e) if e.is::<AuthorizationError>() => e
3138
.downcast::<AuthorizationError>()

src/cargo/ops/registry/logout.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,10 @@ use crate::CargoResult;
88
use crate::Config;
99

1010
use super::get_source_id;
11+
use super::RegistryOrIndex;
1112

12-
pub fn registry_logout(config: &Config, reg: Option<&str>) -> CargoResult<()> {
13-
let source_ids = get_source_id(config, None, reg)?;
13+
pub fn registry_logout(config: &Config, reg_or_index: Option<RegistryOrIndex>) -> CargoResult<()> {
14+
let source_ids = get_source_id(config, reg_or_index.as_ref())?;
1415
auth::logout(config, &source_ids.original)?;
1516
Ok(())
1617
}

src/cargo/ops/registry/mod.rs

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use std::task::Poll;
1616
use anyhow::{bail, format_err, Context as _};
1717
use cargo_credential::{Operation, Secret};
1818
use crates_io::{self, Registry};
19+
use url::Url;
1920

2021
use crate::core::SourceId;
2122
use crate::sources::source::Source;
@@ -24,7 +25,6 @@ use crate::util::auth;
2425
use crate::util::config::{Config, PathAndArgs};
2526
use crate::util::errors::CargoResult;
2627
use crate::util::network::http::http_handle;
27-
use crate::util::IntoUrl;
2828

2929
pub use self::login::registry_login;
3030
pub use self::logout::registry_logout;
@@ -35,6 +35,19 @@ pub use self::publish::PublishOpts;
3535
pub use self::search::search;
3636
pub use self::yank::yank;
3737

38+
/// Represents either `--registry` or `--index` argument, which is mutually exclusive.
39+
#[derive(Debug, Clone)]
40+
pub enum RegistryOrIndex {
41+
Registry(String),
42+
Index(Url),
43+
}
44+
45+
impl RegistryOrIndex {
46+
fn is_index(&self) -> bool {
47+
matches!(self, RegistryOrIndex::Index(..))
48+
}
49+
}
50+
3851
/// Registry settings loaded from config files.
3952
///
4053
/// This is loaded based on the `--registry` flag and the config settings.
@@ -103,14 +116,14 @@ impl RegistryCredentialConfig {
103116
fn registry(
104117
config: &Config,
105118
token_from_cmdline: Option<Secret<&str>>,
106-
index: Option<&str>,
107-
registry: Option<&str>,
119+
reg_or_index: Option<&RegistryOrIndex>,
108120
force_update: bool,
109121
token_required: Option<Operation<'_>>,
110122
) -> CargoResult<(Registry, RegistrySourceIds)> {
111-
let source_ids = get_source_id(config, index, registry)?;
123+
let source_ids = get_source_id(config, reg_or_index)?;
112124

113-
if token_required.is_some() && index.is_some() && token_from_cmdline.is_none() {
125+
let is_index = reg_or_index.map(|v| v.is_index()).unwrap_or_default();
126+
if is_index && token_required.is_some() && token_from_cmdline.is_none() {
114127
bail!("command-line argument --index requires --token to be specified");
115128
}
116129
if let Some(token) = token_from_cmdline {
@@ -171,13 +184,12 @@ fn registry(
171184
/// crates.io (such as index.crates.io), while the second is always the original source.
172185
fn get_source_id(
173186
config: &Config,
174-
index: Option<&str>,
175-
reg: Option<&str>,
187+
reg_or_index: Option<&RegistryOrIndex>,
176188
) -> CargoResult<RegistrySourceIds> {
177-
let sid = match (reg, index) {
178-
(None, None) => SourceId::crates_io(config)?,
179-
(_, Some(i)) => SourceId::for_registry(&i.into_url()?)?,
180-
(Some(r), None) => SourceId::alt_registry(config, r)?,
189+
let sid = match reg_or_index {
190+
None => SourceId::crates_io(config)?,
191+
Some(RegistryOrIndex::Index(url)) => SourceId::for_registry(url)?,
192+
Some(RegistryOrIndex::Registry(r)) => SourceId::alt_registry(config, r)?,
181193
};
182194
// Load source replacements that are built-in to Cargo.
183195
let builtin_replacement_sid = SourceConfigMap::empty(config)?
@@ -186,7 +198,7 @@ fn get_source_id(
186198
let replacement_sid = SourceConfigMap::new(config)?
187199
.load(sid, &HashSet::new())?
188200
.replaced_source_id();
189-
if reg.is_none() && index.is_none() && replacement_sid != builtin_replacement_sid {
201+
if reg_or_index.is_none() && replacement_sid != builtin_replacement_sid {
190202
// Neither --registry nor --index was passed and the user has configured source-replacement.
191203
if let Some(replacement_name) = replacement_sid.alt_registry_key() {
192204
bail!("crates-io is replaced with remote registry {replacement_name};\ninclude `--registry {replacement_name}` or `--registry crates-io`");

0 commit comments

Comments
 (0)