#![deny(rust_2018_idioms, missing_docs)]
#![forbid(unsafe_code)]
use std::io::Read;
use std::{
ffi::OsString,
path::{Path, PathBuf},
};
use bstr::{BString, ByteSlice};
pub struct Prepare {
pub command: OsString,
pub context: Option<Context>,
pub stdin: std::process::Stdio,
pub stdout: std::process::Stdio,
pub stderr: std::process::Stdio,
pub args: Vec<OsString>,
pub env: Vec<(OsString, OsString)>,
pub use_shell: bool,
pub allow_manual_arg_splitting: bool,
}
#[derive(Debug, Default, Clone)]
pub struct Context {
pub git_dir: Option<PathBuf>,
pub worktree_dir: Option<PathBuf>,
pub no_replace_objects: Option<bool>,
pub ref_namespace: Option<BString>,
pub literal_pathspecs: Option<bool>,
pub glob_pathspecs: Option<bool>,
pub icase_pathspecs: Option<bool>,
pub stderr: Option<bool>,
}
mod prepare {
use std::borrow::Cow;
use std::{
ffi::OsString,
process::{Command, Stdio},
};
use bstr::ByteSlice;
use crate::{extract_interpreter, win_path_lookup, Context, Prepare};
impl Prepare {
pub fn with_shell(mut self) -> Self {
self.use_shell = self.command.to_str().map_or(true, |cmd| {
cmd.as_bytes().find_byteset(b"|&;<>()$`\\\"' \t\n*?[#~=%").is_some()
});
self
}
pub fn without_shell(mut self) -> Self {
self.use_shell = false;
self
}
pub fn with_context(mut self, ctx: Context) -> Self {
self.context = Some(ctx);
self
}
pub fn with_shell_allow_argument_splitting(mut self) -> Self {
self.allow_manual_arg_splitting = true;
self.with_shell()
}
pub fn stdin(mut self, stdio: Stdio) -> Self {
self.stdin = stdio;
self
}
pub fn stdout(mut self, stdio: Stdio) -> Self {
self.stdout = stdio;
self
}
pub fn stderr(mut self, stdio: Stdio) -> Self {
self.stderr = stdio;
self
}
pub fn arg(mut self, arg: impl Into<OsString>) -> Self {
self.args.push(arg.into());
self
}
pub fn args(mut self, args: impl IntoIterator<Item = impl Into<OsString>>) -> Self {
self.args
.append(&mut args.into_iter().map(Into::into).collect::<Vec<_>>());
self
}
pub fn env(mut self, key: impl Into<OsString>, value: impl Into<OsString>) -> Self {
self.env.push((key.into(), value.into()));
self
}
}
impl Prepare {
pub fn spawn(self) -> std::io::Result<std::process::Child> {
let mut cmd = Command::from(self);
gix_trace::debug!(cmd = ?cmd);
cmd.spawn()
}
}
impl From<Prepare> 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().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 mut cmd = Command::new(if cfg!(windows) { "sh" } else { "/bin/sh" });
cmd.arg("-c");
if !prep.args.is_empty() {
if prep.command.to_str().map_or(true, |cmd| !cmd.contains("$@")) {
prep.command.push(" \"$@\"");
} else {
gix_trace::debug!(
"Will not add '$@' to '{:?}' as it seems to contain it already",
prep.command
);
}
}
cmd.arg(prep.command);
cmd.arg("--");
cmd
}
}
} else if cfg!(windows) {
let program: Cow<'_, std::path::Path> = std::env::var_os("PATH")
.and_then(|path| win_path_lookup(prep.command.as_ref(), &path))
.map(Cow::Owned)
.unwrap_or(Cow::Borrowed(prep.command.as_ref()));
if let Some(shebang) = extract_interpreter(program.as_ref()) {
let mut cmd = Command::new(shebang.interpreter);
if program.is_absolute() {
cmd.args(shebang.args);
}
cmd.arg(prep.command);
cmd
} else {
Command::new(prep.command)
}
} else {
Command::new(prep.command)
};
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x08000000;
cmd.creation_flags(CREATE_NO_WINDOW);
}
cmd.stdin(prep.stdin)
.stdout(prep.stdout)
.stderr(prep.stderr)
.envs(prep.env)
.args(prep.args);
if let Some(ctx) = prep.context {
if let Some(git_dir) = ctx.git_dir {
cmd.env("GIT_DIR", &git_dir);
}
if let Some(worktree_dir) = ctx.worktree_dir {
cmd.env("GIT_WORK_TREE", worktree_dir);
}
if let Some(value) = ctx.no_replace_objects {
cmd.env("GIT_NO_REPLACE_OBJECTS", usize::from(value).to_string());
}
if let Some(namespace) = ctx.ref_namespace {
cmd.env("GIT_NAMESPACE", gix_path::from_bstring(namespace));
}
if let Some(value) = ctx.literal_pathspecs {
cmd.env("GIT_LITERAL_PATHSPECS", usize::from(value).to_string());
}
if let Some(value) = ctx.glob_pathspecs {
cmd.env(
if value {
"GIT_GLOB_PATHSPECS"
} else {
"GIT_NOGLOB_PATHSPECS"
},
"1",
);
}
if let Some(value) = ctx.icase_pathspecs {
cmd.env("GIT_ICASE_PATHSPECS", usize::from(value).to_string());
}
if let Some(stderr) = ctx.stderr {
cmd.stderr(if stderr { Stdio::inherit() } else { Stdio::null() });
}
}
cmd
}
}
}
fn is_exe(executable: &Path) -> bool {
executable.extension() == Some(std::ffi::OsStr::new("exe"))
}
fn win_path_lookup(command: &Path, path_value: &std::ffi::OsStr) -> Option<PathBuf> {
fn lookup(root: &bstr::BStr, command: &Path, is_exe: bool) -> Option<PathBuf> {
let mut path = gix_path::try_from_bstr(root).ok()?.join(command);
if !is_exe {
path.set_extension("exe");
}
if path.is_file() {
return Some(path);
}
if is_exe {
return None;
}
path.set_extension("");
path.is_file().then_some(path)
}
if command.components().take(2).count() == 2 {
return None;
}
let path = gix_path::os_str_into_bstr(path_value).ok()?;
let is_exe = is_exe(command);
for root in path.split(|b| *b == b';') {
if let Some(executable) = lookup(root.as_bstr(), command, is_exe) {
return Some(executable);
}
}
None
}
pub fn extract_interpreter(executable: &Path) -> Option<shebang::Data> {
#[cfg(windows)]
if is_exe(executable) {
return None;
}
let mut buf = [0; 100]; let mut file = std::fs::File::open(executable).ok()?;
let n = file.read(&mut buf).ok()?;
shebang::parse(buf[..n].as_bstr())
}
pub mod shebang {
use bstr::{BStr, ByteSlice};
use std::ffi::OsString;
use std::path::PathBuf;
pub fn parse(buf: &BStr) -> Option<Data> {
let mut line = buf.lines().next()?;
line = line.strip_prefix(b"#!")?;
let slash_idx = line.rfind_byteset(b"/\\")?;
Some(match line[slash_idx..].find_byte(b' ') {
Some(space_idx) => {
let space = slash_idx + space_idx;
Data {
interpreter: gix_path::from_byte_slice(line[..space].trim()).to_owned(),
args: line
.get(space + 1..)
.and_then(|mut r| {
r = r.trim();
if r.is_empty() {
return None;
}
match r.as_bstr().to_str() {
Ok(args) => shell_words::split(args)
.ok()
.map(|args| args.into_iter().map(Into::into).collect()),
Err(_) => Some(vec![gix_path::from_byte_slice(r).to_owned().into()]),
}
})
.unwrap_or_default(),
}
}
None => Data {
interpreter: gix_path::from_byte_slice(line.trim()).to_owned(),
args: Vec::new(),
},
})
}
#[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct Data {
pub interpreter: PathBuf,
pub args: Vec<OsString>,
}
}
pub fn prepare(cmd: impl Into<OsString>) -> Prepare {
Prepare {
command: cmd.into(),
context: None,
stdin: std::process::Stdio::null(),
stdout: std::process::Stdio::piped(),
stderr: std::process::Stdio::inherit(),
args: Vec::new(),
env: Vec::new(),
use_shell: false,
allow_manual_arg_splitting: cfg!(windows),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn internal_win_path_lookup() -> gix_testtools::Result {
let root = gix_testtools::scripted_fixture_read_only("win_path_lookup.sh")?;
let mut paths: Vec<_> = std::fs::read_dir(&root)?
.filter_map(Result::ok)
.map(|e| e.path().to_str().expect("no illformed UTF8").to_owned())
.collect();
paths.sort();
let lookup_path: OsString = paths.join(";").into();
assert_eq!(
win_path_lookup("a/b".as_ref(), &lookup_path),
None,
"any path with separator is considered ready to use"
);
assert_eq!(
win_path_lookup("x".as_ref(), &lookup_path),
Some(root.join("a").join("x.exe")),
"exe will be preferred, and it searches left to right thus doesn't find c/x.exe"
);
assert_eq!(
win_path_lookup("x.exe".as_ref(), &lookup_path),
Some(root.join("a").join("x.exe")),
"no matter what, a/x won't be found as it's shadowed by an exe file"
);
assert_eq!(
win_path_lookup("exe".as_ref(), &lookup_path),
Some(root.join("b").join("exe")),
"it finds files further down the path as well"
);
Ok(())
}
}