1use futures::future::join_all;
2use regex::{Captures, Regex};
3use std::env;
4use std::path::Path;
5use std::sync::LazyLock;
6use tokio::process::Command;
7
8pub async fn expand_shell(content: &str, cwd: &Path) -> String {
12 let commands = SHELL_MARKER.captures_iter(content).map(|captures| {
13 let (_, [command]) = captures.extract();
14 run(command, cwd)
15 });
16 let mut outputs = join_all(commands)
17 .await
18 .into_iter()
19 .map(|output| output.inspect_err(|error| tracing::warn!("{error}")).unwrap_or_default());
20
21 SHELL_MARKER.replace_all(content, |_: &Captures<'_>| outputs.next().unwrap_or_default()).into_owned()
22}
23
24#[derive(Debug, thiserror::Error)]
25enum ShellExpansionError {
26 #[error("Failed to spawn {shell} for `{cmd}`: {error}")]
27 Spawn { shell: String, cmd: String, error: String },
28 #[error("Shell interpolation `{cmd}` failed with {status}: {stderr}")]
29 NonZeroExit { cmd: String, status: String, stderr: String },
30}
31
32static SHELL_MARKER: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"!`([^`\n]+)`").expect("valid regex"));
33
34async fn run(cmd: &str, cwd: &Path) -> Result<String, ShellExpansionError> {
35 let shell = env::var("SHELL").unwrap_or_else(|_| "sh".to_string());
36 let output =
37 Command::new(&shell).arg("-c").arg(cmd).current_dir(cwd).output().await.map_err(|e| {
38 ShellExpansionError::Spawn { shell: shell.clone(), cmd: cmd.to_string(), error: e.to_string() }
39 })?;
40
41 if !output.status.success() {
42 let stderr = String::from_utf8_lossy(&output.stderr);
43 return Err(ShellExpansionError::NonZeroExit {
44 cmd: cmd.to_string(),
45 status: output.status.to_string(),
46 stderr: stderr.trim().to_string(),
47 });
48 }
49
50 Ok(String::from_utf8_lossy(&output.stdout).trim_end().to_string())
51}
52
53#[cfg(test)]
54mod tests {
55 use super::*;
56
57 #[tokio::test]
58 async fn no_op_without_marker() {
59 let content = "Just some plain content with no directives";
60 let cwd = std::env::current_dir().unwrap();
61 let result = expand_shell(content, &cwd).await;
62 assert_eq!(result, content);
63 }
64
65 #[tokio::test]
66 async fn runs_shell_command() {
67 let cwd = std::env::current_dir().unwrap();
68 let result = expand_shell("branch: !`echo main`", &cwd).await;
69 assert_eq!(result, "branch: main");
70 }
71
72 #[tokio::test]
73 async fn runs_command_in_cwd() {
74 let dir = tempfile::tempdir().unwrap();
75 std::fs::write(dir.path().join("sentinel.txt"), "").unwrap();
76
77 let result = expand_shell("files: !`ls`", dir.path()).await;
78 assert!(result.contains("sentinel.txt"), "expected sentinel.txt in output: {result}");
79 }
80
81 #[tokio::test]
82 async fn handles_multiple_commands() {
83 let cwd = std::env::current_dir().unwrap();
84 let result = expand_shell("a=!`echo one`, b=!`echo two`", &cwd).await;
85 assert_eq!(result, "a=one, b=two");
86 }
87
88 #[tokio::test]
89 async fn failed_command_substitutes_empty_string() {
90 let cwd = std::env::current_dir().unwrap();
91 let result = expand_shell("before !`exit 1` after", &cwd).await;
92 assert_eq!(result, "before after");
93 }
94
95 #[tokio::test]
96 async fn trims_trailing_whitespace() {
97 let cwd = std::env::current_dir().unwrap();
98 let result = expand_shell("!`printf 'hi\\n\\n'`", &cwd).await;
99 assert_eq!(result, "hi");
100 }
101}