larastvel_core/process/
mod.rs1use std::io;
4use std::path::Path;
5use std::time::Duration;
6
7#[derive(Debug, Clone, Default, PartialEq)]
9pub struct ProcessResult {
10 pub exit_code: Option<i32>,
12 pub stdout: String,
13 pub stderr: String,
14}
15
16impl ProcessResult {
17 pub fn successful(&self) -> bool {
18 self.exit_code == Some(0)
19 }
20}
21
22pub struct ProcessBuilder {
24 command: String,
25 path: Option<String>,
26 timeout: Option<Duration>,
27 envs: Vec<(String, String)>,
28}
29
30impl ProcessBuilder {
31 pub fn new(command: impl Into<String>) -> Self {
32 Self {
33 command: command.into(),
34 path: None,
35 timeout: None,
36 envs: Vec::new(),
37 }
38 }
39
40 pub fn path(mut self, path: impl Into<String>) -> Self {
42 self.path = Some(path.into());
43 self
44 }
45
46 pub fn timeout(mut self, timeout: Duration) -> Self {
48 self.timeout = Some(timeout);
49 self
50 }
51
52 pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
54 self.envs.push((key.into(), value.into()));
55 self
56 }
57
58 fn base_command(&self) -> tokio::process::Command {
59 let mut cmd = if cfg!(windows) {
60 let mut c = tokio::process::Command::new("cmd");
61 c.arg("/C").arg(&self.command);
62 c
63 } else {
64 let mut c = tokio::process::Command::new("sh");
65 c.arg("-c").arg(&self.command);
66 c
67 };
68 if let Some(p) = &self.path {
69 cmd.current_dir(Path::new(p));
70 }
71 for (k, v) in &self.envs {
72 cmd.env(k, v);
73 }
74 cmd
75 }
76
77 pub async fn run(&self) -> io::Result<ProcessResult> {
79 let mut child = self
80 .base_command()
81 .stdout(std::process::Stdio::piped())
82 .stderr(std::process::Stdio::piped())
83 .spawn()?;
84
85 let mut stdout = child.stdout.take().expect("stdout is piped");
86 let mut stderr = child.stderr.take().expect("stderr is piped");
87 let reader = tokio::task::spawn(async move {
88 let mut out = Vec::new();
89 let mut err = Vec::new();
90 let _ = tokio::io::AsyncReadExt::read_to_end(&mut stdout, &mut out).await;
91 let _ = tokio::io::AsyncReadExt::read_to_end(&mut stderr, &mut err).await;
92 (out, err)
93 });
94
95 let exit_code = match self.timeout {
96 Some(t) => match tokio::time::timeout(t, child.wait()).await {
97 Ok(status) => status?.code(),
98 Err(_) => {
99 let _ = child.kill().await;
100 None
101 }
102 },
103 None => child.wait().await?.code(),
104 };
105
106 let (stdout_bytes, stderr_bytes) = reader.await.unwrap_or_default();
107 Ok(ProcessResult {
108 exit_code,
109 stdout: String::from_utf8_lossy(&stdout_bytes).to_string(),
110 stderr: String::from_utf8_lossy(&stderr_bytes).to_string(),
111 })
112 }
113
114 pub async fn background(&self) -> io::Result<tokio::process::Child> {
116 self.base_command()
117 .stdout(std::process::Stdio::null())
118 .stderr(std::process::Stdio::null())
119 .spawn()
120 }
121}
122
123pub async fn run(command: impl Into<String>) -> io::Result<ProcessResult> {
130 ProcessBuilder::new(command).run().await
131}
132
133pub async fn foreground(command: impl Into<String>) -> io::Result<ProcessResult> {
136 let builder = ProcessBuilder::new(command);
137 let mut child = builder
138 .base_command()
139 .stdout(std::process::Stdio::inherit())
140 .stderr(std::process::Stdio::inherit())
141 .spawn()?;
142 let status = child.wait().await?;
143 Ok(ProcessResult {
144 exit_code: status.code(),
145 stdout: String::new(),
146 stderr: String::new(),
147 })
148}
149
150#[cfg(test)]
151mod tests {
152 use super::*;
153
154 #[tokio::test]
155 async fn test_run_captures_stdout() {
156 let result = run("echo hello").await.unwrap();
157 assert_eq!(result.exit_code, Some(0));
158 assert!(result.stdout.contains("hello"));
159 assert!(result.successful());
160 }
161
162 #[tokio::test]
163 async fn test_run_reports_nonzero_exit() {
164 let result = run("exit 3").await.unwrap();
165 assert_eq!(result.exit_code, Some(3));
166 assert!(!result.successful());
167 }
168
169 #[tokio::test]
170 async fn test_run_captures_stderr() {
171 let result = run("echo oops 1>&2").await.unwrap();
172 assert!(result.stderr.contains("oops"));
173 }
174
175 #[tokio::test]
176 async fn test_run_with_env() {
177 let result = ProcessBuilder::new("echo $GREETING")
178 .env("GREETING", "hola")
179 .run()
180 .await
181 .unwrap();
182 assert!(result.stdout.contains("hola"));
183 }
184
185 #[tokio::test]
186 async fn test_run_timeout_kills_process() {
187 let result = ProcessBuilder::new("sleep 5")
188 .timeout(Duration::from_millis(100))
189 .run()
190 .await
191 .unwrap();
192 assert_eq!(result.exit_code, None);
193 }
194
195 #[tokio::test]
196 async fn test_foreground_streams_and_exits() {
197 let result = foreground("echo streamed").await.unwrap();
198 assert_eq!(result.exit_code, Some(0));
199 }
200}