-
Notifications
You must be signed in to change notification settings - Fork 4k
Expand file tree
/
Copy pathasync.rs
More file actions
421 lines (392 loc) · 12.6 KB
/
async.rs
File metadata and controls
421 lines (392 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
// Allow disallowed types here. We actively want to use `std::process::Command` since this is the
// wrapper implementation that allows us to not import the above type elsewhere in this workspace.
#![allow(clippy::disallowed_types)]
use async_process::Child;
use std::ffi::OsStr;
use std::fmt;
use std::future::Future;
use std::io;
use std::path::Path;
use std::process::{ExitStatus, Output, Stdio};
/// Wrapper around a [`async_process::Command`] that ensures any new Command is set with the windows
/// `CREATE_NO_WINDOW` flag to avoid a console window temporarily popping up.
pub struct Command {
pub(super) inner: async_process::Command,
stdin_is_default: bool,
stdout_is_default: bool,
stderr_is_default: bool,
}
impl fmt::Debug for Command {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.inner, f)
}
}
impl Command {
/// Constructs a new [`Command`] for launching `program`.
///
/// The initial configuration (the working directory and environment variables) is inherited
/// from the current process.
///
/// # Examples
///
/// ```
/// use async_process::Command;
///
/// let mut cmd = Command::new("ls");
/// ```
pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
let program = crate::wsl::translate_program_for_spawn(program.as_ref());
let inner = async_process::Command::new(program);
Self::new_internal(inner)
}
/// Same as new, but makes this process the leader of a new session with
/// the same ID as the process ID.
///
/// This ensures the process does not inherit the controlling terminal.
///
/// See [`setsid(2)`](https://man7.org/linux/man-pages/man2/setsid.2.html).
#[cfg(unix)]
pub fn new_with_session<S: AsRef<OsStr>>(program: S) -> Command {
let program = crate::wsl::translate_program_for_spawn(program.as_ref());
let mut command = std::process::Command::new(program);
// SAFETY: `pre_exec` requires the closure to be async-signal-safe.
// `setsid` is async-signal-safe per POSIX; see the signal-safety(7) man page:
// https://man7.org/linux/man-pages/man7/signal-safety.7.html
unsafe {
use std::os::unix::process::CommandExt as _;
command.pre_exec(|| {
// TODO: Use `CommandExt::setsid` once it stabilizes (https://github.com/rust-lang/rust/issues/105376).
// That enables the `posix_spawn` fast path rather than falling back to `fork`/`exec`.
if libc::setsid() < 0 {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
let inner: async_process::Command = command.into();
Self::new_internal(inner)
}
/// Same as new, but makes this process the leader of a process group with same ID
/// as the process ID.
/// This allows for killing any other processes spawned by this process
/// when we kill this process.
pub fn new_with_process_group<S: AsRef<OsStr>>(program: S) -> Command {
let program = crate::wsl::translate_program_for_spawn(program.as_ref());
#[allow(unused_mut)]
let mut command = std::process::Command::new(program);
// Configures the new process to be the leader of a process group with its
// process ID as the group ID. This allows for killing any other processes
// spawned by this process when we kill this process.
//
// TODO(roland): handle for windows
#[cfg(unix)]
std::os::unix::process::CommandExt::process_group(&mut command, 0);
let inner: async_process::Command = command.into();
Self::new_internal(inner)
}
#[allow(unused_mut)]
fn new_internal(mut inner: async_process::Command) -> Command {
#[cfg(all(windows, not(feature = "test-util")))]
{
use async_process::windows::CommandExt;
// We need to set the `CREATE_BREAKAWAY_FROM_JOB` flag to avoid assigning
// the process to the same Job Object as the Warp process, otherwise the
// process will be killed when the Warp process is killed.
let flags = windows::Win32::System::Threading::CREATE_NO_WINDOW.0
| windows::Win32::System::Threading::CREATE_BREAKAWAY_FROM_JOB.0;
inner.creation_flags(flags);
}
Self {
inner,
stdin_is_default: true,
stdout_is_default: true,
stderr_is_default: true,
}
}
/// Adds a single argument to pass to the program.
///
/// # Examples
///
/// ```
/// use async_process::Command;
///
/// let mut cmd = Command::new("echo");
/// cmd.arg("hello");
/// cmd.arg("world");
/// ```
pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
self.inner.arg(arg);
self
}
/// Adds multiple arguments to pass to the program.
///
/// # Examples
///
/// ```
/// use async_process::Command;
///
/// let mut cmd = Command::new("echo");
/// cmd.args(&["hello", "world"]);
/// ```
pub fn args<I, S>(&mut self, args: I) -> &mut Command
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
self.inner.args(args);
self
}
/// Configures an environment variable for the new process.
///
/// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
/// and case-sensitive on all other platforms.
///
/// # Examples
///
/// ```
/// use async_process::Command;
///
/// let mut cmd = Command::new("ls");
/// cmd.env("PATH", "/bin");
/// ```
pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
where
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
self.inner.env(key, val);
self
}
/// Configures multiple environment variables for the new process.
///
/// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
/// and case-sensitive on all other platforms.
///
/// # Examples
///
/// ```
/// use async_process::Command;
///
/// let mut cmd = Command::new("ls");
/// cmd.envs(vec![("PATH", "/bin"), ("TERM", "xterm-256color")]);
/// ```
pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
where
I: IntoIterator<Item = (K, V)>,
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
self.inner.envs(vars);
self
}
/// Removes an environment variable mapping.
///
/// # Examples
///
/// ```
/// use async_process::Command;
///
/// let mut cmd = Command::new("ls");
/// cmd.env_remove("PATH");
/// ```
pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
self.inner.env_remove(key);
self
}
/// Removes all environment variable mappings.
///
/// # Examples
///
/// ```
/// use async_process::Command;
///
/// let mut cmd = Command::new("ls");
/// cmd.env_clear();
/// ```
pub fn env_clear(&mut self) -> &mut Command {
self.inner.env_clear();
self
}
/// Configures the working directory for the new process.
///
/// # Examples
///
/// ```
/// use async_process::Command;
///
/// let mut cmd = Command::new("ls");
/// cmd.current_dir("/");
/// ```
pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
self.inner.current_dir(dir);
self
}
/// Configures the standard input (stdin) for the new process.
///
/// # Examples
///
/// ```
/// use async_process::{Command, Stdio};
///
/// let mut cmd = Command::new("cat");
/// cmd.stdin(Stdio::null());
/// ```
pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
self.inner.stdin(cfg);
self.stdin_is_default = false;
self
}
/// Configures the standard output (stdout) for the new process.
///
/// # Examples
///
/// ```
/// use async_process::{Command, Stdio};
///
/// let mut cmd = Command::new("ls");
/// cmd.stdout(Stdio::piped());
/// ```
pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
self.inner.stdout(cfg);
self.stdout_is_default = false;
self
}
/// Configures the standard error (stderr) for the new process.
///
/// # Examples
///
/// ```
/// use async_process::{Command, Stdio};
///
/// let mut cmd = Command::new("ls");
/// cmd.stderr(Stdio::piped());
/// ```
pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
self.inner.stderr(cfg);
self.stderr_is_default = false;
self
}
/// Configures whether to reap the zombie process when [`Child`] is dropped.
///
/// When the process finishes, it becomes a "zombie" and some resources associated with it
/// remain until [`Child::try_status()`], [`Child::status()`], or [`Child::output()`] collects
/// its exit code.
///
/// If its exit code is never collected, the resources may leak forever. This crate has a
/// background thread named "async-process" that collects such "zombie" processes and then
/// "reaps" them, thus preventing the resource leaks.
///
/// The default value of this option is `true`.
///
/// # Examples
///
/// ```
/// use async_process::{Command, Stdio};
///
/// let mut cmd = Command::new("cat");
/// cmd.reap_on_drop(false);
/// ```
pub fn reap_on_drop(&mut self, reap_on_drop: bool) -> &mut Command {
self.inner.reap_on_drop(reap_on_drop);
self
}
/// Configures whether to kill the process when [`Child`] is dropped.
///
/// The default value of this option is `false`.
///
/// # Examples
///
/// ```
/// use async_process::{Command, Stdio};
///
/// let mut cmd = Command::new("cat");
/// cmd.kill_on_drop(true);
/// ```
pub fn kill_on_drop(&mut self, kill_on_drop: bool) -> &mut Command {
self.inner.kill_on_drop(kill_on_drop);
self
}
/// Executes the command and returns the [`Child`] handle to it.
///
/// If not configured, stdin, stdout and stderr will be set to [`Stdio::null()`].
///
/// # Examples
///
/// ```no_run
/// # futures_lite::future::block_on(async {
/// use async_process::Command;
///
/// let child = Command::new("ls").spawn()?;
/// # std::io::Result::Ok(()) });
/// ```
pub fn spawn(&mut self) -> io::Result<Child> {
if self.stdin_is_default {
self.inner.stdin(Stdio::null());
}
if self.stdout_is_default {
self.inner.stdout(Stdio::null());
}
if self.stderr_is_default {
self.inner.stderr(Stdio::null());
}
self.inner.spawn()
}
/// Executes the command, waits for it to exit, and returns the exit status.
///
/// If not configured, stdin, stdout and stderr will be set to [`Stdio::null()`].
///
/// # Examples
///
/// ```no_run
/// # futures_lite::future::block_on(async {
/// use async_process::Command;
///
/// let status = Command::new("cp")
/// .arg("a.txt")
/// .arg("b.txt")
/// .status()
/// .await?;
/// # std::io::Result::Ok(()) });
/// ```
pub fn status(&mut self) -> impl Future<Output = io::Result<ExitStatus>> {
if self.stdin_is_default {
self.inner.stdin(Stdio::null());
}
if self.stdout_is_default {
self.inner.stdout(Stdio::null());
}
if self.stderr_is_default {
self.inner.stderr(Stdio::null());
}
self.inner.status()
}
/// Executes the command and collects its output.
///
/// If not configured, stdin will be set to [`Stdio::null()`], and stdout and stderr will be
/// set to [`Stdio::piped()`].
///
/// # Examples
///
/// ```no_run
/// # futures_lite::future::block_on(async {
/// use async_process::Command;
///
/// let output = Command::new("cat")
/// .arg("a.txt")
/// .output()
/// .await?;
/// # std::io::Result::Ok(()) });
/// ```
pub fn output(&mut self) -> impl Future<Output = io::Result<Output>> {
if self.stdin_is_default {
self.inner.stdin(Stdio::null());
}
if self.stdout_is_default {
self.inner.stdout(Stdio::piped());
}
if self.stderr_is_default {
self.inner.stderr(Stdio::piped());
}
self.inner.output()
}
}