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

Working with features #194

Closed
wants to merge 22 commits into from
Closed
Show file tree
Hide file tree
Changes from 18 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
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ $ cargo add lib/trial-and-error/
```plain
$ cargo add --help
Usage:
cargo add <crate> [--dev|--build|--optional] [--vers=<ver>|--git=<uri>|--path=<uri>] [options]
cargo add <crates>... [--dev|--build|--optional] [options]
cargo add <crate> [--dev|--build|--optional|--features=<features>] [--vers=<ver>|--git=<uri>|--path=<uri>] [options]
cargo add <crates>... [--dev|--build|--optional|--features=<features>] [options]
cargo add (-h|--help)
cargo add --version

Expand All @@ -71,6 +71,7 @@ Specify what crate to add:
`cargo add [email protected]`.
--git <uri> Specify a git repository to download the crate from.
--path <uri> Specify the path the crate should be loaded from.
--features <FEATURES> Space-separated list of features to add

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should follow cargo in describing the feature flag:

$ cargo build --help 2>&1 | grep -e "--features"
    --features FEATURES          Space-separated list of features to also build

(and maybe replace also build with add)

Specify where to add the crate:
-D --dev Add crate as development dependency.
Expand Down
10 changes: 6 additions & 4 deletions src/bin/add/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ pub struct Args {
pub flag_allow_prerelease: bool,
/// '--quiet'
pub flag_quiet: bool,
/// '--features'
pub flag_features: Option<String>,
}

impl Args {
Expand Down Expand Up @@ -71,7 +73,7 @@ impl Args {
parse_crate_name_with_version(arg_crate)?
} else {
get_latest_dependency(arg_crate, self.flag_allow_prerelease)?
}.set_optional(self.flag_optional);
}.set_optional(self.flag_optional).set_features(self.flag_features.clone());

result.push(le_crate);
}
Expand All @@ -80,14 +82,13 @@ impl Args {

if crate_name_has_version(&self.arg_crate) {
return Ok(vec![
parse_crate_name_with_version(&self.arg_crate)?.set_optional(self.flag_optional),
parse_crate_name_with_version(&self.arg_crate)?.set_optional(self.flag_optional).set_features(self.flag_features.clone()),
]);
}


let dependency = if !crate_name_is_url_or_path(&self.arg_crate) {
let dependency = Dependency::new(&self.arg_crate);

if let Some(ref version) = self.flag_vers {
semver::VersionReq::parse(version)
.chain_err(|| "Invalid dependency version requirement")?;
Expand All @@ -109,7 +110,7 @@ impl Args {
}
} else {
parse_crate_name_from_uri(&self.arg_crate)?
}.set_optional(self.flag_optional);
}.set_optional(self.flag_optional).set_features(self.flag_features.clone());

Ok(vec![dependency])
}
Expand Down Expand Up @@ -150,6 +151,7 @@ impl Default for Args {
flag_upgrade: None,
flag_allow_prerelease: false,
flag_quiet: false,
flag_features: None,
}
}
}
Expand Down
12 changes: 8 additions & 4 deletions src/bin/add/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ use errors::*;

static USAGE: &'static str = r#"
Usage:
cargo add <crate> [--dev|--build|--optional] [--vers=<ver>|--git=<uri>|--path=<uri>] [options]
cargo add <crates>... [--dev|--build|--optional] [options]
cargo add <crate> [--dev|--build|--optional|--features=<features>] [--vers=<ver>|--git=<uri>|--path=<uri>] [options]
cargo add <crates>... [--dev|--build|--optional|--features=<features>] [options]
cargo add (-h|--help)
cargo add --version

Expand All @@ -55,6 +55,7 @@ Specify where to add the crate:
for `dev-dependencies` or `build-dependencies`.
--target <target> Add as dependency to the given target platform. This does not work
for `dev-dependencies` or `build-dependencies`.
--features <FEATURES> Space-separated list of features to add

Options:
--upgrade=<method> Choose method of semantic version upgrade. Must be one of
Expand All @@ -77,7 +78,7 @@ crates.io registry suggests. One goal of `cargo add` is to prevent you from usin
dependencies (version set to "*").
"#;

fn print_msg(dep: &Dependency, section: &[String], optional: bool) -> Result<()> {
fn print_msg(dep: &Dependency, section: &[String], optional: bool, features: Option<String>) -> Result<()> {
let colorchoice = if atty::is(atty::Stream::Stdout) {
ColorChoice::Auto
} else {
Expand All @@ -97,6 +98,9 @@ fn print_msg(dep: &Dependency, section: &[String], optional: bool) -> Result<()>
if optional {
write!(output, " optional")?;
}
if let Some(f) = features {
write!(output, " features {}", f)?
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you place this output after line 109 (and change writeln to write), so that the output would be

... to dependencies with features: jui

rather than

to features jui dependencies

}
let section = if section.len() == 1 {
section[0].clone()
} else {
Expand All @@ -114,7 +118,7 @@ fn handle_add(args: &Args) -> Result<()> {
deps.iter()
.map(|dep| {
if !args.flag_quiet {
print_msg(dep, &args.get_section(), args.flag_optional)?;
print_msg(dep, &args.get_section(), args.flag_optional, args.flag_features.clone())?;
}
manifest
.insert_into_table(&args.get_section(), dep)
Expand Down
22 changes: 18 additions & 4 deletions src/dependency.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use toml_edit;
use std::iter::FromIterator;

#[derive(Debug, Hash, PartialEq, Eq, Clone)]
enum DependencySource {
Expand All @@ -14,6 +15,7 @@ pub struct Dependency {
pub name: String,
optional: bool,
source: DependencySource,
features: Vec<String>,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to distinguish an empty feature list from the default feature list (not specifying the feature flag).

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi Ordian,
Thanks for your suggestion. "cargo list" or "cargo read-manifest" can only read the local cargo.toml manifest file. When you add a dependency to your project, you don't save a copy of the manifest file of the dependencies. Without the manifest file of the dependency, there is no way of returning the list of the available features. I think this enhancement is only useful for experienced users who would check out the available features themselves. I am only motivated in using cargo-edit because Cargo does not support Target specific features. rust-lang/cargo#1197
With cargo-edit being able to specify features, I can use continuous integration to build various target builds with dependencies with various features.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. We download Cargo.toml locally for git dependencies in cargo-edit (and download json for crates.io dependencies), so a proper way to extract feature list would be to create a function get_features_from_manifest similar to get_name_from_manifest. But that can be done in a separate PR.
  2. The point of the comment is different: if user of cargo-edit does not specify --features when adding a dependency, he probably wants a default feature list, not the empty one. Btw, current CI failure is relevant.

}

impl Default for Dependency {
Expand All @@ -22,6 +24,7 @@ impl Default for Dependency {
name: "".into(),
optional: false,
source: DependencySource::Version("0.1.0".into()),
features: vec![],
}
}
}
Expand Down Expand Up @@ -58,6 +61,13 @@ impl Dependency {
self.optional = opt;
self
}
/// Set whether the features is array of string
pub fn set_features(mut self, features: Option<String>) -> Dependency {
if let Some(f) = features {
self.features = f.split(' ').map(String::from).collect::<Vec<String>>();
}
self
}

/// Get version of dependency
pub fn version(&self) -> Option<&str> {
Expand All @@ -74,11 +84,12 @@ impl Dependency {
/// or the path/git repository as an `InlineTable`.
/// (If the dependency is set as `optional`, an `InlineTable` is returned in any case.)
pub fn to_toml(&self) -> (String, toml_edit::Item) {
let data: toml_edit::Item = match (self.optional, self.source.clone()) {
let data: toml_edit::Item = match (self.optional, self.features.len(), self.source.clone())
{
// Extra short when version flag only
(false, DependencySource::Version(v)) => toml_edit::value(v),
(false, 0, DependencySource::Version(v)) => toml_edit::value(v),
// Other cases are represented as an inline table
(optional, source) => {
(optional, _len, source) => {
let mut data = toml_edit::InlineTable::default();

match source {
Expand All @@ -95,7 +106,10 @@ impl Dependency {
if self.optional {
data.get_or_insert("optional", optional);
}

if !self.features.is_empty() {
let features = toml_edit::Value::from_iter(self.features.iter().cloned());
data.get_or_insert("features", features);
}
data.fmt();
toml_edit::value(toml_edit::Value::InlineTable(data))
}
Expand Down
42 changes: 38 additions & 4 deletions tests/cargo-add.rs
Original file line number Diff line number Diff line change
Expand Up @@ -536,6 +536,23 @@ fn adds_dependency_with_target_cfg() {
assert_eq!(val.as_str().unwrap(), "my-package1--CURRENT_VERSION_TEST");
}

#[test]
fn adds_features_dependency() {
let (_tmpdir, manifest) = clone_out_test("tests/fixtures/add/Cargo.toml.sample");

// dependency not present beforehand
let toml = get_toml(&manifest);
assert!(toml["dependencies"].is_none());

execute_command(&["add", "https://github.com/killercup/cargo-edit.git", "--features", "jui"],
&manifest);

// dependency present afterwards
let toml = get_toml(&manifest);
let val = toml["dependencies"]["cargo-edit"]["features"][0].as_str();
assert_eq!(val, Some("jui"));
}

#[test]
fn adds_dependency_with_custom_target() {
let (_tmpdir, manifest) = clone_out_test("tests/fixtures/add/Cargo.toml.sample");
Expand Down Expand Up @@ -746,8 +763,8 @@ fn no_argument() {
r"Invalid arguments.

Usage:
cargo add <crate> [--dev|--build|--optional] [--vers=<ver>|--git=<uri>|--path=<uri>] [options]
cargo add <crates>... [--dev|--build|--optional] [options]
cargo add <crate> [--dev|--build|--optional|--features=<features>] [--vers=<ver>|--git=<uri>|--path=<uri>] [options]
cargo add <crates>... [--dev|--build|--optional|--features=<features>] [options]
cargo add (-h|--help)
cargo add --version",
)
Expand All @@ -762,8 +779,8 @@ fn unknown_flags() {
r"Unknown flag: '--flag'

Usage:
cargo add <crate> [--dev|--build|--optional] [--vers=<ver>|--git=<uri>|--path=<uri>] [options]
cargo add <crates>... [--dev|--build|--optional] [options]
cargo add <crate> [--dev|--build|--optional|--features=<features>] [--vers=<ver>|--git=<uri>|--path=<uri>] [options]
cargo add <crates>... [--dev|--build|--optional|--features=<features>] [options]
cargo add (-h|--help)
cargo add --version",
)
Expand Down Expand Up @@ -835,3 +852,20 @@ fn add_prints_message_for_build_deps() {
.prints_exactly("Adding hello-world v0.1.0 to build-dependencies")
.unwrap();
}
#[test]
fn add_prints_message_for_features_deps() {
let (_tmpdir, manifest) = clone_out_test("tests/fixtures/add/Cargo.toml.sample");

assert_cli::Assert::command(&[
"target/debug/cargo-add",
"add",
"hello-world",
"--vers",
"0.1.0",
"--features",
"jui",
&format!("--manifest-path={}", manifest),
]).succeeds()
.prints_exactly("Adding hello-world v0.1.0 to features jui dependencies")
.unwrap();
}