rune-modules 0.14.1

Native modules for Rune, an embeddable dynamic programming language for Rust.
Documentation
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
//! The native `process` module for the [Rune Language].
//!
//! [Rune Language]: https://rune-rs.github.io
//!
//! ## Usage
//!
//! Add the following to your `Cargo.toml`:
//!
//! ```toml
//! rune-modules = { version = "0.14.1", features = ["process"] }
//! ```
//!
//! Install it into your context:
//!
//! ```rust
//! let mut context = rune::Context::with_default_modules()?;
//! context.install(rune_modules::process::module(true)?)?;
//! # Ok::<_, rune::support::Error>(())
//! ```
//!
//! Use it in Rune:
//!
//! ```rust,ignore
//! use process::Command;
//!
//! fn main() {
//!     let command = Command::new("ls");
//!     command.run().await;
//! }
//! ```

// Documentation copied from the Tokio project under the MIT license.
// See: https://github.com/tokio-rs/tokio/blob/master/LICENSE

use rune::alloc::clone::TryClone;
use rune::alloc::fmt::TryWrite;
use rune::alloc::Vec;
use rune::runtime::{Bytes, Formatter, Mut, Value, VmResult};
use rune::{vm_try, vm_write, Any, ContextError, Module};

use std::io;
use tokio::process;

/// A module for working with processes.
///
/// This allows spawning child processes, capturing their output, and creating
/// pipelines.
///
/// # Tokio
///
/// This function is implemented using [Tokio], and requires the Tokio runtime
/// to be in scope.
///
/// [Tokio]: https://tokio.rs
#[rune::module(::process)]
pub fn module(_stdio: bool) -> Result<Module, ContextError> {
    let mut module = Module::from_meta(self::module_meta)?;

    module.ty::<Command>()?;
    module.function_meta(Command::new__meta)?;
    module.function_meta(Command::arg__meta)?;
    module.function_meta(Command::args__meta)?;
    module.function_meta(Command::debug_fmt__meta)?;
    #[cfg(unix)]
    module.function_meta(Command::arg0__meta)?;
    module.function_meta(Command::stdin__meta)?;
    module.function_meta(Command::stdout__meta)?;
    module.function_meta(Command::stderr__meta)?;
    module.function_meta(Command::kill_on_drop__meta)?;
    module.function_meta(Command::spawn__meta)?;

    module.ty::<Child>()?;
    module.function_meta(Child::debug_fmt__meta)?;
    module.function_meta(Child::stdin__meta)?;
    module.function_meta(Child::stdout__meta)?;
    module.function_meta(Child::stderr__meta)?;
    module.function_meta(Child::id__meta)?;
    module.function_meta(Child::start_kill__meta)?;
    module.function_meta(Child::kill__meta)?;
    module.function_meta(Child::wait__meta)?;
    module.function_meta(Child::wait_with_output__meta)?;

    module.ty::<ExitStatus>()?;
    module.function_meta(ExitStatus::code__meta)?;
    module.function_meta(ExitStatus::success__meta)?;
    module.function_meta(ExitStatus::display_fmt__meta)?;
    module.function_meta(ExitStatus::debug_fmt__meta)?;

    module.ty::<Output>()?;
    module.function_meta(Output::debug_fmt__meta)?;

    module.ty::<Stdio>()?;
    module.function_meta(Stdio::null__meta)?;
    module.function_meta(Stdio::inherit__meta)?;
    module.function_meta(Stdio::piped__meta)?;
    module.function_meta(Stdio::debug_fmt__meta)?;

    module.ty::<ChildStdin>()?;
    module.function_meta(ChildStdin::debug_fmt__meta)?;
    module.function_meta(ChildStdin::try_into_stdio__meta)?;

    module.ty::<ChildStdout>()?;
    module.function_meta(ChildStdout::debug_fmt__meta)?;
    module.function_meta(ChildStdout::try_into_stdio__meta)?;

    module.ty::<ChildStderr>()?;
    module.function_meta(ChildStderr::debug_fmt__meta)?;
    module.function_meta(ChildStderr::try_into_stdio__meta)?;

    Ok(module)
}

