Auto merge of #5485 - patriksvensson:feature/GH-5474, r=matklad

Do not allow running library examples.

This is my first contribution to anything Rust related that I haven't written myself, and I'm not a very proficient Rust programmer (yet), so would love some feedback on improvements.

I also might have solved this the wrong way... 😄

Closes #5474

(cc @matklad)
This commit is contained in:
bors 2018-05-05 14:24:55 +00:00
commit 556f80f3dc
3 changed files with 54 additions and 6 deletions

View File

@ -160,7 +160,7 @@ impl<'a, 'cfg> Context<'a, 'cfg> {
unit.target.name().to_string(),
output.path.clone(),
));
} else if unit.target.is_bin() || unit.target.is_example() {
} else if unit.target.is_bin() || unit.target.is_bin_example() {
self.compilation.binaries.push(bindst.clone());
} else if unit.target.is_lib() {
let pkgid = unit.pkg.package_id().clone();

View File

@ -2,7 +2,7 @@ use std::path::Path;
use ops::{self, Packages};
use util::{self, CargoResult, ProcessError};
use core::Workspace;
use core::{TargetKind, Workspace};
pub fn run(
ws: &Workspace,
@ -36,7 +36,7 @@ pub fn run(
options.filter.target_run(a)
}
})
.map(|bin| bin.name())
.map(|bin| (bin.name(), bin.kind()))
.collect();
if bins.is_empty() {
@ -46,13 +46,29 @@ pub fn run(
// this will be verified in cargo_compile
}
}
if bins.len() == 1 {
let &(name, kind) = bins.first().unwrap();
match kind {
&TargetKind::ExampleLib(..) => {
bail!(
"example target `{}` is a library and cannot be executed",
name
)
},
_ => { }
};
}
if bins.len() > 1 {
if !options.filter.is_specific() {
let names: Vec<&str> = bins.into_iter().map(|bin| bin.0).collect();
bail!(
"`cargo run` requires that a project only have one \
executable; use the `--bin` option to specify which one \
to run\navailable binaries: {}",
bins.join(", ")
to run\navailable binaries: {}",
names.join(", ")
)
} else {
bail!(
@ -86,4 +102,4 @@ pub fn run(
Ok(Some(err))
}
}
}
}

View File

@ -387,6 +387,38 @@ fn run_example() {
);
}
#[test]
fn run_library_example() {
let p = project("foo")
.file(
"Cargo.toml",
r#"
[package]
name = "foo"
version = "0.0.1"
authors = []
[[example]]
name = "bar"
crate_type = ["lib"]
"#,
)
.file("src/lib.rs", "")
.file(
"examples/bar.rs",
r#"
fn foo() {}
"#,
)
.build();
assert_that(
p.cargo("run").arg("--example").arg("bar"),
execs()
.with_status(101)
.with_stderr("[ERROR] example target `bar` is a library and cannot be executed"),
);
}
fn autodiscover_examples_project(rust_edition: &str, autoexamples: Option<bool>) -> Project {
let autoexamples = match autoexamples {
None => "".to_string(),