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
//! 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.0", 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, ValueError, ValueErrorKind};
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.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.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<(), ValueError> {
        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(ValueError::from(ValueErrorKind::ExpectedString {
                        actual: 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: self.inner.spawn()?,
        })
    }
}

struct Child {
    inner: process::Child,
}

impl Child {
    /// Convert the child into a future, use for `.await`.
    fn into_future(self) -> runestick::Future {
        runestick::Future::new(async move {
            let status = match self.inner.await {
                Ok(status) => status,
                Err(error) => return Ok(Err(error)),
            };

            Ok(Ok(ExitStatus { status }))
        })
    }

    // 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) -> io::Result<Output> {
        let inner = self.inner.wait_with_output().await?;

        Ok(Output {
            status: inner.status,
            stdout: Shared::new(Bytes::from_vec(inner.stdout)),
            stderr: Shared::new(Bytes::from_vec(inner.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)
    }
}

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