mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-29 17:55:45 +01:00
craft-xtask: fix the Windows lock test, close piped stdin, ignore stderr write failures
The test for a held workspace lock gave the second run a different first lock directory. On Windows the shared lock is workspace.lock in that first directory, so the set ran and the test failed. On Windows the run now shares the first directory and differs only in the later ones. run_cancelable closes a piped stdin after starting the child, as Command::status does for run, so a child that reads stdin to the end can exit. Diagnostics in runner.rs and lock.rs are written with a fallible write, so a closed stderr no longer panics before a command starts.
This commit is contained in:
1 parent
50aabe2c5a
commit
cf0f8cc77d
4 files changed
+87
-10
No files matched your search
@@ -46,6 +46,13 @@ pub mod runner;
|
||||
#[cfg(feature = "version")]
|
||||
pub mod version;
|
||||
|
||||
/// Writes one diagnostic line to stderr. A failed write, such as one to a closed pipe, is ignored, so a
|
||||
/// diagnostic never stops a run.
|
||||
pub(crate) fn note(line: std::fmt::Arguments<'_>) {
|
||||
use std::io::Write;
|
||||
let _ = writeln!(std::io::stderr(), "{line}");
|
||||
}
|
||||
|
||||
/// Keeps the tests that start child processes apart from the tests that check whether a slot is free.
|
||||
/// A child holds copies of the parent's open files, and so its file locks, until it starts its program.
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -112,7 +112,7 @@ fn record_owner(lock: &Path, label: &str) -> PathBuf {
|
||||
if let (Err(e), Err(w)) = (&removed, &written)
|
||||
&& e.kind() != std::io::ErrorKind::NotFound
|
||||
{
|
||||
eprintln!("lock: could not record the owner in {} ({e}; {w}): waiting runs may show a stale owner", owner_file.display());
|
||||
crate::note(format_args!("lock: could not record the owner in {} ({e}; {w}): waiting runs may show a stale owner", owner_file.display()));
|
||||
}
|
||||
owner_file
|
||||
}
|
||||
@@ -152,9 +152,9 @@ fn read_owner(path: &Path) -> Option<String> {
|
||||
/// before any wait.
|
||||
pub fn acquire(config: &LockConfig, cancel: Option<&Cancel>) -> Result<Held, Error> {
|
||||
acquire_with(config, cancel, || {
|
||||
eprintln!("=== lock: waiting for another run to finish ({} at a time) ===", config.slots);
|
||||
crate::note(format_args!("=== lock: waiting for another run to finish ({} at a time) ===", config.slots));
|
||||
for h in holders(config).unwrap_or_default() {
|
||||
eprintln!(" running: {h}");
|
||||
crate::note(format_args!(" running: {h}"));
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -170,7 +170,7 @@ fn acquire_with(config: &LockConfig, cancel: Option<&Cancel>, on_wait: impl FnOn
|
||||
return Err(Error::Canceled { step: None });
|
||||
}
|
||||
if let Some(held) = try_acquire(config)? {
|
||||
eprintln!("=== lock: waited {:.0} s for a slot ===", waiting.elapsed().as_secs_f64());
|
||||
crate::note(format_args!("=== lock: waited {:.0} s for a slot ===", waiting.elapsed().as_secs_f64()));
|
||||
return Ok(held);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -394,7 +394,7 @@ pub fn cargo(root: &Path) -> Command {
|
||||
///
|
||||
/// Returns an error when the command cannot be started or exits with a failure status.
|
||||
pub fn run(mut cmd: Command, label: &str) -> Result<(), String> {
|
||||
eprintln!("$ {label}");
|
||||
crate::note(format_args!("$ {label}"));
|
||||
let status = cmd.status().map_err(|e| spawn_error(label, &e))?;
|
||||
exit_result(label, status)
|
||||
}
|
||||
@@ -407,10 +407,10 @@ pub fn run(mut cmd: Command, label: &str) -> Result<(), String> {
|
||||
/// `kill -s KILL`. On Windows it ends the process tree with `taskkill /T /F`. When that tool cannot
|
||||
/// be run, only the child itself is ended.
|
||||
pub fn run_cancelable(mut cmd: Command, label: &str, cancel: &Cancel) -> Result<(), String> {
|
||||
eprintln!("$ {label}");
|
||||
crate::note(format_args!("$ {label}"));
|
||||
#[cfg(unix)]
|
||||
std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
|
||||
let mut child = cmd.spawn().map_err(|e| spawn_error(label, &e))?;
|
||||
let mut child = spawn(&mut cmd, label)?;
|
||||
loop {
|
||||
if let Some(status) = child.try_wait().map_err(|e| format!("{label}: {e}"))? {
|
||||
return exit_result(label, status);
|
||||
@@ -444,6 +444,14 @@ fn end_tree(child: &mut Child) -> io::Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts `cmd` and closes its stdin when the caller piped it, as `Command::status` does in [`run`], so
|
||||
/// a child that reads stdin to the end can exit.
|
||||
fn spawn(cmd: &mut Command, label: &str) -> Result<Child, String> {
|
||||
let mut child = cmd.spawn().map_err(|e| spawn_error(label, &e))?;
|
||||
drop(child.stdin.take());
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
fn spawn_error(label: &str, e: &io::Error) -> String {
|
||||
format!("{label}: failed to spawn: {e}")
|
||||
}
|
||||
@@ -486,7 +494,7 @@ fn select_test(
|
||||
TestMode::PreferNextest => {
|
||||
let found = probe();
|
||||
if !found {
|
||||
eprintln!("note: cargo-nextest is not installed, running cargo test (cargo install cargo-nextest --locked)");
|
||||
crate::note(format_args!("note: cargo-nextest is not installed, running cargo test (cargo install cargo-nextest --locked)"));
|
||||
}
|
||||
found
|
||||
}
|
||||
@@ -744,6 +752,8 @@ mod tests {
|
||||
const TREE_CHILD: &str = "CRAFT_XTASK_TREE_CHILD";
|
||||
const BLOCKED_CHILD: &str = "CRAFT_XTASK_BLOCKED_CHILD";
|
||||
const BYTES_CHILD: &str = "CRAFT_XTASK_BYTES_CHILD";
|
||||
const STDIN_CHILD: &str = "CRAFT_XTASK_STDIN_CHILD";
|
||||
const CLOSED_STDERR_CHILD: &str = "CRAFT_XTASK_CLOSED_STDERR_CHILD";
|
||||
const RAW_BYTES: &[u8] = b"\xff\xfe\x00 not UTF-8 \x80\xc3\n";
|
||||
|
||||
/// This test binary, run as a child that runs only the ignored test `name`.
|
||||
@@ -785,6 +795,61 @@ mod tests {
|
||||
io::Read::read_to_end(&mut lines, &mut Vec::new()).expect("pipe end");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spawn_closes_a_piped_stdin() {
|
||||
let _guard = crate::spawn_guard();
|
||||
let mut cmd = test_child("runner::tests::stdin_child", STDIN_CHILD);
|
||||
cmd.stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null());
|
||||
// The child reads stdin to the end, so it exits only once the pipe is closed. A failed check
|
||||
// drops the child's stdin with it, so the child still exits.
|
||||
let mut child = spawn(&mut cmd, "stdin").expect("child");
|
||||
assert!(child.stdin.is_none(), "the child's stdin is still open");
|
||||
assert!(child.wait().expect("child").success());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnostics_to_a_closed_stderr_do_not_panic() {
|
||||
let _guard = crate::spawn_guard();
|
||||
let (reader, writer) = io::pipe().expect("pipe");
|
||||
drop(reader);
|
||||
let mut child = test_child("runner::tests::closed_stderr_child", CLOSED_STDERR_CHILD);
|
||||
child.stdout(Stdio::null()).stderr(writer);
|
||||
let status = child.status().expect("child");
|
||||
assert!(status.success(), "the child failed with a closed stderr: {status}");
|
||||
}
|
||||
|
||||
/// Reads stdin to the end; run by `spawn_closes_a_piped_stdin`.
|
||||
#[test]
|
||||
#[ignore = "child process of spawn_closes_a_piped_stdin"]
|
||||
fn stdin_child() {
|
||||
if std::env::var_os(STDIN_CHILD).is_some() {
|
||||
io::Read::read_to_end(&mut io::stdin(), &mut Vec::new()).expect("stdin");
|
||||
}
|
||||
}
|
||||
|
||||
/// Prints every diagnostic to a stderr whose reading end is closed; run by
|
||||
/// `diagnostics_to_a_closed_stderr_do_not_panic`.
|
||||
#[test]
|
||||
#[ignore = "child process of diagnostics_to_a_closed_stderr_do_not_panic"]
|
||||
fn closed_stderr_child() {
|
||||
if std::env::var_os(CLOSED_STDERR_CHILD).is_none() {
|
||||
return;
|
||||
}
|
||||
let missing = "craft-xtask-test-no-such-program";
|
||||
assert!(run(Command::new(missing), "missing").is_err_and(|e| e.contains("failed to spawn")));
|
||||
assert!(run_cancelable(Command::new(missing), "missing", &Cancel::new()).is_err_and(|e| e.contains("failed to spawn")));
|
||||
assert!(select_test(cargo(Path::new(".")), "xtask", TestMode::PreferNextest, &["--lib"], || false).is_ok());
|
||||
#[cfg(feature = "lock")]
|
||||
{
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
let config = crate::lock::LockConfig::new(dir.path(), 1, "holder");
|
||||
let _held = crate::lock::try_acquire(&config).expect("lock").expect("free slot");
|
||||
let cancel = Cancel::new();
|
||||
cancel.cancel();
|
||||
assert_eq!(crate::lock::acquire(&config, Some(&cancel)).err(), Some(Error::Canceled { step: None }));
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts a blocked child of its own, says `ready`, and blocks; run by `run_cancelable_ends_the_process_tree`.
|
||||
#[test]
|
||||
#[ignore = "child process of run_cancelable_ends_the_process_tree"]
|
||||
|
||||
@@ -1029,10 +1029,15 @@ mod tests {
|
||||
let _guard = crate::spawn_guard();
|
||||
let dir = workspace(MANIFEST, Some("old lock\n"));
|
||||
let other = base_lock(dir.path(), &test_lock_dir(dir.path())).unwrap().expect("free lock");
|
||||
// A run whose owner-labeled lock directories differ from the holder's still meets its lock.
|
||||
// A run whose owner-labeled lock directories differ from the holder's still meets its lock. On
|
||||
// Windows that lock is `workspace.lock` in the first directory, so only the later ones differ.
|
||||
let elsewhere = tempfile::tempdir().unwrap();
|
||||
#[cfg(windows)]
|
||||
let dirs = [test_lock_dir(dir.path()), elsewhere.path().join("lock")];
|
||||
#[cfg(not(windows))]
|
||||
let dirs = [elsewhere.path().join("lock")];
|
||||
let ran = Cell::new(false);
|
||||
let result = run_to(dir.path(), &["set", "2.0.0"], &Limits::default(), Some(&[elsewhere.path().join("lock")]), &mut Vec::new(), || {
|
||||
let result = run_to(dir.path(), &["set", "2.0.0"], &Limits::default(), Some(&dirs), &mut Vec::new(), || {
|
||||
ran.set(true);
|
||||
Ok(())
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user