use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Duration;
use super::runner::HookCommand;
const SHELLS: [&str; 6] = ["sh", "bash", "dash", "zsh", "ksh", "ash"];
const CHECK_DEADLINE: Duration = Duration::from_secs(10);
#[derive(Debug, thiserror::Error)]
pub enum HookCheckError {
#[error("the script {path} cannot be read: {source}")]
Unreadable {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("the script {path} is not UTF-8 text")]
NotText {
path: PathBuf,
},
#[error("the script {path} has a syntax error: {diagnostics}")]
Syntax {
path: PathBuf,
diagnostics: String,
},
#[error("the shell `{shell}` that parses {path} cannot be run: {source}")]
ShellUnavailable {
path: PathBuf,
shell: String,
#[source]
source: std::io::Error,
},
#[error("the shell did not finish parsing {path} within {deadline:?}")]
CheckTimeout {
path: PathBuf,
deadline: Duration,
},
}
impl HookCheckError {
#[must_use]
pub fn path(&self) -> &Path {
match self {
Self::Unreadable { path, .. }
| Self::NotText { path }
| Self::Syntax { path, .. }
| Self::ShellUnavailable { path, .. }
| Self::CheckTimeout { path, .. } => path,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScriptSnapshot {
pub path: PathBuf,
pub content: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Resolved {
pub command: HookCommand,
pub script: Option<ScriptSnapshot>,
}
struct Located {
shell: Vec<String>,
tail: Vec<String>,
spelled: String,
snapshot: ScriptSnapshot,
}
fn is_shell(program: &str) -> bool {
Path::new(program)
.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| SHELLS.contains(&name))
}
async fn read_text(path: &Path) -> Result<String, HookCheckError> {
let bytes = async_fs::read(path)
.await
.map_err(|source| HookCheckError::Unreadable {
path: path.to_path_buf(),
source,
})?;
String::from_utf8(bytes).map_err(|_| HookCheckError::NotText {
path: path.to_path_buf(),
})
}
fn shebang_shell(content: &str) -> Option<Vec<String>> {
let line = content.strip_prefix("#!")?.lines().next()?;
let mut words = line.split_whitespace();
let mut interpreter = words.next()?;
if Path::new(interpreter)
.file_name()
.is_some_and(|n| n == "env")
{
interpreter = words.find(|word| !word.starts_with('-'))?;
}
is_shell(interpreter).then(|| {
std::iter::once(interpreter)
.chain(words)
.map(ToString::to_string)
.collect()
})
}
async fn locate(command: &[String]) -> Result<Option<Located>, HookCheckError> {
let Some((program, args)) = command.split_first() else {
return Ok(None);
};
if is_shell(program) {
let mut index = 0;
while let Some(arg) = args.get(index) {
if !arg.starts_with('-') {
break;
}
if arg.starts_with("--") {
index += 1;
} else if arg.contains('c') {
return Ok(None);
} else if arg == "-o" || arg == "-O" {
index += 2;
} else {
index += 1;
}
}
let Some(spelled) = args.get(index) else {
return Ok(None);
};
let path = PathBuf::from(spelled);
let content = read_text(&path).await?;
return Ok(Some(Located {
shell: command[..=index].to_vec(),
tail: args[index + 1..].to_vec(),
spelled: spelled.clone(),
snapshot: ScriptSnapshot { path, content },
}));
}
if !program.contains(['/', std::path::MAIN_SEPARATOR]) {
return Ok(None);
}
let path = PathBuf::from(program);
let Ok(bytes) = async_fs::read(&path).await else {
return Ok(None);
};
let Some(content) = String::from_utf8(bytes)
.ok()
.filter(|text| text.starts_with("#!"))
else {
return Ok(None);
};
let Some(shell) = shebang_shell(&content) else {
return Ok(None);
};
Ok(Some(Located {
shell,
tail: args.to_vec(),
spelled: program.clone(),
snapshot: ScriptSnapshot { path, content },
}))
}
async fn check(shell: &[String], snapshot: &ScriptSnapshot) -> Result<(), HookCheckError> {
let (program, flags) = shell.split_first().expect("a located shell has a program");
let mut command = async_process::Command::new(program);
command
.args(flags)
.arg("-n")
.arg("-c")
.arg(&snapshot.content)
.stdin(Stdio::null())
.kill_on_drop(true);
let parse = async {
command
.output()
.await
.map_err(|source| HookCheckError::ShellUnavailable {
path: snapshot.path.clone(),
shell: program.clone(),
source,
})
};
let expiry = async {
async_io::Timer::after(CHECK_DEADLINE).await;
Err(HookCheckError::CheckTimeout {
path: snapshot.path.clone(),
deadline: CHECK_DEADLINE,
})
};
let output = futures_lite::future::or(parse, expiry).await?;
if output.status.success() {
Ok(())
} else {
Err(HookCheckError::Syntax {
path: snapshot.path.clone(),
diagnostics: String::from_utf8_lossy(&output.stderr).trim().to_string(),
})
}
}
pub(super) async fn resolve(
command: &HookCommand,
known: Option<&ScriptSnapshot>,
) -> Result<Resolved, HookCheckError> {
let Some(located) = locate(&command.command).await? else {
return Ok(Resolved {
command: command.clone(),
script: None,
});
};
if known != Some(&located.snapshot) {
check(&located.shell, &located.snapshot).await?;
}
let mut argv = located.shell;
argv.push("-c".to_string());
argv.push(located.snapshot.content.clone());
argv.push(located.spelled);
argv.extend(located.tail);
Ok(Resolved {
command: HookCommand {
command: argv,
deadline_ms: command.deadline_ms,
},
script: Some(located.snapshot),
})
}