/// This structure mimics the API of [`std::process::Command`] found in the
/// standard library, but replaces functions that create a process with an
/// asynchronous variant. The main provided asynchronous functions are
/// [spawn](Command::spawn), [status](Command::status), and
/// [output](Command::output).
///
/// `Command` uses asynchronous versions of some `std` types (for example
/// [`Child`]).
///
/// [`std::process::Command`]:
///     https://doc.rust-lang.org/std/process/struct.Command.html
/// [`Child`]: struct@Child
#[derive(Debug, Any)]
#[rune(item = ::process)]
struct Command {
    inner: process::Command,
}

impl Command {
    /// Constructs a new `Command` for launching the program at path `program`,
    /// with the following default configuration:
    ///
    /// * No arguments to the program
    /// * Inherit the current process's environment
    /// * Inherit the current process's working directory
    /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes
    ///   for `output`
    ///
    /// Builder methods are provided to change these defaults and otherwise
    /// configure the process.
    ///
    /// If `program` is not an absolute path, the `PATH` will be searched in an
    /// OS-defined way.
    ///
    /// The search path to be used may be controlled by setting the `PATH`
    /// environment variable on the Command, but this has some implementation
    /// limitations on Windows (see issue [rust-lang/rust#37519]).
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```rune,no_run
    /// use process::Command;
    /// let command = Command::new("sh");
    /// ```
    ///
    /// [rust-lang/rust#37519]: https://github.com/rust-lang/rust/issues/37519
    #[rune::function(keep, path = Self::new)]
    fn new(command: &str) -> Self {
        Self {
            inner: process::Command::new(command),
        }
    }

    /// Adds an argument to pass to the program.
    ///
    /// Only one argument can be passed per use. So instead of:
    ///
    /// ```rune,no_run
    /// use process::Command;
    ///
    /// let command = Command::new("sh");
    /// command.arg("-C /path/to/repo");
    /// ```
    ///
    /// usage would be:
    ///
    /// ```rune,no_run
    /// use process::Command;
    ///
    /// let command = Command::new("sh");
    /// command.arg("-C");
    /// command.arg("/path/to/repo");
    /// ```
    ///
    /// To pass multiple arguments see [`args`].
    ///
    /// [`args`]: method@Self::args
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```rune,no_run
    /// use process::Command;
    ///
    /// let command = Command::new("ls");
    /// command.arg("-l");
    /// command.arg("-a");
    ///
    /// let output = command.output().await?;
    /// ```
    #[rune::function(keep, instance)]
    fn arg(&mut self, arg: &str) {
        self.inner.arg(arg);
    }

    /// Adds multiple arguments to pass to the program.
    ///
    /// To pass a single argument see [`arg`].
    ///
    /// [`arg`]: method@Self::arg
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```rune,no_run
    /// use process::Command;
    ///
    /// let command = Command::new("ls");
    /// command.args(["-l", "-a"]);
    ///
    /// let output = command.output().await?;
    /// ```
    #[rune::function(keep, instance)]
    fn args(&mut self, args: &[Value]) -> VmResult<()> {
        for arg in args {
            self.inner.arg(&*vm_try!(arg.borrow_string_ref()));
        }

        VmResult::Ok(())
    }

    /// Sets executable argument.
    ///
    /// Set the first process argument, `argv[0]`, to something other than the
    /// default executable path.
    #[cfg(unix)]
    #[rune::function(keep, instance)]
    fn arg0(&mut self, arg: &str) {
        self.inner.arg0(arg);
    }

    /// Sets configuration for the child process's standard input (stdin)
    /// handle.
    ///
    /// Defaults to [`inherit`].
    ///
    /// [`inherit`]: process::Stdio::inherit
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```rune,no_run
    /// use process::{Command, Stdio};
    ///
    /// let command = Command::new("ls");
    /// command.stdin(Stdio::null());
    ///
    /// let output = command.output().await?;
    /// ```
    #[rune::function(keep, instance)]
    fn stdin(&mut self, stdio: Stdio) {
        self.inner.stdin(stdio.inner);
    }

    /// Sets configuration for the child process's standard output (stdout)
    /// handle.
    ///
    /// Defaults to [`inherit`] when used with `spawn` or `status`, and defaults
    /// to [`piped`] when used with `output`.
    ///
    /// [`inherit`]: process::Stdio::inherit
    /// [`piped`]: process::Stdio::piped
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```rune,no_run
    /// use process::{Command, Stdio};
    ///
    /// let command = Command::new("ls");
    /// command.stdout(Stdio::null());
    ///
    /// let output = command.output().await?;
    /// ```
    #[rune::function(keep, instance)]
    fn stdout(&mut self, stdio: Stdio) {
        self.inner.stdout(stdio.inner);
    }

