//! Shared helpers for xtask subcommands: locating the repository, running //! child processes and listing the files that belong to the repository. use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; /// Result type of every xtask step; the error is a message for the console. pub type TaskResult = Result; /// Returns the repository root, the parent of the `xtask` crate directory. /// /// # Errors /// Fails if the manifest directory has no parent, which only happens when the /// crate was moved out of the workspace. pub fn repo_root() -> TaskResult { Path::new(env!("CARGO_MANIFEST_DIR")) .parent() .map(Path::to_path_buf) .ok_or_else(|| "xtask is not inside the workspace".to_string()) } /// Resolves the name of a program for spawning. /// /// On Windows, Node-based tools such as `pnpm` are batch shims (`pnpm.cmd`) /// that `Command` does not find by their bare name. pub fn program(name: &str) -> String { if cfg!(windows) && matches!(name, "pnpm" | "npm" | "npx" | "composer") { format!("{name}.cmd") } else { name.to_string() } } /// Runs a program to completion with inherited stdio. /// /// # Errors /// Fails if the program cannot be started or exits unsuccessfully. pub fn run(dir: &Path, name: &str, args: &[&str]) -> TaskResult { let status = Command::new(program(name)) .args(args) .current_dir(dir) .status() .map_err(|e| format!("cannot start `{name}`: {e}"))?; if status.success() { Ok(()) } else { Err(format!("`{name} {}` failed ({status})", args.join(" "))) } } /// Runs a program and captures its standard output as UTF-8 text. /// /// Standard error is passed through to the console. /// /// # Errors /// Fails if the program cannot be started, exits unsuccessfully or prints /// output that is not UTF-8. pub fn capture(dir: &Path, name: &str, args: &[&str]) -> TaskResult { let output = Command::new(program(name)) .args(args) .current_dir(dir) .stderr(Stdio::inherit()) .output() .map_err(|e| format!("cannot start `{name}`: {e}"))?; if !output.status.success() { return Err(format!( "`{name} {}` failed ({})", args.join(" "), output.status )); } String::from_utf8(output.stdout).map_err(|e| format!("`{name}` printed non-UTF-8 output: {e}")) } /// Lists the repository files that are tracked or would be added by /// `git add -A` (untracked but not ignored), as paths relative to the root /// with forward slashes. /// /// # Errors /// Fails if `git` is not available or the root is not a Git repository. pub fn repo_files(root: &Path) -> TaskResult> { let out = capture( root, "git", &[ "ls-files", "--cached", "--others", "--exclude-standard", "-z", ], )?; let mut files: Vec = out .split('\0') .filter(|f| !f.is_empty()) .filter(|f| root.join(f).is_file()) .map(str::to_string) .collect(); files.sort(); files.dedup(); Ok(files) }