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

Allow doctest to refer to external crates (in context of a Cargo project) #19

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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: 21 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,7 @@ sha2 = "0.10.6"
base64-url = "1.4.13"
glob = "0.3.0"
fs_extra = "1.3.0"

# Needed to satisfy error-chain
[lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(has_error_description_deprecated)'] }
47 changes: 37 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,33 +132,42 @@ impl KeeperConfig {
build_dir
});

let manifest_dir = keeper_config.manifest_dir.map(PathBuf::from);
let is_workspace = keeper_config.is_workspace.unwrap_or(false);

let target_dir = keeper_config
.target_dir
.map(PathBuf::from)
.unwrap_or_else(|| {
let mut target_dir = test_dir.clone();
target_dir.push("target");
target_dir
if let Some(mf_dir) = manifest_dir.clone() {
let mut target_dir = mf_dir; // target is ./target/debug if in a Cargo project
target_dir.push("target/debug");
target_dir
} else {
let mut target_dir = test_dir.clone();
target_dir.push("target"); // target is just ./target if not in a Cargo project -- ugh!
target_dir
}
});

let manifest_dir = keeper_config.manifest_dir.map(PathBuf::from);
let is_workspace = keeper_config.is_workspace.unwrap_or(false);

let terminal_colors = keeper_config
.terminal_colors
.unwrap_or_else(|| atty::is(Stream::Stderr));

set_override(terminal_colors);

KeeperConfig {
let config = KeeperConfig {
test_dir,
target_dir,
manifest_dir,
is_workspace,
build_features: keeper_config.build_features,
terminal_colors,
externs: keeper_config.externs,
}
};
//todo future verbose option? eprintln!("... config: {:?}", &config);

config
}

fn setup_environment(&self) {
Expand Down Expand Up @@ -205,8 +214,7 @@ fn get_test_path(test: &Test, test_dir: &Path) -> PathBuf {
fn write_test_to_path(test: &Test, path: &Path) -> Result<(), std::io::Error> {
let mut output = File::create(path)?;
let test_text = create_test_input(&test.text);
write!(output, "{}", test_text)?;

write!(output, "// test name {}\n{}", test.name, test_text)?;
Ok(())
}

Expand Down Expand Up @@ -329,6 +337,7 @@ fn clean_file(test_results: &HashMap<Test, TestResult>, path: &Path) -> Option<(
None => true,
};

//todo future option to retain failing source files (maybe move to the side?)
if should_remove {
std::fs::remove_file(path).expect("Should be able to delete cache-file");
}
Expand Down Expand Up @@ -397,3 +406,21 @@ impl Preprocessor for BookKeeper {
renderer != "not-supported"
}
}

#[allow(unused)]
// invoke VSCode debugger
// Works for CodeLLDB running in VS Code. YMMV
fn attach_debugger() {
let url = format!(
"vscode://vadimcn.vscode-lldb/launch/config?{{'request':'attach','pid':{}}}",
std::process::id()
);

let output = std::process::Command::new("code")
.arg("--open-url")
.arg(url)
.output()
.unwrap();
std::thread::sleep(std::time::Duration::from_millis(1000)); // Wait for debugger to attach
eprintln!("... Debugger attached: status: {:?}", output.status);
}
92 changes: 87 additions & 5 deletions src/run_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ pub fn handle_test(
cargo_toml_path.push("Cargo.toml");

let mut deps_dir = PathBuf::from(target_dir);
deps_dir.push("debug/deps");
deps_dir.push("deps");

// Find the edition

Expand Down Expand Up @@ -141,6 +141,7 @@ pub fn handle_test(
)),
};

//todo future verbose option? eprintln!("... compiling via {:?}", &cmd);
let command_result = cmd.output().unwrap();
return if !command_result.status.success() {
TestResult::CompileFailed(command_result)
Expand Down Expand Up @@ -243,12 +244,61 @@ impl LockedDeps {
impl Iterator for LockedDeps {
type Item = (String, String);

// hack alert -- handle workspace version inheritance
// (I think that's what it is...)
// if you declare the *version* of a crate in the workspace Cargo.toml
// ```
// (<crateRoot>/Cargo.toml)
// [workspace]
// [workspace.package]
// version = <version>
// ```
// and then declare a package in that workspace that inherits version
// from the workspace, like
// with syntax in package like:
// ```
// (<workspaceRoot>/<package>/Cargo.toml)
// [package]
// name = <package>
// version = {workspace = true}
// ```
// then the metadata for the package id is "malformed" in the metadata.
// It looks like:
// ```
// "name": "leptos",
// "version": "0.7.0",
// "id": "path+file:///home/bobhy/src/localdep/leptos/leptos#0.7.0",
// ```
// rather than the expected:
// ```
// "name": "leptos_router",
// "version": "0.7.0",
// "id": "path+file:///home/bobhy/src/localdep/leptos/router#[email protected]",
// ```
// I found I had to resort to extraordinary hacks to
// determine the actual package name. For this case,
// I assume the package is the tail of the source path.
// Wiser heads in Cargo land may be able to explain this.
//
fn next(&mut self) -> Option<(String, String)> {
let dep = self.dependencies.pop()?;
let mut parts = dep.split_whitespace();
let name = parts.next()?;
let val = parts.next()?;
Some((name.replace('-', "_"), val.to_owned()))
if let Some((rest, version)) = dep.rsplit_once('@') {
if let Some((_source, libname)) = rest.rsplit_once('#') {
Some((libname.replace('-', "_"), version.to_owned()))
} else {
Some(("unknown_lib".to_owned(), version.to_owned()))
}
} else {
if let Some((source, version)) = dep.rsplit_once('#') {
if let Some((_base, libname)) = source.rsplit_once('/') {
Some((libname.replace('-', "_"), version.to_owned()))
} else {
Some(("unknown_lib".to_owned(), version.to_owned()))
}
} else {
Some(("unknown_lib".into(), "unknown_ver".into()))
}
}
}
}

Expand Down Expand Up @@ -338,3 +388,35 @@ fn edition_str(edition: &Edition) -> Option<&'static str> {
_ => return None,
})
}

#[cfg(test)]
mod test {
use super::*;
#[test]

fn verify_locked_deps_iterator() {
let test_exp = [
(
"path+file:///home/bobhy/src/localdep/leptos/leptos#0.7.0",
("leptos", "0.7.0"),
),
(
"path+file:///home/bobhy/src/localdep/leptos/router#[email protected]",
("leptos_router", "0.7.0"),
),
];
// note that LockedDeps::IntoIterator yields elements in reverse order,
// that needs to be accounted for in this test.
let ld = LockedDeps {
dependencies: test_exp
.iter()
.map(|(inp, _)| inp.to_string())
.rev()
.collect(),
};

let iterated: Vec<_> = ld.collect();
let exp = test_exp.map(|(_, (l, v))| (l.to_string(), v.to_string()));
assert_eq!(iterated, exp, "actual vs expected");
}
}