wasi_virt_layer_cli/
fallback_command.rs1use std::{
2 io::{Read as _, Seek as _},
3 process::Command,
4};
5
6pub struct FallbackCommand<F>
7where
8 F: FnOnce(&[String]) -> i32 + Send + 'static,
9{
10 bin: String,
11 args: Vec<String>,
12 func: Option<F>,
13}
14
15impl<F> FallbackCommand<F>
16where
17 F: FnOnce(&[String]) -> i32 + Send + 'static,
18{
19 pub fn new(bin: impl AsRef<str>, func: F) -> Self {
20 Self {
21 bin: bin.as_ref().to_string(),
22 args: Vec::new(),
23 func: Some(func),
24 }
25 }
26
27 pub fn arg(&mut self, arg: impl AsRef<str>) -> &mut Self {
28 self.args.push(arg.as_ref().to_string());
29 self
30 }
31
32 pub fn args<I, S>(&mut self, args: I) -> &mut Self
33 where
34 I: IntoIterator<Item = S>,
35 S: AsRef<str>,
36 {
37 for arg in args {
38 self.arg(arg.as_ref());
39 }
40 self
41 }
42
43 pub fn spawn(&mut self) -> std::io::Result<FallbackChild> {
44 let mut cmd = Command::new(&self.bin);
45 cmd.args(&self.args);
46 let piped_out = std::process::Stdio::piped();
47 let piped_err = std::process::Stdio::piped();
48 cmd.stdout(piped_out);
49 cmd.stderr(piped_err);
50 match cmd.spawn() {
51 Ok(child) => Ok(FallbackChild::new_process(child)),
52 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
53 let args = self.args.clone();
55 let func = self.func.take().expect("Function already taken");
56 let handle = std::thread::spawn(move || {
57 let log = std::fs::OpenOptions::new()
58 .truncate(true)
59 .read(true)
60 .create(true)
61 .write(true)
62 .open(get_temp_filepath())
63 .unwrap();
64
65 let print_redirect = gag::Redirect::stdout(log).unwrap();
66
67 let result = (func)(&args);
68
69 let mut log = print_redirect.into_inner();
71
72 let mut buf = String::new();
73 log.seek(std::io::SeekFrom::Start(0)).unwrap();
74 log.read_to_string(&mut buf).unwrap();
75
76 FallbackOutput {
77 stdout: buf.into_bytes(),
78 stderr: Vec::new(),
79 success: result == 0,
80 }
81 });
82 Ok(FallbackChild::new_thread(handle))
83 }
84 Err(e) => Err(e),
85 }
86 }
87}
88
89pub enum FallbackChild {
90 Process(std::process::Child),
91 Thread(std::thread::JoinHandle<FallbackOutput>),
92}
93
94impl FallbackChild {
95 fn new_process(child: std::process::Child) -> Self {
96 FallbackChild::Process(child)
97 }
98
99 fn new_thread(handle: std::thread::JoinHandle<FallbackOutput>) -> Self {
100 FallbackChild::Thread(handle)
101 }
102
103 pub fn wait_with_output(self) -> std::io::Result<FallbackOutput> {
104 match self {
105 FallbackChild::Process(child) => {
106 let output = child.wait_with_output()?;
107 Ok(FallbackOutput {
108 stdout: output.stdout,
109 stderr: output.stderr,
110 success: output.status.success(),
111 })
112 }
113 FallbackChild::Thread(handle) => {
114 let out = handle.join().expect("Thread panicked");
115 Ok(out)
116 }
117 }
118 }
119}
120
121pub struct FallbackOutput {
122 pub stdout: Vec<u8>,
123 pub stderr: Vec<u8>,
124 pub success: bool,
125}
126
127fn get_temp_filepath() -> String {
128 let now = std::time::SystemTime::now();
129 let timestamp = now
130 .duration_since(std::time::UNIX_EPOCH)
131 .unwrap()
132 .as_millis();
133
134 #[cfg(windows)]
135 return dirs::data_local_dir()
136 .unwrap()
137 .join("Temp")
138 .join(format!("tmp_{}_{timestamp}.log", env!("CARGO_PKG_NAME")))
139 .to_string_lossy()
140 .into();
141
142 #[cfg(unix)]
143 return format!("/tmp/tmp_{}_{timestamp}.log", env!("CARGO_PKG_NAME"));
144}
145
146pub fn check_gag() -> bool {
148 pub fn check_gag() -> Option<()> {
149 let gag = gag::Redirect::stdout(
150 std::fs::OpenOptions::new()
151 .truncate(true)
152 .read(true)
153 .create(true)
154 .write(true)
155 .open(get_temp_filepath())
156 .ok()?,
157 )
158 .ok()?;
159
160 const WHITE_SPACE: &str = " \t\n\r";
161
162 print!("{WHITE_SPACE}");
163 std::io::Write::flush(&mut std::io::stdout()).ok()?;
164
165 let mut stdout = gag.into_inner();
166 let mut buf = String::new();
167 stdout.seek(std::io::SeekFrom::Start(0)).ok()?;
168 stdout.read_to_string(&mut buf).ok()?;
169
170 Some(if buf.contains(WHITE_SPACE) {
171 ()
172 } else {
173 return None;
174 })
175 }
176
177 check_gag().is_some()
178}
179
180#[cfg(test)]
181mod tests {
182 use super::*;
183
184 static MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
185
186 #[test]
187 fn test_fallback_command() {
190 let _lock = MUTEX.lock().unwrap();
191 if !check_gag() {
192 return;
193 }
194
195 let mut cmd = FallbackCommand::new("non_existent_command", |args: &[String]| {
196 println!("Fallback function called with args: {:?}", args);
197 0
198 });
199 cmd.arg("arg1").arg("arg2");
200
201 let child = cmd.spawn().expect("Failed to spawn command");
202 let output = child.wait_with_output().expect("Failed to get output");
203
204 assert!(output.success);
205 let stdout_str = String::from_utf8_lossy(&output.stdout);
206 assert!(stdout_str.contains("Fallback function called with args: [\"arg1\", \"arg2\"]"));
207
208 drop(_lock);
209 }
210
211 #[cfg(feature = "fallback")]
212 #[test]
213 fn test_fallback_wasm_merge() {
214 let _lock = MUTEX.lock().unwrap();
215 if !check_gag() {
216 return;
217 }
218
219 let mut cmd = FallbackCommand::new("non_existent_command", |args: &[String]| {
220 wasm_merge_sys::run_wasm_merge(&args)
221 });
222 cmd.arg("--help");
223
224 let child = cmd.spawn().expect("Failed to spawn command");
225 let output = child.wait_with_output().expect("Failed to get output");
226
227 assert!(output.success);
228 let stdout_str = String::from_utf8_lossy(&output.stdout);
229 panic!("Output: {}", stdout_str);
230
231 drop(_lock);
232 }
233}