Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement generate-index-metadata command #6324

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/bin/cargo/commands/generate_index_metadata.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use cargo::ops;
use cargo::print_json;
use crate::command_prelude::*;

pub fn cli() -> App {
subcommand("generate-index-metadata")
.about(
"Output index file metadata, \
required by registry",
)
.arg_manifest_path()
}

pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
let ws = args.workspace(config)?;

let result = ops::generate_index_metadata(&ws)?;

print_json(&result);

Ok(())
}
3 changes: 3 additions & 0 deletions src/bin/cargo/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ pub fn builtin() -> Vec<App> {
doc::cli(),
fetch::cli(),
fix::cli(),
generate_index_metadata::cli(),
generate_lockfile::cli(),
git_checkout::cli(),
init::cli(),
Expand Down Expand Up @@ -44,6 +45,7 @@ pub fn builtin_exec(cmd: &str) -> Option<fn(&mut Config, &ArgMatches<'_>) -> Cli
"doc" => doc::exec,
"fetch" => fetch::exec,
"fix" => fix::exec,
"generate-index-metadata" => generate_index_metadata::exec,
"generate-lockfile" => generate_lockfile::exec,
"git-checkout" => git_checkout::exec,
"init" => init::exec,
Expand Down Expand Up @@ -79,6 +81,7 @@ pub mod clean;
pub mod doc;
pub mod fetch;
pub mod fix;
pub mod generate_index_metadata;
pub mod generate_lockfile;
pub mod git_checkout;
pub mod init;
Expand Down
16 changes: 16 additions & 0 deletions src/cargo/core/dependency.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,22 @@ impl ser::Serialize for Kind {
}
}

impl fmt::Display for Kind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}

impl Kind {
pub fn as_str(&self) -> &'static str {
match *self {
Kind::Normal => "normal",
Kind::Build => "build",
Kind::Development => "dev",
}
}
}

impl Dependency {
/// Attempt to create a `Dependency` from an entry in the manifest.
pub fn parse(
Expand Down
14 changes: 13 additions & 1 deletion src/cargo/core/interning.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use serde::{Serialize, Serializer};

use std::borrow::Borrow;
use std::borrow::{Borrow, Cow};
use std::cmp::Ordering;
use std::collections::HashSet;
use std::fmt;
Expand Down Expand Up @@ -105,3 +105,15 @@ impl Serialize for InternedString {
serializer.serialize_str(self.inner)
}
}

impl From<InternedString> for Cow<'static, str> {
fn from(s: InternedString) -> Self {
s.as_str().into()
}
}

impl<'a> From<&'a InternedString> for Cow<'static, str> {
fn from(s: &InternedString) -> Self {
s.as_str().into()
}
}
18 changes: 18 additions & 0 deletions src/cargo/ops/cargo_generate_index_metadata.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
use crate::core::Workspace;
use crate::sources::registry::RegistryPackage;
use crate::util::errors::{CargoResult, CargoResultExt};

/// Generate index metadata for packages
pub fn generate_index_metadata<'a>(ws: &Workspace<'_>) -> CargoResult<RegistryPackage<'a>> {
let pkg = ws.current()?;
let config = ws.config();
let filename = format!("{}-{}.crate", pkg.name(), pkg.version());
let dir = ws.target_dir().join("package");

dir.open_ro(filename, config, "package file")
.and_then(|pkg_file| RegistryPackage::from_package(pkg, pkg_file))
.chain_err(|| {
"could not find package file. Ensure that crate has been packaged using `cargo package`"
})
.map_err(Into::into)
}
2 changes: 2 additions & 0 deletions src/cargo/ops/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ pub use self::cargo_compile::{compile, compile_with_exec, compile_ws, CompileOpt
pub use self::cargo_compile::{CompileFilter, FilterRule, Packages};
pub use self::cargo_doc::{doc, DocOptions};
pub use self::cargo_fetch::{fetch, FetchOptions};
pub use self::cargo_generate_index_metadata::generate_index_metadata;
pub use self::cargo_generate_lockfile::generate_lockfile;
pub use self::cargo_generate_lockfile::update_lockfile;
pub use self::cargo_generate_lockfile::UpdateOptions;
Expand Down Expand Up @@ -30,6 +31,7 @@ mod cargo_clean;
mod cargo_compile;
mod cargo_doc;
mod cargo_fetch;
mod cargo_generate_index_metadata;
mod cargo_generate_lockfile;
mod cargo_install;
mod cargo_new;
Expand Down
8 changes: 1 addition & 7 deletions src/cargo/ops/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ use curl::easy::{Easy, InfoType, SslOpt};
use log::{log, Level};
use url::percent_encoding::{percent_encode, QUERY_ENCODE_SET};

use crate::core::dependency::Kind;
use crate::core::manifest::ManifestMetadata;
use crate::core::source::Source;
use crate::core::{Package, SourceId, Workspace};
Expand Down Expand Up @@ -173,12 +172,7 @@ fn transmit(
features: dep.features().iter().map(|s| s.to_string()).collect(),
version_req: dep.version_req().to_string(),
target: dep.platform().map(|s| s.to_string()),
kind: match dep.kind() {
Kind::Normal => "normal",
Kind::Build => "build",
Kind::Development => "dev",
}
.to_string(),
kind: dep.kind().to_string(),
registry: dep_registry,
explicit_name_in_toml: dep.explicit_name_in_toml().map(|s| s.to_string()),
})
Expand Down
67 changes: 63 additions & 4 deletions src/cargo/sources/registry/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,12 +161,13 @@
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};