    /// Sets configuration for the child process's standard error (stderr)
    /// handle.
    ///
    /// Defaults to [`inherit`] when used with `spawn` or `status`, and defaults
    /// to [`piped`] when used with `output`.
    ///
    /// [`inherit`]: process::Stdio::inherit
    /// [`piped`]: process::Stdio::piped
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```rune,no_run
    /// use process::{Command, Stdio};
    ///
    /// let command = Command::new("ls");
    /// command.stderr(Stdio::null());
    ///
    /// let output = command.output().await?;
    /// ```
    #[rune::function(keep, instance)]
    fn stderr(&mut self, stdio: Stdio) {
        self.inner.stderr(stdio.inner);
    }

    /// Controls whether a `kill` operation should be invoked on a spawned child
    /// process when its corresponding `Child` handle is dropped.
    ///
    /// By default, this value is assumed to be `false`, meaning the next
    /// spawned process will not be killed on drop, similar to the behavior of
    /// the standard library.
    ///
    /// # Caveats
    ///
    /// On Unix platforms processes must be "reaped" by their parent process
    /// after they have exited in order to release all OS resources. A child
    /// process which has exited, but has not yet been reaped by its parent is
    /// considered a "zombie" process. Such processes continue to count against
    /// limits imposed by the system, and having too many zombie processes
    /// present can prevent additional processes from being spawned.
    ///
    /// Although issuing a `kill` signal to the child process is a synchronous
    /// operation, the resulting zombie process cannot be `.await`ed inside of
    /// the destructor to avoid blocking other tasks. The tokio runtime will, on
    /// a best-effort basis, attempt to reap and clean up such processes in the
    /// background, but no additional guarantees are made with regard to how
    /// quickly or how often this procedure will take place.
    ///
    /// If stronger guarantees are required, it is recommended to avoid dropping
    /// a [`Child`] handle where possible, and instead utilize
    /// `child.wait().await` or `child.kill().await` where possible.
    #[rune::function(keep, instance)]
    pub fn kill_on_drop(&mut self, kill_on_drop: bool) {
        self.inner.kill_on_drop(kill_on_drop);
    }

    /// Executes the command as a child process, returning a handle to it.
    ///
    /// By default, stdin, stdout and stderr are inherited from the parent.
    ///
    /// This method will spawn the child process synchronously and return a
    /// handle to a future-aware child process. The `Child` returned implements
    /// `Future` itself to acquire the `ExitStatus` of the child, and otherwise
    /// the `Child` has methods to acquire handles to the stdin, stdout, and
    /// stderr streams.
    ///
    /// All I/O this child does will be associated with the current default
    /// event loop.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```rune,no_run
    /// use process::Command;
    ///
    /// async fn run_ls() {
    ///     let command = Command::new("ls");
    ///     command.spawn()?.wait().await?;
    /// }
    /// ```
    ///
    /// # Caveats
    ///
    /// ## Dropping/Cancellation
    ///
    /// Similar to the behavior to the standard library, and unlike the futures
    /// paradigm of dropping-implies-cancellation, a spawned process will, by
    /// default, continue to execute even after the `Child` handle has been
    /// dropped.
    ///
    /// The [`Command::kill_on_drop`] method can be used to modify this behavior
    /// and kill the child process if the `Child` wrapper is dropped before it
    /// has exited.
    ///
    /// ## Unix Processes
    ///
    /// On Unix platforms processes must be "reaped" by their parent process
    /// after they have exited in order to release all OS resources. A child
    /// process which has exited, but has not yet been reaped by its parent is
    /// considered a "zombie" process. Such processes continue to count against
    /// limits imposed by the system, and having too many zombie processes
    /// present can prevent additional processes from being spawned.
    ///
    /// The tokio runtime will, on a best-effort basis, attempt to reap and
    /// clean up any process which it has spawned. No additional guarantees are
    /// made with regard to how quickly or how often this procedure will take
    /// place.
    ///
    /// It is recommended to avoid dropping a [`Child`] process handle before it
    /// has been fully `await`ed if stricter cleanup guarantees are required.
    ///
    /// [`Command`]: crate::process::Command
    /// [`Command::kill_on_drop`]: crate::process::Command::kill_on_drop
    /// [`Child`]: crate::process::Child
    ///
    /// # Errors
    ///
    /// On Unix platforms this method will fail with
    /// `std::io::ErrorKind::WouldBlock` if the system process limit is reached
    /// (which includes other applications running on the system).
    #[rune::function(keep, instance)]
    fn spawn(&mut self) -> io::Result<Child> {
        Ok(Child {
            inner: self.inner.spawn()?,
        })
    }

