gix_command/lib.rs
1//! Launch commands very similarly to `Command`, but with `git` specific capabilities and adjustments.
2//!
3//! ## Examples
4//!
5//! ```
6//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
7//! let output = gix_command::prepare("git")
8//! .arg("--version")
9//! .spawn()?
10//! .wait_with_output()?;
11//!
12//! assert!(output.status.success());
13//! assert!(String::from_utf8(output.stdout)?.starts_with("git version "));
14//! # Ok(()) }
15//! ```
16#![deny(missing_docs)]
17#![forbid(unsafe_code)]
18
19use std::{
20 ffi::{OsStr, OsString},
21 io::Read,
22 path::{Path, PathBuf},
23};
24
25use bstr::{BString, ByteSlice};
26
27///
28pub mod parse;
29
30mod prepare;
31
32///
33pub mod shebang {
34 use std::{ffi::OsString, path::PathBuf};
35
36 use bstr::{BStr, ByteSlice};
37
38 /// Parse `buf` to extract all shebang information.
39 pub fn parse(buf: &BStr) -> Option<Data> {
40 let mut line = buf.lines().next()?;
41 line = line.strip_prefix(b"#!")?;
42
43 let slash_idx = line.rfind_byteset(br"/\")?;
44 let space_idx = line[slash_idx..]
45 .find_byte(b' ')
46 .map_or(line.len(), |space_idx| slash_idx + space_idx);
47 let (interpreter, args) = line.split_at(space_idx);
48 Some(Data {
49 interpreter: gix_path::try_from_byte_slice(interpreter.trim()).ok()?.to_owned(),
50 args: crate::parse::arguments(args.trim().as_bstr()).unwrap_or_default(),
51 })
52 }
53
54 /// Shebang information as [parsed](parse()) from a buffer that should contain at least one line.
55 #[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
56 pub struct Data {
57 /// The interpreter to run.
58 pub interpreter: PathBuf,
59 /// Arguments following the interpreter, split like [`crate::parse::command_line()`], or empty if malformed.
60 pub args: Vec<OsString>,
61 }
62}
63
64/// A structure to keep settings to use when invoking a command via [`spawn()`][Prepare::spawn()],
65/// after creating it with [`prepare()`].
66pub struct Prepare {
67 /// The command to invoke, either directly or with a shell depending on `use_shell`.
68 pub command: OsString,
69 /// Additional information to be passed to the spawned command.
70 pub context: Option<Context>,
71 /// The way standard input is configured.
72 pub stdin: std::process::Stdio,
73 /// The way standard output is configured.
74 pub stdout: std::process::Stdio,
75 /// The way standard error is configured.
76 pub stderr: std::process::Stdio,
77 /// The arguments to pass to the process being spawned.
78 pub args: Vec<OsString>,
79 /// Environment variables to set for the spawned process.
80 pub env: Vec<(OsString, OsString)>,
81 /// If `true`, we will use `shell_program` or `sh` to execute the `command`.
82 pub use_shell: bool,
83 /// If `true`, `command` is assumed to be a command or path to the program to execute, and it
84 /// will be shell-quoted to assure it will be executed as is and without splitting across
85 /// whitespace.
86 pub quote_command: bool,
87 /// The name or path to the shell program to use instead of `sh`.
88 pub shell_program: Option<OsString>,
89 /// If `true` (default `true` on Windows and `false` everywhere else) we will see if it's safe
90 /// to manually invoke `command` after splitting its arguments as a shell would do.
91 ///
92 /// Note that outside of Windows, it's generally not advisable as this removes support for
93 /// literal shell scripts with shell-builtins.
94 ///
95 /// This mimics the behaviour we see with `git` on Windows, which also won't invoke the shell
96 /// there at all.
97 ///
98 /// Only effective if `use_shell` is `true` as well, as the shell will be used as a fallback if
99 /// it's not possible to split arguments as the command-line contains 'scripting'.
100 pub allow_manual_arg_splitting: bool,
101}
102
103/// Additional information that is relevant to spawned processes, which typically receive
104/// a wealth of contextual information when spawned from `git`.
105///
106/// See [the git source code](https://github.com/git/git/blob/cfb8a6e9a93adbe81efca66e6110c9b4d2e57169/git.c#L191)
107/// for details.
108#[derive(Debug, Default, Clone)]
109pub struct Context {
110 /// The `.git` directory that contains the repository.
111 ///
112 /// If set, it will be used to set the `GIT_DIR` environment variable.
113 pub git_dir: Option<PathBuf>,
114 /// Set the `GIT_WORK_TREE` environment variable with the given path.
115 pub worktree_dir: Option<PathBuf>,
116 /// If `true`, set `GIT_NO_REPLACE_OBJECTS` to `1`, which turns off object replacements, or `0` otherwise.
117 /// If `None`, the variable won't be set.
118 pub no_replace_objects: Option<bool>,
119 /// Set the `GIT_NAMESPACE` variable with the given value, effectively namespacing all
120 /// operations on references.
121 pub ref_namespace: Option<BString>,
122 /// If `true`, set `GIT_LITERAL_PATHSPECS` to `1`, which makes globs literal and prefixes as well, or `0` otherwise.
123 /// If `None`, the variable won't be set.
124 pub literal_pathspecs: Option<bool>,
125 /// If `true`, set `GIT_GLOB_PATHSPECS` to `1`, which lets wildcards not match the `/` character, and equals the `:(glob)` prefix.
126 /// If `false`, set `GIT_NOGLOB_PATHSPECS` to `1` which lets globs match only themselves.
127 /// If `None`, the variable won't be set.
128 pub glob_pathspecs: Option<bool>,
129 /// If `true`, set `GIT_ICASE_PATHSPECS` to `1`, to let patterns match case-insensitively, or `0` otherwise.
130 /// If `None`, the variable won't be set.
131 pub icase_pathspecs: Option<bool>,
132 /// If `true`, inherit `stderr` just like it's the default when spawning processes.
133 /// If `false`, suppress all stderr output.
134 /// If not `None`, this will override any value set with [`Prepare::stderr()`].
135 pub stderr: Option<bool>,
136}
137
138#[cfg(windows)]
139fn is_exe(executable: &Path) -> bool {
140 executable.extension() == Some(std::ffi::OsStr::new("exe"))
141}
142
143/// Split a joined `PATH` value according to platform conventions, omitting empty entries.
144///
145/// Git's Windows lookup skips empty entries instead of treating them as the current directory. This also prevents an
146/// explicitly empty `PATH` from finding a command there.
147fn split_paths(joined_paths: &OsStr) -> impl Iterator<Item = PathBuf> + '_ {
148 std::env::split_paths(joined_paths).filter(|path| !path.as_os_str().is_empty())
149}
150
151/// Return whether `command` is a single path component eligible for `PATH` lookup.
152fn is_bare_command(command: &Path) -> bool {
153 command.components().take(2).count() == 1
154}
155
156/// Try to find `command` in `joined_paths` using [`split_paths()`].
157/// Commands with an explicit extension are matched verbatim. Otherwise, `.exe` is preferred over an extensionless file.
158/// Note that just like Git, no lookup is performed if a slash or backslash is in `command`.
159fn win_path_lookup(command: &Path, joined_paths: &std::ffi::OsStr) -> Option<PathBuf> {
160 fn lookup(root: &Path, command: &Path, has_extension: bool) -> Option<PathBuf> {
161 let mut path = root.join(command);
162 if has_extension {
163 return path.is_file().then_some(path);
164 }
165
166 path.set_extension("exe");
167 if path.is_file() {
168 return Some(path);
169 }
170 path.set_extension("");
171 path.is_file().then_some(path)
172 }
173 if !is_bare_command(command) {
174 return None;
175 }
176 let has_extension = command.extension().is_some();
177
178 for root in split_paths(joined_paths) {
179 if let Some(executable) = lookup(&root, command, has_extension) {
180 return Some(executable);
181 }
182 }
183 None
184}
185
186/// Parse the shebang (`#!<path>`) from the first line of `executable`, and return the shebang
187/// data when available.
188pub fn extract_interpreter(executable: &Path) -> Option<shebang::Data> {
189 #[cfg(windows)]
190 if is_exe(executable) {
191 return None;
192 }
193 let mut buf = [0; 100]; // Note: just like Git
194 let mut file = std::fs::File::open(executable).ok()?;
195 let n = file.read(&mut buf).ok()?;
196 shebang::parse(buf[..n].as_bstr())
197}
198
199/// Prepare `cmd` for [spawning][std::process::Command::spawn()] by configuring it with various builder methods.
200///
201/// Note that the default IO is configured for typical API usage, that is
202///
203/// - `stdin` is null to prevent blocking unexpectedly on consumption of stdin
204/// - `stdout` is captured for consumption by the caller
205/// - `stderr` is inherited to allow the command to provide context to the user
206///
207/// On Windows, terminal Windows will be suppressed automatically.
208///
209/// ### Warning
210///
211/// When using this method, be sure that the invoked program doesn't rely on the current working dir and/or
212/// environment variables to know its context. If so, call instead [`Prepare::with_context()`] to provide
213/// additional information.
214pub fn prepare(cmd: impl Into<OsString>) -> Prepare {
215 Prepare {
216 command: cmd.into(),
217 shell_program: None,
218 context: None,
219 stdin: std::process::Stdio::null(),
220 stdout: std::process::Stdio::piped(),
221 stderr: std::process::Stdio::inherit(),
222 args: Vec::new(),
223 env: Vec::new(),
224 use_shell: false,
225 quote_command: false,
226 allow_manual_arg_splitting: cfg!(windows),
227 }
228}
229
230#[cfg(test)]
231mod tests;