use anyhow::{anyhow, bail, Context, Result};
use std::collections::HashMap;
use std::path::Path;
use std::process::Command;
#[derive(Debug, Clone)]
pub enum Lifecycle {
PreInstallCmd,
PostInstallCmd,
PostAutoloadDump,
}
impl Lifecycle {
pub fn key(&self) -> &'static str {
match self {
Lifecycle::PreInstallCmd => "pre-install-cmd",
Lifecycle::PostInstallCmd => "post-install-cmd",
Lifecycle::PostAutoloadDump => "post-autoload-dump",
}
}
}
#[derive(Default, Debug)]
pub struct ScriptOutcome {
pub ran: usize,
pub skipped: usize,
}
pub struct Runner<'a> {
pub project_root: &'a Path,
pub vendor_bin_dir: &'a Path,
pub scripts: &'a serde_json::Value,
}
impl<'a> Runner<'a> {
pub fn dispatch(&self, event: Lifecycle) -> Result<ScriptOutcome> {
let key = event.key();
let entries = match self.scripts.get(key) {
Some(v) => v,
None => {
tracing::debug!("no scripts for {key}, skipping");
return Ok(ScriptOutcome::default());
}
};
let list: Vec<String> = match entries {
serde_json::Value::String(s) => vec![s.clone()],
serde_json::Value::Array(a) => a
.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect(),
_ => {
tracing::warn!("scripts.{key} has unexpected shape, skipping");
return Ok(ScriptOutcome::default());
}
};
let mut env_overrides: HashMap<String, String> = HashMap::new();
let mut outcome = ScriptOutcome::default();
for raw in list {
self.run_one(&raw, &mut env_overrides, &mut outcome)
.with_context(|| format!("script `{raw}` (event {key})"))?;
}
Ok(outcome)
}
pub fn run_one(
&self,
raw: &str,
env: &mut HashMap<String, String>,
outcome: &mut ScriptOutcome,
) -> Result<()> {
let cmd = raw.trim();
if let Some(rest) = cmd.strip_prefix("@putenv") {
let rest = rest.trim();
if let Some((k, v)) = rest.split_once('=') {
env.insert(k.trim().to_string(), v.trim().to_string());
} else {
env.remove(rest);
}
outcome.skipped += 1;
return Ok(());
}
if cmd.starts_with("@composer ") || cmd == "@composer" {
tracing::warn!("skipping `{cmd}` — composr does not recursively invoke composer");
outcome.skipped += 1;
return Ok(());
}
if let Some(rest) = cmd.strip_prefix("@php ") {
return self.exec("php", parse_argv(rest)?, env, outcome);
}
if cmd.starts_with('@') {
tracing::warn!("skipping `{cmd}` — unsupported @-script");
outcome.skipped += 1;
return Ok(());
}
if !cmd.contains(char::is_whitespace) && cmd.contains("::") {
tracing::warn!(
"skipping class-method script `{cmd}` — not supported (run `composer run-script` for a fully-evaluated event)"
);
outcome.skipped += 1;
return Ok(());
}
self.exec("sh", vec!["-c".into(), cmd.into()], env, outcome)
}
fn exec(
&self,
program: &str,
args: Vec<String>,
env: &HashMap<String, String>,
outcome: &mut ScriptOutcome,
) -> Result<()> {
let mut c = Command::new(program);
c.args(&args).current_dir(self.project_root);
if let Ok(existing) = std::env::var("PATH") {
let new_path = format!("{}:{}", self.vendor_bin_dir.display(), existing);
c.env("PATH", new_path);
} else {
c.env("PATH", self.vendor_bin_dir);
}
for (k, v) in env {
c.env(k, v);
}
let status = c
.status()
.with_context(|| format!("spawning `{program} {args:?}`"))?;
if !status.success() {
bail!("`{program} {args:?}` exited with {status}");
}
outcome.ran += 1;
Ok(())
}
}
fn parse_argv(s: &str) -> Result<Vec<String>> {
let mut out = Vec::new();
let mut buf = String::new();
let mut chars = s.chars().peekable();
let mut quote: Option<char> = None;
while let Some(c) = chars.next() {
match (c, quote) {
('\\', _) => {
if let Some(&n) = chars.peek() {
chars.next();
buf.push(n);
}
}
('"', None) => quote = Some('"'),
('\'', None) => quote = Some('\''),
(c, Some(q)) if c == q => quote = None,
(c, None) if c.is_whitespace() => {
if !buf.is_empty() {
out.push(std::mem::take(&mut buf));
}
}
(c, _) => buf.push(c),
}
}
if quote.is_some() {
return Err(anyhow!("unterminated quote in script: {s}"));
}
if !buf.is_empty() {
out.push(buf);
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_argv_simple() {
assert_eq!(parse_argv("a b c").unwrap(), vec!["a", "b", "c"]);
}
#[test]
fn parse_argv_quoted() {
assert_eq!(
parse_argv("artisan migrate --message 'hello world'").unwrap(),
vec!["artisan", "migrate", "--message", "hello world"]
);
}
}