Skip to content

Commit 8ff53f6

Browse files
committed
Auto merge of #8954 - Swatinem:doctest-in-workspace, r=alexcrichton
Run rustdoc doctests relative to the workspace By doing so, rustdoc will also emit workspace-relative filenames for the doctests. fixes #8097
2 parents 453dbf8 + e729880 commit 8ff53f6

File tree

10 files changed

+127
-53
lines changed

10 files changed

+127
-53
lines changed

src/cargo/core/compiler/fingerprint.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -334,7 +334,7 @@ use crate::util;
334334
use crate::util::errors::{CargoResult, CargoResultExt};
335335
use crate::util::interning::InternedString;
336336
use crate::util::paths;
337-
use crate::util::{internal, profile, ProcessBuilder};
337+
use crate::util::{internal, path_args, profile, ProcessBuilder};
338338

339339
use super::custom_build::BuildDeps;
340340
use super::job::{Job, Work};
@@ -1313,7 +1313,7 @@ fn calculate_normal(cx: &mut Context<'_, '_>, unit: &Unit) -> CargoResult<Finger
13131313
profile: profile_hash,
13141314
// Note that .0 is hashed here, not .1 which is the cwd. That doesn't
13151315
// actually affect the output artifact so there's no need to hash it.
1316-
path: util::hash_u64(super::path_args(cx.bcx, unit).0),
1316+
path: util::hash_u64(path_args(cx.bcx.ws, unit).0),
13171317
features: format!("{:?}", unit.features),
13181318
deps,
13191319
local: Mutex::new(local),

src/cargo/core/compiler/mod.rs

