artifactize_foundation/platform/
process.rs1use std::{
3 ffi::{OsStr, OsString},
4 io,
5 path::{Path, PathBuf},
6 process::Stdio,
7 time::Duration,
8};
9use tokio::{process::Command, time::sleep};
10
11#[cfg(unix)]
12mod unix;
13#[cfg(windows)]
14mod windows;
15#[cfg(unix)]
16use unix as native;
17#[cfg(unix)]
18pub use unix::*;
19#[cfg(windows)]
20use windows as native;
21#[cfg(windows)]
22pub use windows::*;
23
24pub async fn spawn_verified(launch: super::executable::Launch<'_>) -> io::Result<Child> {
26 launch.spawn().await
27}
28
29pub struct ResolvedCommand {
33 command: Command,
34 binding: self::native::Binding,
35}
36
37impl ResolvedCommand {
38 pub fn as_std(&self) -> &std::process::Command {
39 self.command.as_std()
40 }
41
42 pub fn current_dir(&mut self, dir: impl AsRef<Path>) -> &mut Self {
43 self.command.current_dir(dir);
44 self
45 }
46
47 pub fn env_clear(&mut self) -> &mut Self {
48 self.command.env_clear();
49 self
50 }
51
52 pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Self {
53 self.command.env(key, value);
54 self
55 }
56
57 pub fn envs<K, V>(&mut self, vars: impl IntoIterator<Item = (K, V)>) -> &mut Self
58 where
59 K: AsRef<OsStr>,
60 V: AsRef<OsStr>,
61 {
62 self.command.envs(vars);
63 self
64 }
65
66 pub fn stdin(&mut self, config: impl Into<Stdio>) -> &mut Self {
67 self.command.stdin(config);
68 self
69 }
70
71 pub fn stdout(&mut self, config: impl Into<Stdio>) -> &mut Self {
72 self.command.stdout(config);
73 self
74 }
75
76 pub fn stderr(&mut self, config: impl Into<Stdio>) -> &mut Self {
77 self.command.stderr(config);
78 self
79 }
80
81 pub fn kill_on_drop(&mut self, enabled: bool) -> &mut Self {
82 self.command.kill_on_drop(enabled);
83 self
84 }
85
86 pub fn hide_console_window(&mut self) -> &mut Self {
87 hide_console_window(self.command.as_std_mut());
88 self
89 }
90}
91
92pub struct Program {
94 path: PathBuf,
95 canonical: PathBuf,
96}
97
98impl Program {
99 fn resolve(path: PathBuf) -> io::Result<Self> {
100 if !path.is_absolute() {
101 return Err(io::Error::new(
102 io::ErrorKind::InvalidInput,
103 "launch requires a resolved absolute program",
104 ));
105 }
106 let canonical = std::fs::canonicalize(&path)?;
107 Ok(Self { path, canonical })
108 }
109
110 pub fn path(&self) -> &Path {
112 &self.path
113 }
114
115 pub fn canonical_path(&self) -> &Path {
117 &self.canonical
118 }
119}
120
121pub fn resolve_with(
124 program: &Path,
125 cwd: &Path,
126 variable: impl Fn(&str) -> Option<OsString>,
127) -> io::Result<Program> {
128 Program::resolve(super::program::resolve_with(program, cwd, variable)?)
129}
130
131pub fn resolved_command(
136 program: &Path,
137 args: impl IntoIterator<Item = impl AsRef<OsStr>>,
138) -> io::Result<ResolvedCommand> {
139 Program::resolve(program.to_owned())?.command(args)
140}
141
142mod outcome;
143pub use outcome::{ProcessEnd, ProcessOutcome};
144
145const CLEANUP_GRACE: Duration = Duration::from_secs(1);
147
148#[derive(
152 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
153)]
154#[serde(transparent)]
155pub struct ProcessId(std::num::NonZeroU32);
156
157impl ProcessId {
158 pub fn new(pid: u32) -> Self {
160 Self(std::num::NonZeroU32::new(pid).expect("a real process id is never 0"))
161 }
162
163 pub fn get(self) -> u32 {
164 self.0.get()
165 }
166}
167
168impl From<std::num::NonZeroU32> for ProcessId {
169 fn from(pid: std::num::NonZeroU32) -> Self {
170 Self(pid)
171 }
172}
173
174impl std::fmt::Display for ProcessId {
175 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176 self.0.fmt(f)
177 }
178}
179
180#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
182pub struct ChildIdentity {
183 pub pid: ProcessId,
184 pub start_time: u64,
187}
188
189pub fn child_identity(pid: u32) -> io::Result<ChildIdentity> {
190 let start_time = process_start_time(pid)?;
191 Ok(ChildIdentity {
192 pid: ProcessId::new(pid),
193 start_time,
194 })
195}
196
197pub fn is_alive(owner: Option<ChildIdentity>) -> io::Result<bool> {
200 let Some(owner) = owner else {
201 return Ok(false);
202 };
203 match running_process_start_time(owner.pid.get()) {
204 Ok(start_time) => Ok(start_time == owner.start_time),
205 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
206 Err(error) => Err(error),
207 }
208}
209
210pub async fn terminate(child: &mut Child) -> io::Result<()> {
211 let _ = child.interrupt();
212 tokio::select! {
213 _ = sleep(CLEANUP_GRACE) => {},
214 _ = child.wait() => {},
215 }
216 child.cleanup().await?;
217 Ok(())
218}
219
220#[cfg(test)]
221mod tests;