-
Notifications
You must be signed in to change notification settings - Fork 11
/
process.rs
119 lines (102 loc) · 2.63 KB
/
process.rs
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
use std::{
ffi::{OsStr, OsString},
fmt::Debug,
io,
process::Stdio,
sync::Arc,
};
use async_trait::async_trait;
use tokio::io::AsyncRead;
pub mod fake;
pub mod os;
pub struct Command {
program: OsString,
args: Vec<OsString>,
envs: Vec<(OsString, OsString)>,
stdin: Option<Stdio>,
stdout: Option<Stdio>,
stderr: Option<Stdio>,
kill_on_drop: bool,
}
impl Command {
pub fn new<S>(program: S) -> Self
where
S: AsRef<OsStr>,
{
Self {
program: program.as_ref().to_os_string(),
args: vec![],
envs: vec![],
stdin: None,
stdout: None,
stderr: None,
kill_on_drop: false,
}
}
pub fn args<I, S>(mut self, args: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
self.args = args
.into_iter()
.map(|arg| arg.as_ref().to_os_string())
.collect();
self
}
pub fn envs<I, K, V>(mut self, vars: I) -> Self
where
I: IntoIterator<Item = (K, V)>,
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
self.envs = vars
.into_iter()
.map(|(key, val)| (key.as_ref().to_os_string(), val.as_ref().to_os_string()))
.collect();
self
}
pub fn stdin<T>(mut self, cfg: T) -> Self
where
T: Into<Stdio>,
{
self.stdin = Some(cfg.into());
self
}
pub fn stdout<T>(mut self, cfg: T) -> Self
where
T: Into<Stdio>,
{
self.stdout = Some(cfg.into());
self
}
pub fn stderr<T>(mut self, cfg: T) -> Self
where
T: Into<Stdio>,
{
self.stderr = Some(cfg.into());
self
}
pub fn kill_on_drop(mut self, kill_on_drop: bool) -> Self {
self.kill_on_drop = kill_on_drop;
self
}
}
pub type DynAsyncRead = Box<dyn AsyncRead + Send + Unpin>;
#[async_trait]
pub trait Process: Debug {
async fn id(&self) -> Option<u32>;
async fn take_stdout(&self) -> Option<DynAsyncRead>;
async fn take_stderr(&self) -> Option<DynAsyncRead>;
async fn kill(&self) -> io::Result<()>;
}
pub type DynProcess = Arc<dyn Process + Send + Sync>;
#[async_trait]
pub trait ProcessManager {
async fn spawn(&self, command: Command) -> io::Result<DynProcess>;
async fn output(&self, command: Command) -> io::Result<std::process::Output>;
async fn kill<T>(&self, pid: nix::unistd::Pid, signal: T) -> nix::Result<()>
where
T: Into<Option<nix::sys::signal::Signal>> + Send;
}
pub type DynProcessManager = Arc<dyn Process + Send + Sync>;