    #[rune::function(keep, protocol = DEBUG_FMT)]
    fn debug_fmt(&self, f: &mut Formatter) -> VmResult<()> {
        vm_write!(f, "{self:?}")
    }
}

/// Representation of a child process spawned onto an event loop.
///
/// # Caveats
///
/// Similar to the behavior to the standard library, and unlike the futures
/// paradigm of dropping-implies-cancellation, a spawned process will, by
/// default, continue to execute even after the `Child` handle has been dropped.
///
/// The `Command::kill_on_drop` method can be used to modify this behavior and
/// kill the child process if the `Child` wrapper is dropped before it has
/// exited.
#[derive(Debug, Any)]
#[rune(item = ::process)]
struct Child {
    // we use an option to avoid a panic if we try to complete the child process
    // multiple times.
    inner: process::Child,
}

impl Child {
    /// The handle for writing to the child's standard input (stdin), if it has
    /// been captured. To avoid partially moving the `child` and thus blocking
    /// yourself from calling functions on `child` while using `stdin`, you
    /// might find it helpful to do:
    ///
    /// ```rune,no_run
    /// # let child = #{};
    /// let stdin = child.stdin()?;
    /// ```
    #[rune::function(keep, instance)]
    fn stdin(&mut self) -> Option<ChildStdin> {
        let inner = self.inner.stdin.take()?;
        Some(ChildStdin { inner })
    }

    /// The handle for reading from the child's standard output (stdout), if it
    /// has been captured. You might find it helpful to do
    ///
    /// ```rune,no_run
    /// # let child = #{};
    /// let stdout = child.stdout.take()?;
    /// ```
    ///
    /// to avoid partially moving the `child` and thus blocking yourself from
    /// calling functions on `child` while using `stdout`.
    #[rune::function(keep, instance)]
    fn stdout(&mut self) -> Option<ChildStdout> {
        let inner = self.inner.stdout.take()?;
        Some(ChildStdout { inner })
    }

    /// The handle for reading from the child's standard error (stderr), if it
    /// has been captured. You might find it helpful to do
    ///
    /// ```rune,no_run
    /// # let child = #{};
    /// let stderr = child.stderr()?;
    /// ```
    ///
    /// to avoid partially moving the `child` and thus blocking yourself from
    /// calling functions on `child` while using `stderr`.
    #[rune::function(keep, instance)]
    fn stderr(&mut self) -> Option<ChildStderr> {
        let inner = self.inner.stderr.take()?;
        Some(ChildStderr { inner })
    }

    /// Returns the OS-assigned process identifier associated with this child
    /// while it is still running.
    ///
    /// Once the child has been polled to completion this will return `None`.
    /// This is done to avoid confusion on platforms like Unix where the OS
    /// identifier could be reused once the process has completed.
    #[rune::function(keep, instance)]
    fn id(&self) -> Option<u32> {
        self.inner.id()
    }

    /// Attempts to force the child to exit, but does not wait for the request
    /// to take effect.
    ///
    /// On Unix platforms, this is the equivalent to sending a `SIGKILL`. Note
    /// that on Unix platforms it is possible for a zombie process to remain
    /// after a kill is sent; to avoid this, the caller should ensure that
    /// either `child.wait().await` or `child.try_wait()` is invoked
    /// successfully.
    #[rune::function(keep, instance)]
    fn start_kill(&mut self) -> io::Result<()> {
        self.inner.start_kill()
    }