Lines changed: 3 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ use crate::util::errors::{self, CargoResult, CargoResultExt, ProcessError, Verbo
5555
use crate::util::interning::InternedString;
5656
use crate::util::machine_message::Message;
5757
use crate::util::{self, machine_message, ProcessBuilder};
58-
use crate::util::{internal, join_paths, paths, profile};
58+
use crate::util::{add_path_args, internal, join_paths, paths, profile};
5959

6060
const RUSTDOC_CRATE_VERSION_FLAG: &str = "--crate-version";
6161

@@ -583,7 +583,7 @@ fn rustdoc(cx: &mut Context<'_, '_>, unit: &Unit) -> CargoResult<Work> {
583583
let mut rustdoc = cx.compilation.rustdoc_process(unit)?;
584584
rustdoc.inherit_jobserver(&cx.jobserver);
585585
rustdoc.arg("--crate-name").arg(&unit.target.crate_name());
586-
add_path_args(bcx, unit, &mut rustdoc);
586+
add_path_args(bcx.ws, unit, &mut rustdoc);
587587
add_cap_lints(bcx, unit, &mut rustdoc);
588588

589589
if let CompileKind::Target(target) = unit.kind {
@@ -669,41 +669,6 @@ fn append_crate_version_flag(unit: &Unit, rustdoc: &mut ProcessBuilder) {
669669
.arg(unit.pkg.version().to_string());
670670
}
671671

672-
// The path that we pass to rustc is actually fairly important because it will
673-
// show up in error messages (important for readability), debug information
674-
// (important for caching), etc. As a result we need to be pretty careful how we
675-
// actually invoke rustc.
676-
//
677-
// In general users don't expect `cargo build` to cause rebuilds if you change
678-
// directories. That could be if you just change directories in the package or
679-
// if you literally move the whole package wholesale to a new directory. As a
680-
// result we mostly don't factor in `cwd` to this calculation. Instead we try to
681-
// track the workspace as much as possible and we update the current directory
682-
// of rustc/rustdoc where appropriate.
683-
//
684-
// The first returned value here is the argument to pass to rustc, and the
685-
// second is the cwd that rustc should operate in.
686-
fn path_args(bcx: &BuildContext<'_, '_>, unit: &Unit) -> (PathBuf, PathBuf) {
687-
let ws_root = bcx.ws.root();
688-
let src = match unit.target.src_path() {
689-
TargetSourcePath::Path(path) => path.to_path_buf(),
690-
TargetSourcePath::Metabuild => unit.pkg.manifest().metabuild_path(bcx.ws.target_dir()),
691-
};
692-
assert!(src.is_absolute());
693-
if unit.pkg.package_id().source_id().is_path() {
694-
if let Ok(path) = src.strip_prefix(ws_root) {
695-
return (path.to_path_buf(), ws_root.to_path_buf());
696-
}
697-
}
698-
(src, unit.pkg.root().to_path_buf())
699-
}
700-
701-
fn add_path_args(bcx: &BuildContext<'_, '_>, unit: &Unit, cmd: &mut ProcessBuilder) {
702-
let (arg, cwd) = path_args(bcx, unit);
703-
cmd.arg(arg);
704-
cmd.cwd(cwd);
705-
}
706-
707672
fn add_cap_lints(bcx: &BuildContext<'_, '_>, unit: &Unit, cmd: &mut ProcessBuilder) {
708673
// If this is an upstream dep we don't want warnings from, turn off all
709674
// lints.
@@ -798,7 +763,7 @@ fn build_base_args(
798763
cmd.arg(format!("--edition={}", edition));
799764
}
800765

801-
add_path_args(bcx, unit, cmd);
766+
add_path_args(bcx.ws, unit, cmd);
802767
add_error_format_and_color(cx, cmd, cx.rmeta_required(unit))?;
803768

804769
if !test {

src/cargo/ops/cargo_test.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use crate::core::shell::Verbosity;
55
use crate::core::Workspace;
66
use crate::ops;
77
use crate::util::errors::CargoResult;
8-
use crate::util::{CargoTestError, Config, ProcessError, Test};
8+
use crate::util::{add_path_args, CargoTestError, Config, ProcessError, Test};
99

1010
pub struct TestOptions {
1111
pub compile_opts: ops::CompileOptions,
@@ -30,7 +30,7 @@ pub fn run_tests(
3030
return Ok(Some(CargoTestError::new(test, errors)));
3131
}
3232

33-
let (doctest, docerrors) = run_doc_tests(ws.config(), options, test_args, &compilation)?;
33+
let (doctest, docerrors) = run_doc_tests(ws, options, test_args, &compilation)?;
3434
let test = if docerrors.is_empty() { test } else { doctest };
3535
errors.extend(docerrors);
3636
if errors.is_empty() {
@@ -131,11 +131,12 @@ fn run_unit_tests(
131131
}
132132

133133
fn run_doc_tests(
134-
config: &Config,
134+
ws: &Workspace<'_>,
135135
options: &TestOptions,
136136
test_args: &[&str],
137137
compilation: &Compilation<'_>,
138138
) -> CargoResult<(Test, Vec<ProcessError>)> {
139+
let config = ws.config();
139140
let mut errors = Vec::new();
140141
let doctest_xcompile = config.cli_unstable().doctest_xcompile;
141142

@@ -161,10 +162,9 @@ fn run_doc_tests(
161162

162163
config.shell().status("Doc-tests", unit.target.name())?;
163164
let mut p = compilation.rustdoc_process(unit)?;
164-
p.arg("--test")
165-
.arg(unit.target.src_path().path().unwrap())
166-
.arg("--crate-name")
167-
.arg(&unit.target.crate_name());
165+
p.arg("--crate-name").arg(&unit.target.crate_name());
166+
p.arg("--test");
167+
add_path_args(ws, unit, &mut p);
168168

169169
if doctest_xcompile {
170170
if let CompileKind::Target(target) = unit.kind {

src/cargo/util/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@ pub use self::sha256::Sha256;
2727
pub use self::to_semver::ToSemver;
2828
pub use self::vcs::{existing_vcs_repo, FossilRepo, GitRepo, HgRepo, PijulRepo};
2929
pub use self::workspace::{
30-
print_available_benches, print_available_binaries, print_available_examples,
31-
print_available_packages, print_available_tests,
30+
add_path_args, path_args, print_available_benches, print_available_binaries,
31+
print_available_examples, print_available_packages, print_available_tests,
3232
};
3333

3434
mod canonical_url;

src/cargo/util/workspace.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
1+
use super::ProcessBuilder;
2+
use crate::core::compiler::Unit;
3+
use crate::core::manifest::TargetSourcePath;
14
use crate::core::{Target, Workspace};
25
use crate::ops::CompileOptions;
36
use crate::util::CargoResult;
47
use anyhow::bail;
58
use std::fmt::Write;
9+
use std::path::PathBuf;
610

711
fn get_available_targets<'a>(
812
filter_fn: fn(&Target) -> bool,
@@ -89,3 +93,38 @@ pub fn print_available_benches(ws: &Workspace<'_>, options: &CompileOptions) ->
8993
pub fn print_available_tests(ws: &Workspace<'_>, options: &CompileOptions) -> CargoResult<()> {
9094
print_available_targets(Target::is_test, ws, options, "--test", "tests")
9195
}
96+
97+
/// The path that we pass to rustc is actually fairly important because it will
98+
/// show up in error messages (important for readability), debug information
99+
/// (important for caching), etc. As a result we need to be pretty careful how we
100+
/// actually invoke rustc.
101+
///
102+
/// In general users don't expect `cargo build` to cause rebuilds if you change
103+
/// directories. That could be if you just change directories in the package or
104+
/// if you literally move the whole package wholesale to a new directory. As a
105+
/// result we mostly don't factor in `cwd` to this calculation. Instead we try to
106+
/// track the workspace as much as possible and we update the current directory
107+
/// of rustc/rustdoc where appropriate.
108+
///
109+
/// The first returned value here is the argument to pass to rustc, and the
110+
/// second is the cwd that rustc should operate in.
111+
pub fn path_args(ws: &Workspace<'_>, unit: &Unit) -> (PathBuf, PathBuf) {
112+
let ws_root = ws.root();
113+
let src = match unit.target.src_path() {
114+
TargetSourcePath::Path(path) => path.to_path_buf(),
115+
TargetSourcePath::Metabuild => unit.pkg.manifest().metabuild_path(ws.target_dir()),
116+
};
117+
assert!(src.is_absolute());
118+
if unit.pkg.package_id().source_id().is_path() {
119+
if let Ok(path) = src.strip_prefix(ws_root) {
120+
return (path.to_path_buf(), ws_root.to_path_buf());
121+
}
122+
}
123+
(src, unit.pkg.root().to_path_buf())
124+
}
125+
126+
pub fn add_path_args(ws: &Workspace<'_>, unit: &Unit, cmd: &mut ProcessBuilder) {
127+
let (arg, cwd) = path_args(ws, unit);
128+
cmd.arg(arg);
129+
cmd.cwd(cwd);
130+
}

tests/testsuite/build_script.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2753,7 +2753,7 @@ fn doctest_receives_build_link_args() {
27532753

27542754
p.cargo("test -v")
27552755
.with_stderr_contains(
2756-
"[RUNNING] `rustdoc [..]--test [..] --crate-name foo [..]-L native=bar[..]`",
2756+
"[RUNNING] `rustdoc [..]--crate-name foo --test [..]-L native=bar[..]`",
27572757
)
27582758
.run();
27592759
}

tests/testsuite/cross_compile.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1109,7 +1109,7 @@ fn doctest_xcompile_linker() {
11091109
.masquerade_as_nightly_cargo()
11101110
.with_stderr_contains(&format!(
11111111
"\
1112-
[RUNNING] `rustdoc --crate-type lib --test [..]\
1112+
[RUNNING] `rustdoc --crate-type lib --crate-name foo --test [..]\
11131113
--target {target} [..] -C linker=my-linker-tool[..]
11141114
",
11151115
target = target,

tests/testsuite/doc.rs

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1638,3 +1638,73 @@ fn crate_versions_flag_is_overridden() {
16381638
p.cargo("rustdoc -- --crate-version 2.0.3").run();
16391639
asserts(output_documentation());
16401640
}
1641+
1642+
#[cargo_test]
1643+
fn doc_test_in_workspace() {
1644+
let p = project()
1645+
.file(
1646+
"Cargo.toml",
1647+
r#"
1648+
[workspace]
1649+
members = [
1650+
"crate-a",
1651+
"crate-b",
1652+
]
1653+
"#,
1654+
)
1655+
.file(
1656+
"crate-a/Cargo.toml",
1657+
r#"
1658+
[project]
1659+
name = "crate-a"
1660+
version = "0.1.0"
1661+
"#,
1662+
)
1663+
.file(
1664+
"crate-a/src/lib.rs",
1665+
"\
1666+
//! ```
1667+
//! assert_eq!(1, 1);
1668+
//! ```
1669+
",
1670+
)
1671+
.file(
1672+
"crate-b/Cargo.toml",
1673+
r#"
1674+
[project]
1675+
name = "crate-b"
1676+
version = "0.1.0"
1677+
"#,
1678+
)
1679+
.file(
1680+
"crate-b/src/lib.rs",
1681+
"\
1682+
//! ```
1683+
//! assert_eq!(1, 1);
1684+
//! ```
1685+
",
1686+
)
1687+
.build();
1688+
p.cargo("test --doc -vv")
1689+
.with_stderr_contains("[DOCTEST] crate-a")
1690+
.with_stdout_contains(
1691+
"
1692+
running 1 test
1693+
test crate-a/src/lib.rs - (line 1) ... ok
1694+
1695+
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out[..]
1696+
1697+
",
1698+
)
1699+
.with_stderr_contains("[DOCTEST] crate-b")
1700+
.with_stdout_contains(
1701+
"
1702+
running 1 test
1703+
test crate-b/src/lib.rs - (line 1) ... ok
1704+
1705+
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out[..]
1706+
1707+
",
1708+
)
1709+
.run();
1710+
}

tests/testsuite/lto.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -526,7 +526,7 @@ fn cdylib_and_rlib() {
526526
[RUNNING] [..]target/release/deps/bar-[..]
527527
[RUNNING] [..]target/release/deps/b-[..]
528528
[DOCTEST] bar
529-
[RUNNING] `rustdoc --crate-type cdylib --crate-type rlib --test [..]-C embed-bitcode=no[..]
529+
[RUNNING] `rustdoc --crate-type cdylib --crate-type rlib --crate-name bar --test [..]-C embed-bitcode=no[..]
530530
",
531531
)
532532
.run();

tests/testsuite/rename_deps.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,7 @@ fn can_run_doc_tests() {
265265
.with_stderr_contains(
266266
"\
267267
[DOCTEST] foo
268-
[RUNNING] `rustdoc [..]--test [CWD]/src/lib.rs \
268+
[RUNNING] `rustdoc [..]--test src/lib.rs \
269269
[..] \
270270
--extern bar=[CWD]/target/debug/deps/libbar-[..].rlib \
271271
--extern baz=[CWD]/target/debug/deps/libbar-[..].rlib \

0 commit comments

Comments
 (0)