| 1 |
|
| 2 |
|
| 3 |
use log::{debug, trace}; |
| 4 |
use std::process::Output; |
| 5 |
use thiserror::Error; |
| 6 |
|
| 7 |
use crate::{command::Command, io::ProcessIo}; |
| 8 |
|
| 9 |
|
| 10 |
#[derive(Debug, Error)] |
| 11 |
pub enum SpawnThenWaitWithOutputError { |
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
#[error("Invalid argument: expected {0}, got {1:?}")] |
| 18 |
InvalidArgument(&'static str, ProcessIo), |
| 19 |
|
| 20 |
|
| 21 |
#[error("Command not initialized")] |
| 22 |
NotInitialized, |
| 23 |
} |
| 24 |
|
| 25 |
|
| 26 |
#[derive(Debug)] |
| 27 |
pub enum SpawnThenWaitWithOutputResult { |
| 28 |
|
| 29 |
Ok(Output), |
| 30 |
|
| 31 |
|
| 32 |
Io(ProcessIo), |
| 33 |
|
| 34 |
|
| 35 |
Err(SpawnThenWaitWithOutputError), |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
#[derive(Debug)] |
| 48 |
pub struct SpawnThenWaitWithOutput { |
| 49 |
cmd: Option<Command>, |
| 50 |
} |
| 51 |
|
| 52 |
impl SpawnThenWaitWithOutput { |
| 53 |
|
| 54 |
pub fn new(cmd: Command) -> Self { |
| 55 |
trace!("prepare command to be spawned: {cmd:?}"); |
| 56 |
let cmd = Some(cmd); |
| 57 |
Self { cmd } |
| 58 |
} |
| 59 |
|
| 60 |
|
| 61 |
pub fn resume(&mut self, arg: Option<ProcessIo>) -> SpawnThenWaitWithOutputResult { |
| 62 |
let Some(arg) = arg else { |
| 63 |
let Some(cmd) = self.cmd.take() else { |
| 64 |
return SpawnThenWaitWithOutputResult::Err( |
| 65 |
SpawnThenWaitWithOutputError::NotInitialized, |
| 66 |
); |
| 67 |
}; |
| 68 |
|
| 69 |
trace!("break: need I/O to spawn command"); |
| 70 |
return SpawnThenWaitWithOutputResult::Io(ProcessIo::SpawnThenWaitWithOutput(Err(cmd))); |
| 71 |
}; |
| 72 |
|
| 73 |
trace!("resume after spawning command"); |
| 74 |
|
| 75 |
let ProcessIo::SpawnThenWaitWithOutput(io) = arg else { |
| 76 |
let err = SpawnThenWaitWithOutputError::InvalidArgument("spawn output", arg); |
| 77 |
return SpawnThenWaitWithOutputResult::Err(err); |
| 78 |
}; |
| 79 |
|
| 80 |
let output = match io { |
| 81 |
Ok(output) => output, |
| 82 |
Err(cmd) => { |
| 83 |
let io = ProcessIo::SpawnThenWaitWithOutput(Err(cmd)); |
| 84 |
return SpawnThenWaitWithOutputResult::Io(io); |
| 85 |
} |
| 86 |
}; |
| 87 |
|
| 88 |
debug!("spawned command: {:?}", output.status); |
| 89 |
SpawnThenWaitWithOutputResult::Ok(output) |
| 90 |
} |
| 91 |
} |