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

Support namespaced features #154

Merged
merged 1 commit into from
Jul 18, 2022
Merged
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ Note: In this file, do not use the hard wrap in the middle of a sentence for com

## [Unreleased]

- Support namespaced features (features with `dep:` prefix). ([#154](https://github.com/taiki-e/cargo-hack/pull/154))

- Add metadata for cargo binstall.

## [0.5.14] - 2022-06-02
Expand Down
29 changes: 7 additions & 22 deletions src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,34 +46,28 @@ impl Context {
bail!("--include-deps-features requires Cargo 1.41 or later");
}

let mut manifests = HashMap::with_capacity(metadata.workspace_members.len());
let mut pkg_features = HashMap::with_capacity(metadata.workspace_members.len());

for id in &metadata.workspace_members {
let features = Features::new(&metadata, id);
let manifest_path = &metadata.packages[id].manifest_path;
let manifest = Manifest::new(manifest_path)?;
let features = Features::new(&metadata, &manifest, id);
manifests.insert(id.clone(), manifest);
pkg_features.insert(id.clone(), features);
}

let mut this = Self {
args,
metadata,
manifests: HashMap::new(),
manifests,
pkg_features,
cargo: cargo.into(),
restore,
current_dir: env::current_dir()?,
version_range: None,
};

// Only a few options require information from cargo manifest.
// If manifest information is not required, do not read and parse them.
if this.require_manifest_info() {
this.manifests.reserve(this.metadata.workspace_members.len());
for id in &this.metadata.workspace_members {
let manifest_path = &this.metadata.packages[id].manifest_path;
let manifest = Manifest::new(manifest_path)?;
this.manifests.insert(id.clone(), manifest);
}
}

this.version_range = this
.args
.version_range
Expand Down Expand Up @@ -103,7 +97,6 @@ impl Context {
}

pub(crate) fn manifests(&self, id: &PackageId) -> &Manifest {
debug_assert!(self.require_manifest_info());
&self.manifests[id]
}

Expand Down Expand Up @@ -140,14 +133,6 @@ impl Context {
}
}

/// Return `true` if options that require information from cargo manifest is specified.
pub(crate) fn require_manifest_info(&self) -> bool {
(self.metadata.cargo_version < 39 && self.ignore_private)
|| (self.metadata.cargo_version < 58 && self.args.version_range.is_some())
|| self.no_dev_deps
|| self.remove_dev_deps
}

pub(crate) fn cargo(&self) -> ProcessBuilder<'_> {
cmd!(&self.cargo)
}
Expand Down
17 changes: 14 additions & 3 deletions src/features.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{
slice,
};

use crate::{metadata::Metadata, PackageId};
use crate::{manifest::Manifest, metadata::Metadata, PackageId};

#[derive(Debug)]
pub(crate) struct Features {
Expand All @@ -13,15 +13,26 @@ pub(crate) struct Features {
}

impl Features {
pub(crate) fn new(metadata: &Metadata, id: &PackageId) -> Self {
pub(crate) fn new(metadata: &Metadata, manifest: &Manifest, id: &PackageId) -> Self {
let package = &metadata.packages[id];
let node = &metadata.resolve.nodes[id];

let mut features = Vec::with_capacity(package.features.len());
let mut optional_deps = vec![];
let mut namespaced_features = vec![]; // features with `dep:` prefix

// package.features.values() does not provide a way to determine the `dep:` specified by the user.
for names in manifest.features.values() {
for name in names {
if let Some(name) = name.strip_prefix("dep:") {
namespaced_features.push(name);
}
}
}
for name in package.optional_deps() {
optional_deps.push(name);
if !namespaced_features.contains(&name) {
optional_deps.push(name);
}
}
for name in package.features.keys() {
if !optional_deps.contains(&&**name) {
Expand Down
33 changes: 31 additions & 2 deletions src/manifest.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::path::Path;
use std::{collections::BTreeMap, path::Path};

use anyhow::{format_err, Context as _, Result};

Expand All @@ -12,6 +12,7 @@ pub(crate) struct Manifest {
pub(crate) raw: String,
pub(crate) doc: toml_edit::Document,
pub(crate) package: Package,
pub(crate) features: BTreeMap<String, Vec<String>>,
}

impl Manifest {
Expand All @@ -23,7 +24,10 @@ impl Manifest {
let package = Package::from_table(&doc).map_err(|s| {
format_err!("failed to parse `{}` field from manifest `{}`", s, path.display())
})?;
Ok(Self { raw, doc, package })
let features = Features::from_table(&doc).map_err(|s| {
format_err!("failed to parse `{}` field from manifest `{}`", s, path.display())
})?;
Ok(Self { raw, doc, package, features })
}

pub(crate) fn remove_dev_deps(&self) -> String {
Expand Down Expand Up @@ -62,6 +66,31 @@ impl Package {
}
}

struct Features {}

impl Features {
fn from_table(doc: &toml_edit::Document) -> ParseResult<BTreeMap<String, Vec<String>>> {
let features = match doc.get("features") {
Some(features) => features.as_table().ok_or("features")?,
None => return Ok(BTreeMap::new()),
};
let mut res = BTreeMap::new();
for (name, values) in features {
res.insert(
name.to_owned(),
values
.as_array()
.ok_or("features")?
.into_iter()
.flat_map(toml_edit::Value::as_str)
.map(str::to_owned)
.collect(),
);
}
Ok(res)
}
}

fn remove_dev_deps(doc: &mut toml_edit::Document) {
const KEY: &str = "dev-dependencies";
let table = doc.as_table_mut();
Expand Down
16 changes: 16 additions & 0 deletions tests/fixtures/namespaced_features/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[package]
name = "namespaced_features"
version = "0.0.0"
edition = "2021"
publish = false

[workspace]
resolver = "2"

[features]
easytime = ["dep:easytime"]

[dependencies]
easytime = { version = "0.2", optional = true, default-features = false }

[dev-dependencies]
Empty file.
12 changes: 12 additions & 0 deletions tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1393,3 +1393,15 @@ fn keep_going() {
",
));
}

#[test]
fn namespaced_features() {
cargo_hack(["check", "--feature-powerset"])
.assert_success2("namespaced_features", Some(60))
.stderr_contains(
"
running `cargo check --no-default-features` on namespaced_features (1/2)
running `cargo check --no-default-features --features easytime` on namespaced_features (2/2)
",
);
}