Skip to content

Commit

Permalink
Auto merge of #6135 - cswindle:default-registry, r=alexcrichton
Browse files Browse the repository at this point in the history
Add support for a default registry for cargo commands

This adds two things:
  - --registry support for new and init
 - adds default registry configuration to cargo

The main reason for these changes is to reduce the risk of closed-source software ending up accidentally on crates.io.

This fixes #6123.
  • Loading branch information
bors committed Oct 8, 2018
2 parents aa06d7c + 1fd3f1b commit 5dbac98
Show file tree
Hide file tree
Showing 12 changed files with 58 additions and 15 deletions.
19 changes: 17 additions & 2 deletions src/bin/cargo/command_prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use cargo::CargoResult;
use cargo::core::Workspace;
use cargo::core::compiler::{BuildConfig, MessageFormat};
use cargo::ops::{CompileFilter, CompileOptions, NewOptions, Packages, VersionControl};
use cargo::sources::CRATES_IO_REGISTRY;
use cargo::util::paths;
use cargo::util::important_paths::find_root_manifest_for_wd;

Expand Down Expand Up @@ -347,6 +348,7 @@ pub trait ArgMatchesExt {
self.value_of_path("path", config).unwrap(),
self._value_of("name").map(|s| s.to_string()),
self._value_of("edition").map(|s| s.to_string()),
self.registry(config)?,
)
}

Expand All @@ -359,9 +361,22 @@ pub trait ArgMatchesExt {
requires -Zunstable-options to use."
));
}
Ok(Some(registry.to_string()))

if registry == CRATES_IO_REGISTRY {
// If "crates.io" is specified then we just need to return None
// as that will cause cargo to use crates.io. This is required
// for the case where a default alterative registry is used
// but the user wants to switch back to crates.io for a single
// command.
Ok(None)
}
else {
Ok(Some(registry.to_string()))
}
}
None => {
config.default_registry()
}
None => Ok(None),
}
}

Expand Down
1 change: 1 addition & 0 deletions src/bin/cargo/commands/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ pub fn cli() -> App {
subcommand("init")
.about("Create a new cargo package in an existing directory")
.arg(Arg::with_name("path").default_value("."))
.arg(opt("registry", "Registry to use").value_name("REGISTRY"))
.arg_new_opts()
}

Expand Down
1 change: 1 addition & 0 deletions src/bin/cargo/commands/new.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ pub fn cli() -> App {
subcommand("new")
.about("Create a new cargo package at <path>")
.arg(Arg::with_name("path").required(true))
.arg(opt("registry", "Registry to use").value_name("REGISTRY"))
.arg_new_opts()
}

