use crate::driver::{process, substitute_f_parameter, Operation, Process, State};
use crate::{driver, Driver};
use bstr::{BStr, BString};
use std::process::Stdio;
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum Error {
#[error("Failed to spawn driver: {command:?}")]
SpawnCommand {
source: std::io::Error,
command: std::process::Command,
},
#[error("Process handshake with command {command:?} failed")]
ProcessHandshake {
source: process::client::handshake::Error,
command: std::process::Command,
},
}
impl State {
pub fn process(
&mut self,
driver: &Driver,
operation: Operation,
rela_path: &BStr,
) -> Result<Option<Process<'_>>, Error> {
match driver.process.as_ref() {
Some(process) => {
let client = match self.running.remove(process) {
Some(c) => c,
None => {
let (child, cmd) = spawn_driver(process.clone())?;
process::Client::handshake(child, "git-filter", &[2], &["clean", "smudge", "delay"]).map_err(
|err| Error::ProcessHandshake {
source: err,
command: cmd,
},
)?
}
};
self.running.insert(process.clone(), client);
let client = self.running.get_mut(process).expect("just inserted");
Ok(Some(Process::MultiFile {
client,
key: driver::Key(process.to_owned()),
}))
}
None => {
let cmd = match operation {
Operation::Clean => driver
.clean
.as_ref()
.map(|cmd| substitute_f_parameter(cmd.as_ref(), rela_path)),
Operation::Smudge => driver
.smudge
.as_ref()
.map(|cmd| substitute_f_parameter(cmd.as_ref(), rela_path)),
};
let cmd = match cmd {
Some(cmd) => cmd,
None => return Ok(None),
};
let (child, command) = spawn_driver(cmd)?;
Ok(Some(Process::SingleFile { child, command }))
}
}
}
}
fn spawn_driver(cmd: BString) -> Result<(std::process::Child, std::process::Command), Error> {
let mut cmd: std::process::Command = gix_command::prepare(gix_path::from_bstr(cmd).into_owned())
.with_shell()
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.into();
let child = match cmd.spawn() {
Ok(child) => child,
Err(err) => {
return Err(Error::SpawnCommand {
source: err,
command: cmd,
})
}
};
Ok((child, cmd))
}