use flate2::read::GzDecoder;
use log::debug;
use semver::Version;
use serde::Deserialize;
use serde::{Serialize, Deserialize};
use tar::Archive;

use crate::core::dependency::{Dependency, Kind};
Expand All @@ -176,7 +177,7 @@ use crate::sources::PathSource;
use crate::util::errors::CargoResultExt;
use crate::util::hex;
use crate::util::to_url::ToUrl;
use crate::util::{internal, CargoResult, Config, FileLock, Filesystem};
use crate::util::{internal, CargoResult, Config, FileLock, Filesystem, Sha256};

const INDEX_LOCK: &str = ".cargo-index-lock";
pub const CRATES_IO_INDEX: &str = "https://github.com/rust-lang/crates.io-index";
Expand Down Expand Up @@ -214,14 +215,15 @@ pub struct RegistryConfig {
pub api: Option<String>,
}

#[derive(Deserialize)]
#[derive(Serialize, Deserialize)]
pub struct RegistryPackage<'a> {
name: Cow<'a, str>,
vers: Version,
deps: Vec<RegistryDependency<'a>>,
features: BTreeMap<Cow<'a, str>, Vec<Cow<'a, str>>>,
cksum: String,
yanked: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
links: Option<Cow<'a, str>>,
}

Expand Down Expand Up @@ -270,7 +272,7 @@ enum Field {
Links,
}

#[derive(Deserialize)]
#[derive(Serialize, Deserialize)]
struct RegistryDependency<'a> {
name: Cow<'a, str>,
req: Cow<'a, str>,
Expand All @@ -279,10 +281,48 @@ struct RegistryDependency<'a> {
default_features: bool,
target: Option<Cow<'a, str>>,
kind: Option<Cow<'a, str>>,
#[serde(skip_serializing_if = "Option::is_none")]
registry: Option<Cow<'a, str>>,
#[serde(skip_serializing_if = "Option::is_none")]
package: Option<Cow<'a, str>>,
}

impl<'a> RegistryPackage<'a> {
pub fn from_package(pkg: &Package, mut pkg_file: FileLock) -> CargoResult<Self> {
let cksum = {
let mut c = Vec::new();
pkg_file.read_to_end(&mut c)?;

let mut sha = Sha256::new();
sha.update(&c);
::hex::encode(&sha.finish())
};
let summary = pkg.summary();

Ok(
Self {
name: pkg.name().as_str().into(),
vers: pkg.version().clone(),
deps: pkg.dependencies().into_iter().map(RegistryDependency::from_dep).collect(),
features: summary
.features()
.into_iter()
.map(|(name, values)| (
name.as_str().into(),
values
.into_iter()
.map(|value| value.to_string(summary).into())
.collect())
)
.collect(),
cksum,
yanked: Some(false),
links: pkg.summary().links().map(|link| link.as_str().into())
}
)
}
}

impl<'a> RegistryDependency<'a> {
/// Converts an encoded dependency in the registry to a cargo dependency
pub fn into_dep(self, default: SourceId) -> CargoResult<Dependency> {
Expand Down Expand Up @@ -335,6 +375,25 @@ impl<'a> RegistryDependency<'a> {

Ok(dep)
}

pub fn from_dep(dep: &Dependency) -> Self {
let (name, package) = match dep.explicit_name_in_toml() {
Some(explicit) => (explicit.into(), Some(dep.package_name().into())),
None => (dep.package_name().into(), None),
};

Self {
name,
req: dep.version_req().to_string().into(),
features: dep.features().into_iter().map(|f| f.into()).collect(),
optional: dep.is_optional(),
default_features: dep.uses_default_features(),
target: dep.platform().map(|s| s.to_string().into()),
kind: Some(dep.kind().as_str().into()),
registry: dep.registry_id().map(|s| s.url().to_string().into()),
package
}
}
}

pub trait RegistryData {
Expand Down
Loading