Expand Down
4 changes: 2 additions & 2 deletions src/cargo/core/package_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,12 +182,12 @@ impl fmt::Debug for PackageId {
mod tests {
use super::PackageId;
use core::source::SourceId;
use sources::CRATES_IO;
use sources::CRATES_IO_INDEX;
use util::ToUrl;

#[test]
fn invalid_version_handled_nicely() {
let loc = CRATES_IO.to_url().unwrap();
let loc = CRATES_IO_INDEX.to_url().unwrap();
let repo = SourceId::for_registry(&loc).unwrap();

assert!(PackageId::new("foo", "1.0", &repo).is_err());
Expand Down
6 changes: 3 additions & 3 deletions src/cargo/core/source/source_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use url::Url;

use ops;
use sources::git;
use sources::{GitSource, PathSource, RegistrySource, CRATES_IO};
use sources::{GitSource, PathSource, RegistrySource, CRATES_IO_INDEX};
use sources::DirectorySource;
use util::{CargoResult, Config, ToUrl};

Expand Down Expand Up @@ -184,7 +184,7 @@ impl SourceId {
}
&index[..]
} else {
CRATES_IO
CRATES_IO_INDEX
};
let url = url.to_url()?;
SourceId::for_registry(&url)
Expand Down Expand Up @@ -302,7 +302,7 @@ impl SourceId {
Kind::Registry => {}
_ => return false,
}
self.inner.url.to_string() == CRATES_IO
self.inner.url.to_string() == CRATES_IO_INDEX
}

/// Hash `self`
Expand Down
16 changes: 15 additions & 1 deletion src/cargo/ops/cargo_new.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub struct NewOptions {
pub path: PathBuf,
pub name: Option<String>,
pub edition: Option<String>,
pub registry: Option<String>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
Expand Down Expand Up @@ -67,6 +68,7 @@ struct MkOptions<'a> {
source_files: Vec<SourceFileInformation>,
bin: bool,
edition: Option<&'a str>,
registry: Option<&'a str>,
}

impl NewOptions {
Expand All @@ -77,6 +79,7 @@ impl NewOptions {
path: PathBuf,
name: Option<String>,
edition: Option<String>,
registry: Option<String>,
) -> CargoResult<NewOptions> {
let kind = match (bin, lib) {
(true, true) => bail!("can't specify both lib and binary outputs"),
Expand All @@ -91,6 +94,7 @@ impl NewOptions {
path,
name,
edition,
registry,
};
Ok(opts)
}
Expand Down Expand Up @@ -326,6 +330,7 @@ pub fn new(opts: &NewOptions, config: &Config) -> CargoResult<()> {
source_files: vec![plan_new_source_file(opts.kind.is_bin(), name.to_string())],
bin: opts.kind.is_bin(),
edition: opts.edition.as_ref().map(|s| &**s),
registry: opts.registry.as_ref().map(|s| &**s),
};

mk(config, &mkopts).chain_err(|| {
Expand Down Expand Up @@ -403,6 +408,7 @@ pub fn init(opts: &NewOptions, config: &Config) -> CargoResult<()> {
bin: src_paths_types.iter().any(|x| x.bin),
source_files: src_paths_types,
edition: opts.edition.as_ref().map(|s| &**s),
registry: opts.registry.as_ref().map(|s| &**s),
};

mk(config, &mkopts).chain_err(|| {
Expand Down Expand Up @@ -537,7 +543,7 @@ name = "{}"
version = "0.1.0"
authors = [{}]
edition = {}
{}
[dependencies]
{}"#,
name,
Expand All @@ -546,6 +552,14 @@ edition = {}
Some(edition) => toml::Value::String(edition.to_string()),
None => toml::Value::String("2018".to_string()),
},
match opts.registry {
Some(registry) => {
format!("publish = {}\n",
toml::Value::Array(vec!(toml::Value::String(registry.to_string())))
)
}
None => "".to_string(),
},
cargotoml_path_specifier
).as_bytes(),
)?;
Expand Down
4 changes: 2 additions & 2 deletions src/cargo/sources/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use std::path::{Path, PathBuf};
use url::Url;

use core::{GitReference, Source, SourceId};
use sources::ReplacedSource;
use sources::{ReplacedSource, CRATES_IO_REGISTRY};
use util::{Config, ToUrl};
use util::config::ConfigValue;
use util::errors::{CargoResult, CargoResultExt};
Expand Down Expand Up @@ -59,7 +59,7 @@ impl<'cfg> SourceConfigMap<'cfg> {
config,
};
base.add(
"crates-io",
CRATES_IO_REGISTRY,
SourceConfig {
id: SourceId::crates_io(config)?,
replace_with: None,
Expand Down
2 changes: 1 addition & 1 deletion src/cargo/sources/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ pub use self::config::SourceConfigMap;
pub use self::directory::DirectorySource;
pub use self::git::GitSource;
pub use self::path::PathSource;
pub use self::registry::{RegistrySource, CRATES_IO};
pub use self::registry::{RegistrySource, CRATES_IO_INDEX, CRATES_IO_REGISTRY};
pub use self::replaced::ReplacedSource;

pub mod config;
Expand Down
3 changes: 2 additions & 1 deletion src/cargo/sources/registry/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,8 @@ use util::to_url::ToUrl;
use util::{internal, CargoResult, Config, FileLock, Filesystem};

const INDEX_LOCK: &str = ".cargo-index-lock";
pub const CRATES_IO: &str = "https://github.com/rust-lang/crates.io-index";
pub const CRATES_IO_INDEX: &str = "https://github.com/rust-lang/crates.io-index";
pub const CRATES_IO_REGISTRY: &str = "crates-io";
const CRATE_TEMPLATE: &str = "{crate}";
const VERSION_TEMPLATE: &str = "{version}";

Expand Down
10 changes: 10 additions & 0 deletions src/cargo/util/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,16 @@ impl Config {
self.home_path.join("registry").join("src")
}

/// The default cargo registry (`alternative-registry`)
pub fn default_registry(&self) -> CargoResult<Option<String>> {
Ok(
match self.get_string("registry.default")? {
Some(registry) => Some(registry.val),
None => None,
}
)
}

/// Get a reference to the shell, for e.g. writing error messages
pub fn shell(&self) -> RefMut<Shell> {
self.shell.borrow_mut()
Expand Down
6 changes: 3 additions & 3 deletions src/cargo/util/toml/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use core::profiles::Profiles;
use core::{Dependency, Manifest, PackageId, Summary, Target};
use core::{Edition, EitherManifest, Feature, Features, VirtualManifest};
use core::{GitReference, PackageIdSpec, SourceId, WorkspaceConfig, WorkspaceRootConfig};
use sources::CRATES_IO;
use sources::{CRATES_IO_INDEX, CRATES_IO_REGISTRY};
use util::errors::{CargoError, CargoResult, CargoResultExt};
use util::paths;
use util::{self, Config, ToUrl};
Expand Down Expand Up @@ -1140,7 +1140,7 @@ impl TomlManifest {
)
})?;
if spec.url().is_none() {
spec.set_url(CRATES_IO.parse().unwrap());
spec.set_url(CRATES_IO_INDEX.parse().unwrap());
}

let version_specified = match *replacement {
Expand Down Expand Up @@ -1175,7 +1175,7 @@ impl TomlManifest {
let mut patch = HashMap::new();
for (url, deps) in self.patch.iter().flat_map(|x| x) {
let url = match &url[..] {
"crates-io" => CRATES_IO.parse().unwrap(),
CRATES_IO_REGISTRY => CRATES_IO_INDEX.parse().unwrap(),
_ => url.to_url()?,
};
patch.insert(
Expand Down
1 change: 1 addition & 0 deletions src/doc/src/reference/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ runner = ".."
[registry]
index = "..." # URL of the registry index (defaults to the central repository)
token = "..." # Access token (found on the central repo’s website)
default = "..." # Default alternative registry to use (can be overriden with --registry)

[http]
proxy = "host:port" # HTTP proxy to use for HTTP requests (defaults to none)
Expand Down

0 comments on commit 5dbac98

Please sign in to comment.