    /// Forces the child to exit.
    ///
    /// This is equivalent to sending a `SIGKILL` on unix platforms.
    ///
    /// If the child has to be killed remotely, it is possible to do it using a
    /// combination of the select! macro and a `oneshot` channel. In the
    /// following example, the child will run until completion unless a message
    /// is sent on the `oneshot` channel. If that happens, the child is killed
    /// immediately using the `.kill()` method.
    ///
    /// ```rune,no_run
    /// use process::Command;
    /// # async fn wait_for_something() {}
    ///
    /// let child = Command::new("sleep");
    /// child.arg("1");
    ///
    /// let child = child.spawn();
    ///
    /// let recv = wait_for_something();
    ///
    /// select {
    ///     _ = child.wait() => {}
    ///     _ = recv => child.kill().await.expect("kill failed"),
    /// }
    /// ```
    #[rune::function(keep, instance, path = Self::kill)]
    async fn kill(mut this: Mut<Self>) -> io::Result<()> {
        this.inner.kill().await
    }

    /// Waits for the child to exit completely, returning the status that it
    /// exited with. This function will continue to have the same return value
    /// after it has been called at least once.
    ///
    /// The stdin handle to the child process, if any, will be closed
    /// before waiting. This helps avoid deadlock: it ensures that the
    /// child does not block waiting for input from the parent, while
    /// the parent waits for the child to exit.
    ///
    /// If the caller wishes to explicitly control when the child's stdin
    /// handle is closed, they may `.take()` it before calling `.wait()`:
    ///
    /// # Cancel safety
    ///
    /// This function is cancel safe.
    ///
    /// ```rune,no_run
    /// use process::{Command, Stdio};
    ///
    /// let child = Command::new("cat");
    /// child.stdin(Stdio::piped());
    ///
    /// let child = child.spawn()?;
    ///
    /// let stdin = child.stdin()?;
    ///
    /// // wait for the process to complete
    /// let _ = child.wait().await?;
    /// ```
    #[rune::function(keep, instance, path = Self::wait)]
    async fn wait(mut this: Mut<Self>) -> io::Result<ExitStatus> {
        let inner = this.inner.wait().await?;
        Ok(ExitStatus { inner })
    }

    /// Returns a future that will resolve to an `Output`, containing the exit
    /// status, stdout, and stderr of the child process.
    ///
    /// The returned future will simultaneously waits for the child to exit and
    /// collect all remaining output on the stdout/stderr handles, returning an
    /// `Output` instance.
    ///
    /// The stdin handle to the child process, if any, will be closed before
    /// waiting. This helps avoid deadlock: it ensures that the child does not
    /// block waiting for input from the parent, while the parent waits for the
    /// child to exit.
    ///
    /// By default, stdin, stdout and stderr are inherited from the parent. In
    /// order to capture the output into this `Output` it is necessary to create
    /// new pipes between parent and child. Use `stdout(Stdio::piped())` or
    /// `stderr(Stdio::piped())`, respectively, when creating a `Command`.
    #[rune::function(keep, vm_result, instance)]
    async fn wait_with_output(self) -> io::Result<Output> {
        let output = self.inner.wait_with_output().await?;

        Ok(Output {
            status: ExitStatus {
                inner: output.status,
            },
            stdout: Value::new(Bytes::from_vec(Vec::try_from(output.stdout).vm?)).vm?,
            stderr: Value::new(Bytes::from_vec(Vec::try_from(output.stderr).vm?)).vm?,
        })
    }

    #[rune::function(keep, protocol = DEBUG_FMT)]
    fn debug_fmt(&self, f: &mut Formatter) -> VmResult<()> {
        vm_write!(f, "{:?}", self.inner)
    }
}

/// The output of a finished process.
///
/// This is returned in a Result by either the [`output`] method of a
/// [`Command`], or the [`wait_with_output`] method of a [`Child`] process.
///
/// [`output`]: Command::output
/// [`wait_with_output`]: Child::wait_with_output
#[derive(Debug, Any)]
#[rune(item = ::process)]
struct Output {
    /// The status (exit code) of the process.
    #[rune(get, copy)]
    status: ExitStatus,
    /// The data that the process wrote to stdout.
    #[rune(get)]
    stdout: Value,
    /// The data that the process wrote to stderr.
    #[rune(get)]
    stderr: Value,
}

impl Output {
    #[rune::function(keep, protocol = DEBUG_FMT)]
    fn debug_fmt(&self, f: &mut Formatter) -> VmResult<()> {
        vm_write!(f, "{self:?}")
    }
}

/// The exit status from a completed child process
#[derive(Debug, TryClone, Clone, Copy, Any)]
#[rune(item = ::process)]
struct ExitStatus {
    inner: std::process::ExitStatus,
}

