//! Launch commands very similarly to `Command`, but with `git` specific capabilities and adjustments. //! //! ## Examples //! //! ``` //! # fn main() -> Result<(), Box> { //! let output = gix_command::prepare("git") //! .arg("--version") //! .spawn()? //! .wait_with_output()?; //! //! assert!(output.status.success()); //! assert!(String::from_utf8(output.stdout)?.starts_with("git version ")); //! # Ok(()) } //! ``` #![deny(missing_docs)] #![forbid(unsafe_code)] use std::{ ffi::OsString, io::Read, path::{Path, PathBuf}, }; use bstr::{BString, ByteSlice}; /// A structure to keep settings to use when invoking a command via [`spawn()`][Prepare::spawn()], /// after creating it with [`prepare()`]. pub struct Prepare { /// The command to invoke, either directly or with a shell depending on `use_shell`. pub command: OsString, /// Additional information to be passed to the spawned command. pub context: Option, /// The way standard input is configured. pub stdin: std::process::Stdio, /// The way standard output is configured. pub stdout: std::process::Stdio, /// The way standard error is configured. pub stderr: std::process::Stdio, /// The arguments to pass to the process being spawned. pub args: Vec, /// Environment variables to set for the spawned process. pub env: Vec<(OsString, OsString)>, /// If `true`, we will use `shell_program` or `sh` to execute the `command`. pub use_shell: bool, /// If `true`, `command` is assumed to be a command or path to the program to execute, and it /// will be shell-quoted to assure it will be executed as is and without splitting across /// whitespace. pub quote_command: bool, /// The name or path to the shell program to use instead of `sh`. pub shell_program: Option, /// If `true` (default `true` on Windows and `false` everywhere else) we will see if it's safe /// to manually invoke `command` after splitting its arguments as a shell would do. /// /// Note that outside of Windows, it's generally not advisable as this removes support for /// literal shell scripts with shell-builtins. /// /// This mimics the behaviour we see with `git` on Windows, which also won't invoke the shell /// there at all. /// /// Only effective if `use_shell` is `true` as well, as the shell will be used as a fallback if /// it's not possible to split arguments as the command-line contains 'scripting'. pub allow_manual_arg_splitting: bool, } /// Additional information that is relevant to spawned processes, which typically receive /// a wealth of contextual information when spawned from `git`. /// /// See [the git source code](https://github.com/git/git/blob/cfb8a6e9a93adbe81efca66e6110c9b4d2e57169/git.c#L191) /// for details. #[derive(Debug, Default, Clone)] pub struct Context { /// The `.git` directory that contains the repository. /// /// If set, it will be used to set the `GIT_DIR` environment variable. pub git_dir: Option, /// Set the `GIT_WORK_TREE` environment variable with the given path. pub worktree_dir: Option, /// If `true`, set `GIT_NO_REPLACE_OBJECTS` to `1`, which turns off object replacements, or `0` otherwise. /// If `None`, the variable won't be set. pub no_replace_objects: Option, /// Set the `GIT_NAMESPACE` variable with the given value, effectively namespacing all /// operations on references. pub ref_namespace: Option, /// If `true`, set `GIT_LITERAL_PATHSPECS` to `1`, which makes globs literal and prefixes as well, or `0` otherwise. /// If `None`, the variable won't be set. pub literal_pathspecs: Option, /// If `true`, set `GIT_GLOB_PATHSPECS` to `1`, which lets wildcards not match the `/` character, and equals the `:(glob)` prefix. /// If `false`, set `GIT_NOGLOB_PATHSPECS` to `1` which lets globs match only themselves. /// If `None`, the variable won't be set. pub glob_pathspecs: Option, /// If `true`, set `GIT_ICASE_PATHSPECS` to `1`, to let patterns match case-insensitively, or `0` otherwise. /// If `None`, the variable won't be set. pub icase_pathspecs: Option, /// If `true`, inherit `stderr` just like it's the default when spawning processes. /// If `false`, suppress all stderr output. /// If not `None`, this will override any value set with [`Prepare::stderr()`]. pub stderr: Option, } mod prepare { use std::{ borrow::Cow, ffi::OsString, process::{Command, Stdio}, }; use bstr::ByteSlice; use crate::{Context, Prepare, extract_interpreter, win_path_lookup}; /// Builder impl Prepare { /// If called, the command will be checked for characters that are typical for shell /// scripts, and if found will use `sh` to execute it or whatever is set as /// [`with_shell_program()`](Self::with_shell_program()). /// /// If the command isn't valid UTF-8, a shell will always be used. /// /// If a shell is used, then arguments given here with [arg()](Self::arg) or /// [args()](Self::args) will be substituted via `"$@"` if it's not already present in the /// command. /// /// /// The [`command_may_be_shell_script_allow_manual_argument_splitting()`](Self::command_may_be_shell_script_allow_manual_argument_splitting()) /// and [`command_may_be_shell_script_disallow_manual_argument_splitting()`](Self::command_may_be_shell_script_disallow_manual_argument_splitting()) /// methods also call this method. /// /// If neither this method nor [`with_shell()`](Self::with_shell()) is called, commands are /// always executed verbatim and directly, without the use of a shell. pub fn command_may_be_shell_script(mut self) -> Self { self.use_shell = self .command .to_str() .is_none_or(|cmd| cmd.as_bytes().find_byteset(b"|&;<>()$`\\\"' \t\n*?[#~=%").is_some()); self } /// If called, unconditionally use a shell to execute the command and its arguments. /// /// This uses `sh` to execute it, or whatever is set as /// [`with_shell_program()`](Self::with_shell_program()). /// /// Arguments given here with [arg()](Self::arg) or [args()](Self::args) will be /// substituted via `"$@"` if it's not already present in the command. /// /// If neither this method nor /// [`command_may_be_shell_script()`](Self::command_may_be_shell_script()) is called, /// commands are always executed verbatim and directly, without the use of a shell. (But /// see [`command_may_be_shell_script()`](Self::command_may_be_shell_script()) on other /// methods that call that method.) /// /// We also disallow manual argument splitting /// (see [`command_may_be_shell_script_disallow_manual_argument_splitting`](Self::command_may_be_shell_script_disallow_manual_argument_splitting())) /// to assure a shell is indeed used, no matter what. pub fn with_shell(mut self) -> Self { self.use_shell = true; self.allow_manual_arg_splitting = false; self } /// Quote the command if it is run in a shell, so its path is left intact. /// /// This is only meaningful if the command has been arranged to run in a shell, either /// unconditionally with [`with_shell()`](Self::with_shell()), or conditionally with /// [`command_may_be_shell_script()`](Self::command_may_be_shell_script()). /// /// Note that this should not be used if the command is a script - quoting is only the /// right choice if it's known to be a program path. /// /// Note also that this does not affect arguments passed with [arg()](Self::arg) or /// [args()](Self::args), which do not have to be quoted by the *caller* because they are /// passed as `"$@"` positional parameters (`"$1"`, `"$2"`, and so on). pub fn with_quoted_command(mut self) -> Self { self.quote_command = true; self } /// Set the name or path to the shell `program` to use if a shell is to be used, to avoid /// using the default shell which is `sh`. /// /// Note that shells that are not Bourne-style cannot be expected to work correctly, /// because POSIX shell syntax is assumed when searching for and conditionally adding /// `"$@"` to receive arguments, where applicable (and in the behaviour of /// [`with_quoted_command()`](Self::with_quoted_command()), if called). pub fn with_shell_program(mut self, program: impl Into) -> Self { self.shell_program = Some(program.into()); self } /// Unconditionally turn off using the shell when spawning the command. /// /// Note that not using the shell is the default. So an effective use of this method /// is some time after [`command_may_be_shell_script()`](Self::command_may_be_shell_script()) /// or [`with_shell()`](Self::with_shell()) was called. pub fn without_shell(mut self) -> Self { self.use_shell = false; self } /// Set additional `ctx` to be used when spawning the process. /// /// Note that this is a must for most kind of commands that `git` usually spawns, as at /// least they need to know the correct Git repository to function. pub fn with_context(mut self, ctx: Context) -> Self { self.context = Some(ctx); self } /// Like [`command_may_be_shell_script()`](Self::command_may_be_shell_script()), but try to /// split arguments by hand if this can be safely done without a shell. /// /// This is useful on platforms where spawning processes is slow, or where many processes /// have to be spawned in a row which should be sped up. Manual argument splitting is /// enabled by default on Windows only. /// /// Note that this does *not* check for the use of possible shell builtins. Commands may /// fail or behave differently if they are available as shell builtins and no corresponding /// external command exists, or the external command behaves differently. pub fn command_may_be_shell_script_allow_manual_argument_splitting(mut self) -> Self { self.allow_manual_arg_splitting = true; self.command_may_be_shell_script() } /// Like [`command_may_be_shell_script()`](Self::command_may_be_shell_script()), but don't /// allow to bypass the shell even if manual argument splitting can be performed safely. pub fn command_may_be_shell_script_disallow_manual_argument_splitting(mut self) -> Self { self.allow_manual_arg_splitting = false; self.command_may_be_shell_script() } /// Configure the process to use `stdio` for _stdin_. pub fn stdin(mut self, stdio: Stdio) -> Self { self.stdin = stdio; self } /// Configure the process to use `stdio` for _stdout_. pub fn stdout(mut self, stdio: Stdio) -> Self { self.stdout = stdio; self } /// Configure the process to use `stdio` for _stderr_. pub fn stderr(mut self, stdio: Stdio) -> Self { self.stderr = stdio; self } /// Add `arg` to the list of arguments to call the command with. pub fn arg(mut self, arg: impl Into) -> Self { self.args.push(arg.into()); self } /// Add `args` to the list of arguments to call the command with. pub fn args(mut self, args: impl IntoIterator>) -> Self { self.args .append(&mut args.into_iter().map(Into::into).collect::>()); self } /// Add `key` with `value` to the environment of the spawned command. pub fn env(mut self, key: impl Into, value: impl Into) -> Self { self.env.push((key.into(), value.into())); self } } /// Finalization impl Prepare { /// Spawn the command as configured. pub fn spawn(self) -> std::io::Result { let mut cmd = Command::from(self); gix_trace::debug!(cmd = ?cmd); cmd.spawn() } } impl From for Command { fn from(mut prep: Prepare) -> Command { let mut cmd = if prep.use_shell { let split_args = prep .allow_manual_arg_splitting .then(|| { if gix_path::into_bstr(std::borrow::Cow::Borrowed(prep.command.as_ref())) .find_byteset(b"\\|&;<>()$`\n*?[#~%") .is_none() { prep.command.to_str().and_then(|args| { shell_words::split(args) .ok() .filter(|args| !args.is_empty()) .map(Vec::into_iter) }) } else { None } }) .flatten(); match split_args { Some(mut args) => { let mut cmd = Command::new(args.next().expect("non-empty input")); cmd.args(args); cmd } None => { let shell = prep.shell_program.unwrap_or_else(|| gix_path::env::shell().into()); // Passed as `command_name` after `-c