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
//! The native `process` module for the [Rune Language].
//!
//! [Rune Language]: https://github.com/rune-rs/rune
//!
//! ## Usage
//!
//! Add the following to your `Cargo.toml`:
//!
//! ```toml
//! rune-modules = {version = "0.6.14", features = ["process"]}
//! ```
//!
//! Install it into your context:
//!
//! ```rust
//! # fn main() -> runestick::Result<()> {
//! let mut context = runestick::Context::with_default_modules()?;
//! context.install(&rune_modules::process::module()?)?;
//! # Ok(())
//! # }
//! ```
//!
//! Use it in Rune:
//!
//! ```rust,ignore
//! use process::Command;
//!
//! fn main() {
//!     let command = Command::new("ls");
//!     command.run().await;
//! }
//! ```

use runestick::{Bytes, Shared, Value, VmError};
use std::fmt;
use std::io;
use tokio::process;

/// Construct the `process` module.
pub fn module() -> Result<runestick::Module, runestick::ContextError> {
    let mut module = runestick::Module::new(&["process"]);
    module.ty(&["Command"]).build::<Command>()?;
    module.ty(&["Child"]).build::<Child>()?;
    module.ty(&["ExitStatus"]).build::<ExitStatus>()?;
    module.ty(&["Output"]).build::<Output>()?;

    module.function(&["Command", "new"], Command::new)?;
    module.inst_fn("spawn", Command::spawn)?;
    module.inst_fn("arg", Command::arg)?;
    module.inst_fn("args", Command::args)?;
    module.async_inst_fn(runestick::INTO_FUTURE, Child::into_future)?;
    module.async_inst_fn("wait_with_output", Child::wait_with_output)?;
    module.inst_fn(runestick::STRING_DISPLAY, ExitStatus::display)?;
    module.inst_fn("code", ExitStatus::code)?;

    module.getter("status", Output::status)?;
    module.getter("stdout", Output::stdout)?;
    module.getter("stderr", Output::stderr)?;
    Ok(module)
}

struct Command {
    inner: process::Command,
}

impl Command {
    /// Construct a new command.
    fn new(command: &str) -> Self {
        Self {
            inner: process::Command::new(command),
        }
    }

    /// Add arguments.
    fn args(&mut self, args: &[Value]) -> Result<(), VmError> {
        for arg in args {
            match arg {
                Value::String(s) => {
                    self.inner.arg(&*s.borrow_ref()?);
                }
                Value::StaticString(s) => {
                    self.inner.arg(&***s);
                }
                actual => {
                    return Err(VmError::expected::<String>(actual.type_info()?));
                }
            }
        }

        Ok(())
    }

    /// Add an argument.
    fn arg(&mut self, arg: &str) {
        self.inner.arg(arg);
    }

    /// Spawn the command.
    fn spawn(mut self) -> io::Result<Child> {
        Ok(Child {
            inner: Some(self.inner.spawn()?),
        })
    }
}

struct Child {
    // we use an option to avoid a panic if we try to complete the child process
    // multiple times.
    //
    // TODO: enapculate this pattern in some better way.
    inner: Option<process::Child>,
}

impl Child {
    /// Convert the child into a future, use for `.await`.
    async fn into_future(&mut self) -> Result<io::Result<ExitStatus>, VmError> {
        let result = match &mut self.inner {
            Some(inner) => match inner.await {
                Ok(status) => Ok(ExitStatus { status }),
                Err(e) => Err(e),
            },
            None => {
                return Err(VmError::panic("already completed"));
            }
        };

        self.inner = None;
        Ok(result)
    }

    // Returns a future that will resolve to an Output, containing the exit
    // status, stdout, and stderr of the child process.
    async fn wait_with_output(self) -> Result<io::Result<Output>, VmError> {
        let inner = match self.inner {
            Some(inner) => inner,
            None => {
                return Err(VmError::panic("already completed"));
            }
        };

        let output = match inner.wait_with_output().await {
            Ok(output) => output,
            Err(error) => return Ok(Err(error)),
        };

        Ok(Ok(Output {
            status: output.status,
            stdout: Shared::new(Bytes::from_vec(output.stdout)),
            stderr: Shared::new(Bytes::from_vec(output.stderr)),
        }))
    }
}

struct Output {
    status: std::process::ExitStatus,
    stdout: Shared<Bytes>,
    stderr: Shared<Bytes>,
}

impl Output {
    /// Get the exist status of the process.
    fn status(&self) -> ExitStatus {
        ExitStatus {
            status: self.status,
        }
    }

    /// Grab the stdout of the process.
    fn stdout(&mut self) -> Shared<Bytes> {
        self.stdout.clone()
    }

    /// Grab the stderr of the process.
    fn stderr(&mut self) -> Shared<Bytes> {
        self.stderr.clone()
    }
}

struct ExitStatus {
    status: std::process::ExitStatus,
}

impl ExitStatus {
    fn display(&self, buf: &mut String) -> fmt::Result {
        use std::fmt::Write as _;
        write!(buf, "{}", self.status)
    }

    fn code(&self) -> Option<i32> {
        self.status.code()
    }
}

runestick::impl_external!(Command);
runestick::impl_external!(Child);
runestick::impl_external!(ExitStatus);
runestick::impl_external!(Output);