impl ExitStatus {
    /// Was termination successful? Signal termination is not considered a
    /// success, and success is defined as a zero exit status.
    ///
    /// # Examples
    ///
    /// ```rune,no_run
    /// use process::Command;
    ///
    /// let command = Command::new("mkdir");
    /// command.arg("projects");
    ///
    /// let status = command.status()?;
    ///
    /// if status.success() {
    ///     println!("'projects/' directory created");
    /// } else {
    ///     println!("failed to create 'projects/' directory: {status}");
    /// }
    /// ```
    #[rune::function(keep)]
    fn success(&self) -> bool {
        self.inner.success()
    }

    /// Returns the exit code of the process, if any.
    ///
    /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the
    /// process finished by calling `exit`.  Note that on Unix the exit status is truncated to 8
    /// bits, and that values that didn't come from a program's call to `exit` may be invented by the
    /// runtime system (often, for example, 255, 254, 127 or 126).
    ///
    /// On Unix, this will return `None` if the process was terminated by a signal.
    /// [`ExitStatusExt`](crate::os::unix::process::ExitStatusExt) is an
    /// extension trait for extracting any such signal, and other details, from the `ExitStatus`.
    ///
    /// # Examples
    ///
    /// ```rune,no_run
    /// use process::Command;
    ///
    /// let command = Command::new("mkdir");
    /// command.arg("projects");
    ///
    /// let status = command.status().await?;
    ///
    /// match status.code() {
    ///     Some(code) => println!("Exited with status code: {code}"),
    ///     None => println!("Process terminated by signal")
    /// }
    /// ```
    #[rune::function(keep)]
    fn code(&self) -> Option<i32> {
        self.inner.code()
    }

    #[rune::function(keep, protocol = DISPLAY_FMT)]
    fn display_fmt(&self, f: &mut Formatter) -> VmResult<()> {
        vm_write!(f, "{}", self.inner)
    }

    #[rune::function(keep, protocol = DEBUG_FMT)]
    fn debug_fmt(&self, f: &mut Formatter) -> VmResult<()> {
        vm_write!(f, "{:?}", self.inner)
    }
}

/// Describes what to do with a standard I/O stream for a child process when passed to the stdin, stdout, and stderr methods of Command.
#[derive(Debug, Any)]
#[rune(item = ::process)]
struct Stdio {
    inner: std::process::Stdio,
}

impl Stdio {
    /// This stream will be ignored. This is the equivalent of attaching the stream to /dev/null.
    #[rune::function(keep, path = Self::null)]
    fn null() -> Self {
        Self {
            inner: std::process::Stdio::null(),
        }
    }

    /// The child inherits from the corresponding parent descriptor. This is the default.
    #[rune::function(keep, path = Self::inherit)]
    fn inherit() -> Self {
        Self {
            inner: std::process::Stdio::inherit(),
        }
    }

    /// A new pipe should be arranged to connect the parent and child processes.
    #[rune::function(keep, path = Self::piped)]
    fn piped() -> Self {
        Self {
            inner: std::process::Stdio::piped(),
        }
    }

    #[rune::function(keep, protocol = DEBUG_FMT)]
    fn debug_fmt(&self, f: &mut Formatter) -> VmResult<()> {
        vm_write!(f, "{:?}", self.inner)
    }
}

macro_rules! stdio_stream {
    ($name:ident, $stream:tt) => {
        #[derive(Debug, Any)]
        #[rune(item = ::process)]
        #[doc = concat!("The ", $stream, " stream for spawned children.")]
        struct $name {
            inner: process::$name,
        }

        impl $name {
            /// Try to convert into a `Stdio`, which allows creating a pipeline between processes.
            ///
            /// This consumes the stream, as it can only be used once.
            ///
            /// Returns a Result<Stdio>
            #[rune::function(keep, instance)]
            fn try_into_stdio(self) -> io::Result<Stdio> {
                Ok(Stdio {
                    inner: self.inner.try_into()?,
                })
            }

            #[rune::function(keep, protocol = DEBUG_FMT)]
            fn debug_fmt(&self, f: &mut Formatter) -> VmResult<()> {
                vm_write!(f, "{:?}", self.inner)
            }
        }
    };
}
stdio_stream!(ChildStdin, "stdin");
stdio_stream!(ChildStdout, "stdout");
stdio_stream!(ChildStderr, "stderr");