subprocess 1.0.3

Execution and control of child processes and pipelines.
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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
#[cfg(unix)]
mod os {
    pub const SHELL: [&str; 2] = ["sh", "-c"];
}

#[cfg(windows)]
mod os {
    pub const SHELL: [&str; 2] = ["cmd.exe", "/c"];
}

use crate::communicate::Communicator;
use crate::process::ExitStatus;
use std::collections::HashMap;
use std::env;
use std::ffi::OsString;
use std::fmt;
use std::fs::File;
use std::io::{self, Read, Write};
use std::ops::BitOr;
use std::path::Path;
use std::sync::Arc;

use crate::job::Job;
pub(crate) use crate::job::{ReadAdapter, ReadErrAdapter, WriteAdapter};
use crate::pipeline::Pipeline;
use crate::spawn::{Arg, OsOptions, SpawnResult, display_escape, spawn};

use os::*;

/// Instruction what to do with a stream in the child process.
///
/// `Redirection` values are used for the `stdin`, `stdout`, and `stderr` parameters when
/// configuring a subprocess via [`Exec`] or [`Pipeline`].
///
/// [`Exec`]: struct.Exec.html
/// [`Pipeline`]: struct.Pipeline.html
#[derive(Debug)]
pub enum Redirection {
    /// Do nothing with the stream.
    ///
    /// The stream is typically inherited from the parent. The corresponding pipe field in
    /// [`Job`] will be `None`.
    ///
    /// [`Job`]: struct.Job.html
    None,

    /// Redirect the stream to a pipe.
    ///
    /// This variant requests that a stream be redirected to a unidirectional pipe. One
    /// end of the pipe is passed to the child process and configured as one of its
    /// standard streams, and the other end is available to the parent for communicating
    /// with the child.
    Pipe,

    /// Merge the stream to the other output stream.
    ///
    /// This variant is only valid when configuring redirection of standard output and
    /// standard error. Using `Redirection::Merge` for stderr requests the child's stderr
    /// to refer to the same underlying file as the child's stdout (which may or may not
    /// itself be redirected), equivalent to the `2>&1` operator of the Bourne
    /// shell. Analogously, using `Redirection::Merge` for stdout is equivalent to `1>&2`
    /// in the shell.
    ///
    /// Specifying `Redirection::Merge` for stdin or specifying it for both stdout and
    /// stderr is invalid and will cause an error.
    Merge,

    /// Redirect the stream to the specified open `File`.
    ///
    /// This does not create a pipe, it simply spawns the child so that the specified
    /// stream sees that file. The child can read from or write to the provided file on
    /// its own, without any intervention by the parent.
    File(File),

    /// Redirect the stream to the null device (`/dev/null` on Unix, `nul` on Windows).
    ///
    /// This is equivalent to `Redirection::File` with a null device file, but more
    /// convenient and portable.
    Null,
}

/// A builder for creating subprocesses.
///
/// `Exec` provides a builder API for spawning subprocesses, and includes convenience
/// methods for capturing the output and for connecting subprocesses into pipelines.
///
/// # Examples
///
/// Execute an external command and wait for it to complete:
///
/// ```no_run
/// # use subprocess::*;
/// # fn dummy() -> std::io::Result<()> {
/// # let dirname = "some_dir";
/// let exit_status = Exec::cmd("umount").arg(dirname).join()?;
/// # Ok(())
/// # }
/// ```
///
/// Execute the command using the OS shell, like C's `system`:
///
/// ```no_run
/// # use subprocess::*;
/// # fn dummy() -> std::io::Result<()> {
/// Exec::shell("shutdown -h now").join()?;
/// # Ok(())
/// # }
/// ```
///
/// Start a subprocess and obtain its output as an `impl Read`, like C's `popen`:
///
/// ```
/// # use subprocess::*;
/// # fn dummy() -> std::io::Result<()> {
/// let stream = Exec::cmd("ls").stream_stdout()?;
/// // call stream.read_to_string, construct io::BufReader(stream), etc.
/// # Ok(())
/// # }
/// ```
///
/// Capture the output of a command:
///
/// ```
/// # use subprocess::*;
/// # fn dummy() -> std::io::Result<()> {
/// let out = Exec::cmd("ls").capture()?.stdout_str();
/// # Ok(())
/// # }
/// ```
///
/// Redirect standard error to standard output, and capture both in a single stream:
///
/// ```
/// # use subprocess::*;
/// # fn dummy() -> std::io::Result<()> {
/// let out_and_err = Exec::cmd("ls")
///   .stderr(Redirection::Merge)
///   .capture()?
///   .stdout_str();
/// # Ok(())
/// # }
/// ```
///
/// Provide input to the command and read its output:
///
/// ```
/// # use subprocess::*;
/// # fn dummy() -> std::io::Result<()> {
/// let out = Exec::cmd("sort")
///   .stdin("b\nc\na\n")
///   .capture()?
///   .stdout_str();
/// assert!(out == "a\nb\nc\n");
/// # Ok(())
/// # }
/// ```
#[must_use]
pub struct Exec {
    command: OsString,
    args: Vec<Arg>,
    check_success: bool,
    stdin_data: Option<InputData>,
    pub(crate) stdin_redirect: Arc<Redirection>,
    pub(crate) stdout_redirect: Arc<Redirection>,
    pub(crate) stderr_redirect: Arc<Redirection>,
    detached: bool,
    executable: Option<OsString>,
    env: Option<Vec<(OsString, OsString)>>,
    cwd: Option<OsString>,
    os_options: OsOptions,
}

impl Exec {
    /// Constructs a new `Exec`, configured to run `command`.
    ///
    /// The command will be run directly in the OS, without an intervening shell. To run
    /// it through a shell, use [`Exec::shell`] instead.
    ///
    /// By default, the command will be run without arguments, and none of the standard
    /// streams will be modified.
    ///
    /// [`Exec::shell`]: struct.Exec.html#method.shell
    pub fn cmd(command: impl Into<OsString>) -> Exec {
        Exec {
            command: command.into(),
            args: vec![],
            check_success: false,
            stdin_data: None,
            stdin_redirect: Arc::new(Redirection::None),
            stdout_redirect: Arc::new(Redirection::None),
            stderr_redirect: Arc::new(Redirection::None),
            detached: false,
            executable: None,
            env: None,
            cwd: None,
            os_options: Default::default(),
        }
    }

    /// Constructs a new `Exec`, configured to run `cmdstr` with the system shell.
    ///
    /// `subprocess` never spawns shells without an explicit request. This command
    /// requests the shell to be used; on Unix-like systems, this is equivalent to
    /// `Exec::cmd("sh").arg("-c").arg(cmdstr)`. On Windows, it runs
    /// `Exec::cmd("cmd.exe").arg("/c").raw_arg(cmdstr)`, passing the command
    /// string without quoting so that `cmd.exe` interprets it correctly.
    ///
    /// `shell` is useful for porting code that uses the C `system` function, which also
    /// spawns a shell.
    ///
    /// When invoking this function, be careful not to interpolate arguments into the
    /// string run by the shell, such as `Exec::shell(format!("sort {}", filename))`. Such
    /// code is prone to errors and, if `filename` comes from an untrusted source, to
    /// shell injection attacks. Instead, use `Exec::cmd("sort").arg(filename)`.
    pub fn shell(cmdstr: impl Into<OsString>) -> Exec {
        let cmd = Exec::cmd(SHELL[0]).args(&SHELL[1..]);
        #[cfg(not(windows))]
        {
            cmd.arg(cmdstr)
        }
        #[cfg(windows)]
        {
            use crate::ExecExt;
            cmd.raw_arg(cmdstr)
        }
    }

    /// Appends `arg` to argument list.
    pub fn arg(mut self, arg: impl Into<OsString>) -> Exec {
        self.args.push(Arg::Regular(arg.into()));
        self
    }

    /// Extends the argument list with `args`.
    pub fn args(mut self, args: impl IntoIterator<Item = impl Into<OsString>>) -> Exec {
        self.args
            .extend(args.into_iter().map(|x| Arg::Regular(x.into())));
        self
    }

    /// Specifies that the process is initially detached.
    ///
    /// A detached process means that we will not wait for the process to finish when the
    /// object that owns it goes out of scope.
    pub fn detached(mut self) -> Exec {
        self.detached = true;
        self
    }

    /// If called, [`join`](Self::join) and [`capture`](Self::capture) will return an
    /// error if the process exits with a non-zero status.
    pub fn checked(mut self) -> Exec {
        self.check_success = true;
        self
    }

    fn ensure_env(&mut self) -> &mut Vec<(OsString, OsString)> {
        self.env.get_or_insert_with(|| env::vars_os().collect())
    }

    /// Clears the environment of the subprocess.
    ///
    /// When this is invoked, the subprocess will not inherit the environment of this
    /// process.
    pub fn env_clear(mut self) -> Exec {
        self.env = Some(vec![]);
        self
    }

    /// Sets an environment variable in the child process.
    ///
    /// If the same variable is set more than once, the last value is used.
    ///
    /// Other environment variables are by default inherited from the current process. If
    /// this is undesirable, call `env_clear` first.
    pub fn env(mut self, key: impl Into<OsString>, value: impl Into<OsString>) -> Exec {
        self.ensure_env().push((key.into(), value.into()));
        self
    }

    /// Sets multiple environment variables in the child process.
    ///
    /// The keys and values of the variables are specified by the iterable.  If the same
    /// variable is set more than once, the last value is used.
    ///
    /// Other environment variables are by default inherited from the current process. If
    /// this is undesirable, call `env_clear` first.
    pub fn env_extend(
        mut self,
        vars: impl IntoIterator<Item = (impl Into<OsString>, impl Into<OsString>)>,
    ) -> Exec {
        self.ensure_env()
            .extend(vars.into_iter().map(|(k, v)| (k.into(), v.into())));
        self
    }

    /// Removes an environment variable from the child process.
    ///
    /// Other environment variables are inherited by default.
    pub fn env_remove(mut self, key: impl Into<OsString>) -> Exec {
        let key = key.into();
        self.ensure_env().retain(|(k, _v)| *k != key);
        self
    }

    /// Specifies the current working directory of the child process.
    ///
    /// If unspecified, the current working directory is inherited from the parent.
    pub fn cwd(mut self, dir: impl AsRef<Path>) -> Exec {
        self.cwd = Some(dir.as_ref().as_os_str().to_owned());
        self
    }

    /// Specifies the source for the standard input of the child process.
    ///
    /// The source can be:
    ///
    /// * a [`Redirection`];
    /// * a `File`, which is a shorthand for `Redirection::File(file)`;
    /// * a `Vec<u8>`, `&str`, `&[u8]`, `Box<[u8]>`, or `[u8; N]`, which will set up a
    ///   `Redirection::Pipe` for stdin, feeding that data into the standard input of the
    ///   subprocess;
    /// * an [`InputData`], which also sets up a pipe, but wraps any reader and feeds its
    ///   content to the standard input of the subprocess. Use [`InputData::from_bytes`]
    ///   for in-memory byte containers not covered by the above, like `bytes::Bytes` or
    ///   `memmap2::Mmap`. Use [`InputData::from_reader`] for a custom `Read` that
    ///   generates or transforms data.
    ///
    /// If the child exits before consuming all input, the `BrokenPipe` error is silently
    /// ignored. Use the exit status and output to check if the child processed the input
    /// correctly.
    ///
    /// [`Redirection`]: enum.Redirection.html
    /// [`InputData`]: struct.InputData.html
    pub fn stdin<T>(mut self, stdin: T) -> Exec
    where
        InputRedirection: FromSource<T>,
    {
        match InputRedirection::from_source(stdin) {
            InputRedirection::Redirection(new) => {
                self.stdin_redirect = Arc::new(new);
                self.stdin_data = None;
            }
            InputRedirection::Data(data) => {
                self.stdin_redirect = Arc::new(Redirection::Pipe);
                self.stdin_data = Some(data);
            }
        }
        self
    }

    /// Specifies the sink for the standard output of the child process.
    ///
    /// The sink can be:
    ///
    /// * a [`Redirection`];
    /// * a `File`, which is a shorthand for `Redirection::File(file)`.
    ///
    /// [`Redirection`]: enum.Redirection.html
    pub fn stdout<T>(mut self, stdout: T) -> Exec
    where
        Redirection: FromSink<T>,
    {
        self.stdout_redirect = Arc::new(Redirection::from_sink(stdout));
        self
    }

    /// Specifies the sink for the standard error of the child process.
    ///
    /// The sink can be:
    ///
    /// * a [`Redirection`];
    /// * a `File`, which is a shorthand for `Redirection::File(file)`.
    ///
    /// [`Redirection`]: enum.Redirection.html
    pub fn stderr<T>(mut self, stderr: T) -> Exec
    where
        Redirection: FromSink<T>,
    {
        self.stderr_redirect = Arc::new(Redirection::from_sink(stderr));
        self
    }

    fn check_no_stdin_data(&self, meth: &str) {
        if self.stdin_data.is_some() {
            panic!("{} called with input data specified", meth);
        }
    }

    // Terminators

    /// Spawn the process and return the raw spawn result.
    ///
    /// This is the low-level entry point used by both `start()` and
    /// `Pipeline::start()`. It calls `crate::spawn::spawn()` with the Exec's fields.
    pub(crate) fn spawn(self) -> io::Result<SpawnResult> {
        let mut argv = self.args;
        argv.insert(0, Arg::Regular(self.command));

        spawn(
            argv,
            self.stdin_redirect,
            self.stdout_redirect,
            self.stderr_redirect,
            self.detached,
            self.executable.as_deref(),
            self.env.as_deref(),
            self.cwd.as_deref(),
            self.os_options,
        )
    }

    /// Starts the process and returns a [`Job`] handle with the running process and its
    /// pipe ends.
    pub fn start(mut self) -> io::Result<Job> {
        let stdin_data = self.stdin_data.take().unwrap_or_default();
        let check_success = self.check_success;

        let result = self.spawn()?;

        Ok(Job {
            stdin: result.stdin,
            stdout: result.stdout,
            stderr: result.stderr,
            stdin_data,
            check_success,
            processes: vec![result.process],
        })
    }

    /// Starts the process, waits for it to finish, and returns the exit status.
    pub fn join(self) -> io::Result<ExitStatus> {
        self.start()?.join()
    }

    /// Starts the process and returns a value implementing the `Read` trait that reads
    /// from the standard output of the child process.
    ///
    /// This will automatically set up `stdout(Redirection::Pipe)`, so it is not necessary
    /// to do that beforehand.
    ///
    /// When the trait object is dropped, it will wait for the process to finish. If this
    /// is undesirable, use `detached()`.
    ///
    /// # Panics
    ///
    /// Panics if input data was specified with [`stdin`](Self::stdin). Use
    /// [`capture`](Self::capture) or [`communicate`](Self::communicate) to both feed
    /// input and read output.
    pub fn stream_stdout(self) -> io::Result<impl Read> {
        self.check_no_stdin_data("stream_stdout");
        Ok(ReadAdapter(self.stdout(Redirection::Pipe).start()?))
    }

    /// Starts the process and returns a value implementing the `Read` trait that reads
    /// from the standard error of the child process.
    ///
    /// This will automatically set up `stderr(Redirection::Pipe)`, so it is not necessary
    /// to do that beforehand.
    ///
    /// When the trait object is dropped, it will wait for the process to finish. If this
    /// is undesirable, use `detached()`.
    ///
    /// # Panics
    ///
    /// Panics if input data was specified with [`stdin`](Self::stdin). Use
    /// [`capture`](Self::capture) or [`communicate`](Self::communicate) to both feed
    /// input and read output.
    pub fn stream_stderr(self) -> io::Result<impl Read> {
        self.check_no_stdin_data("stream_stderr");
        Ok(ReadErrAdapter(self.stderr(Redirection::Pipe).start()?))
    }

    /// Starts the process and returns a value implementing the `Write` trait that writes
    /// to the standard input of the child process.
    ///
    /// This will automatically set up `stdin(Redirection::Pipe)`, so it is not necessary
    /// to do that beforehand.
    ///
    /// When the trait object is dropped, it will wait for the process to finish. If this
    /// is undesirable, use `detached()`.
    ///
    /// # Panics
    ///
    /// Panics if input data was specified with [`stdin`](Self::stdin).
    pub fn stream_stdin(self) -> io::Result<impl Write> {
        self.check_no_stdin_data("stream_stdin");
        Ok(WriteAdapter(self.stdin(Redirection::Pipe).start()?))
    }

    /// Starts the process and returns a `Communicator` handle.
    ///
    /// Unless already configured, stdout and stderr are redirected to pipes. If you
    /// need different redirection (e.g. `stderr(Merge)`), set it up before calling
    /// this method and it will be preserved.
    ///
    /// Compared to `capture()`, this offers more choice in how communication is
    /// performed, such as read size limit and timeout. Unlike `capture()`, this
    /// method doesn't wait for the process to finish, effectively detaching it.
    pub fn communicate(mut self) -> io::Result<Communicator> {
        self = self.detached();
        if matches!(*self.stdout_redirect, Redirection::None) {
            self = self.stdout(Redirection::Pipe);
        }
        if matches!(*self.stderr_redirect, Redirection::None) {
            self = self.stderr(Redirection::Pipe);
        }
        self.start()?.communicate()
    }

    /// Starts the process, collects its output, and waits for it to finish.
    ///
    /// The return value provides the standard output and standard error as bytes or
    /// optionally strings, as well as the exit status.
    ///
    /// Unless already configured, stdout and stderr are redirected to pipes so they
    /// can be captured. If you need different redirection (e.g. `stderr(Merge)`),
    /// set it up before calling this method and it will be preserved.
    ///
    /// This method waits for the process to finish, rather than simply waiting for
    /// its standard streams to close. If this is undesirable, use `detached()`.
    pub fn capture(mut self) -> io::Result<Capture> {
        if matches!(*self.stdout_redirect, Redirection::None) {
            self = self.stdout(Redirection::Pipe);
        }
        if matches!(*self.stderr_redirect, Redirection::None) {
            self = self.stderr(Redirection::Pipe);
        }
        self.start()?.capture()
    }

    /// Show Exec as command-line string quoted in the Unix style.
    pub fn to_cmdline_lossy(&self) -> String {
        let mut out = String::new();
        if let Some(cmd_env) = &self.env {
            let current: Vec<_> = env::vars_os().collect();
            let current_map: HashMap<_, _> = current.iter().map(|(x, y)| (x, y)).collect();
            for (k, v) in cmd_env {
                if current_map.get(k) == Some(&v) {
                    continue;
                }
                out.push_str(&display_escape(&k.to_string_lossy()));
                out.push('=');
                out.push_str(&display_escape(&v.to_string_lossy()));
                out.push(' ');
            }
            let cmd_env: HashMap<_, _> = cmd_env.iter().map(|(k, v)| (k, v)).collect();
            for (k, _) in current {
                if !cmd_env.contains_key(&k) {
                    out.push_str(&display_escape(&k.to_string_lossy()));
                    out.push('=');
                    out.push(' ');
                }
            }
        }
        out.push_str(&display_escape(&self.command.to_string_lossy()));
        for arg in &self.args {
            out.push(' ');
            out.push_str(&arg.display_escaped());
        }
        out
    }

    pub(crate) fn stdin_is_set(&self) -> bool {
        !matches!(*self.stdin_redirect, Redirection::None)
    }

    pub(crate) fn stdout_is_set(&self) -> bool {
        !matches!(*self.stdout_redirect, Redirection::None)
    }

    #[cfg(unix)]
    pub(crate) fn setpgid_is_set(&self) -> bool {
        self.os_options.setpgid_is_set()
    }

    #[cfg(unix)]
    pub(crate) fn set_pgid_value(&mut self, pgid: u32) {
        self.os_options.set_pgid_value(pgid);
    }
}

impl BitOr for Exec {
    type Output = Pipeline;

    /// Create a `Pipeline` from `self` and `rhs`.
    fn bitor(self, rhs: Exec) -> Pipeline {
        Pipeline::new().pipe(self).pipe(rhs)
    }
}

impl fmt::Debug for Exec {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Exec {{ {} }}", self.to_cmdline_lossy())
    }
}

/// Data captured by [`Exec::capture`] and [`Pipeline::capture`].
///
/// [`Exec::capture`]: struct.Exec.html#method.capture
/// [`Pipeline::capture`]: struct.Pipeline.html#method.capture
#[derive(Debug)]
pub struct Capture {
    /// Standard output as bytes.
    pub stdout: Vec<u8>,
    /// Standard error as bytes.
    pub stderr: Vec<u8>,
    /// Exit status.
    pub exit_status: ExitStatus,
}

impl Capture {
    /// Returns the standard output as string, converted from bytes using
    /// `String::from_utf8_lossy`.
    pub fn stdout_str(&self) -> String {
        String::from_utf8_lossy(&self.stdout).into_owned()
    }

    /// Returns the standard error as string, converted from bytes using
    /// `String::from_utf8_lossy`.
    pub fn stderr_str(&self) -> String {
        String::from_utf8_lossy(&self.stderr).into_owned()
    }

    /// True if the exit status of the process or pipeline is 0.
    pub fn success(&self) -> bool {
        self.exit_status.success()
    }

    /// Returns `self` if the exit status is successful, or an error otherwise.
    pub fn check(self) -> io::Result<Self> {
        if self.success() {
            Ok(self)
        } else {
            Err(io::Error::other(format!(
                "command failed: {}",
                self.exit_status
            )))
        }
    }
}

/// Type-erased readable source for input data fed to a subprocess's stdin.
///
/// `InputData` wraps a reader, so it can supply stdin data from any readable source:
/// in-memory bytes, a custom `Read` implementation that generates or transforms data,
/// etc.
///
/// Use [`InputData::from_bytes`] for in-memory byte data (`Vec<u8>`, `bytes::Bytes`,
/// `memmap2::Mmap`, etc.) and [`InputData::from_reader`] for a custom `Read`
/// implementation.
pub struct InputData(Box<dyn Read + Send + Sync>);

impl InputData {
    /// Create `InputData` from in-memory byte data.
    ///
    /// Accepts any type that implements `AsRef<[u8]>`, such as `Vec<u8>`, `Box<[u8]>`,
    /// `bytes::Bytes`, or `memmap2::Mmap`.
    pub fn from_bytes(data: impl AsRef<[u8]> + Send + Sync + 'static) -> Self {
        InputData(Box::new(io::Cursor::new(data)))
    }

    /// Create `InputData` from a custom `Read` implementation that generates or
    /// transforms data on the fly.
    pub fn from_reader(reader: impl Read + Send + Sync + 'static) -> Self {
        InputData(Box::new(reader))
    }
}

impl Read for InputData {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.0.read(buf)
    }
}

impl Default for InputData {
    fn default() -> Self {
        InputData(Box::new(io::empty()))
    }
}

impl fmt::Debug for InputData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("InputData(..)")
    }
}

#[derive(Debug)]
pub enum InputRedirection {
    Redirection(Redirection),
    Data(InputData),
}

/// Trait for converting a source type into an input redirection.
///
/// Implemented for each type accepted by [`Exec::stdin`] and
/// [`Pipeline::stdin`](crate::Pipeline::stdin).
pub trait FromSource<T> {
    /// Create the input redirection from the given source.
    fn from_source(source: T) -> Self;
}

/// Trait for converting a sink type into an output redirection.
///
/// Implemented on [`Redirection`] for each type accepted by
/// [`Exec::stdout`], [`Exec::stderr`], and their `Pipeline` equivalents.
pub trait FromSink<T> {
    /// Create the output redirection from the given sink.
    fn from_sink(sink: T) -> Self;
}

impl FromSource<Redirection> for InputRedirection {
    fn from_source(source: Redirection) -> Self {
        if let Redirection::Merge = source {
            panic!("Redirection::Merge is only allowed for output streams");
        }
        InputRedirection::Redirection(source)
    }
}

impl FromSource<File> for InputRedirection {
    fn from_source(source: File) -> Self {
        InputRedirection::Redirection(Redirection::File(source))
    }
}

impl FromSource<InputData> for InputRedirection {
    fn from_source(source: InputData) -> Self {
        InputRedirection::Data(source)
    }
}

impl FromSource<Vec<u8>> for InputRedirection {
    fn from_source(source: Vec<u8>) -> Self {
        InputRedirection::Data(InputData::from_bytes(source))
    }
}

impl FromSource<&'static str> for InputRedirection {
    fn from_source(source: &'static str) -> Self {
        InputRedirection::Data(InputData::from_bytes(source))
    }
}

impl FromSource<&'static [u8]> for InputRedirection {
    fn from_source(source: &'static [u8]) -> Self {
        InputRedirection::Data(InputData::from_bytes(source))
    }
}

impl<const N: usize> FromSource<&'static [u8; N]> for InputRedirection {
    fn from_source(source: &'static [u8; N]) -> Self {
        InputRedirection::Data(InputData::from_bytes(source))
    }
}

impl<const N: usize> FromSource<[u8; N]> for InputRedirection {
    fn from_source(source: [u8; N]) -> Self {
        InputRedirection::Data(InputData::from_bytes(source))
    }
}

impl FromSource<Box<[u8]>> for InputRedirection {
    fn from_source(source: Box<[u8]>) -> Self {
        InputRedirection::Data(InputData::from_bytes(source))
    }
}

impl FromSink<Redirection> for Redirection {
    fn from_sink(sink: Redirection) -> Self {
        sink
    }
}

impl FromSink<File> for Redirection {
    fn from_sink(sink: File) -> Self {
        Redirection::File(sink)
    }
}

#[cfg(unix)]
pub mod unix {
    use super::Exec;
    use crate::job::Job;
    use crate::pipeline::Pipeline;
    use crate::unix::ProcessExt;
    use std::io;

    /// Unix-specific extension methods for [`Job`].
    pub trait JobExt {
        /// Send the specified signal to all processes in the pipeline.
        ///
        /// Delegates to [`ProcessExt::send_signal`] on each process.
        fn send_signal(&self, signal: i32) -> io::Result<()>;

        /// Send the specified signal to the process group of the first process.
        ///
        /// When used with [`PipelineExt::setpgid`], all pipeline processes share the
        /// first process's group, so signaling it reaches the entire pipeline. For a
        /// single process started with [`ExecExt::setpgid`], this signals its group.
        fn send_signal_group(&self, signal: i32) -> io::Result<()>;
    }

    impl JobExt for Job {
        fn send_signal(&self, signal: i32) -> io::Result<()> {
            for p in &self.processes {
                p.send_signal(signal)?;
            }
            Ok(())
        }

        fn send_signal_group(&self, signal: i32) -> io::Result<()> {
            if let Some(p) = self.processes.first() {
                p.send_signal_group(signal)?;
            }
            Ok(())
        }
    }

    /// Extension trait for Unix-specific process creation options.
    pub trait ExecExt {
        /// Set the user ID for the spawned process.
        ///
        /// The child process will run with the specified user ID, which affects file
        /// access permissions and process ownership. This calls `setuid(2)` in the child
        /// process after `fork()` but before `exec()`.
        fn setuid(self, uid: u32) -> Self;

        /// Set the group ID for the spawned process.
        ///
        /// The child process will run with the specified group ID, which affects file
        /// access permissions based on group ownership. This calls `setgid(2)` in the
        /// child process after `fork()` but before `exec()`.
        fn setgid(self, gid: u32) -> Self;

        /// Put the subprocess into its own process group.
        ///
        /// This calls `setpgid(0, 0)` before execing the child process, making it the
        /// leader of a new process group.  Useful for a single process that spawns
        /// children, allowing them all to be signaled as a group with
        /// [`ProcessExt::send_signal_group`].
        ///
        /// For pipelines, use [`PipelineExt::setpgid`] instead, which puts all pipeline
        /// processes into a shared group.
        ///
        /// [`ProcessExt::send_signal_group`]: crate::unix::ProcessExt::send_signal_group
        /// [`PipelineExt::setpgid`]: PipelineExt::setpgid
        fn setpgid(self) -> Self;
    }

    impl ExecExt for Exec {
        fn setuid(mut self, uid: u32) -> Exec {
            self.os_options.setuid = Some(uid);
            self
        }

        fn setgid(mut self, gid: u32) -> Exec {
            self.os_options.setgid = Some(gid);
            self
        }

        fn setpgid(mut self) -> Exec {
            self.os_options.setpgid = Some(0);
            self
        }
    }

    /// Unix-specific extension methods for [`Pipeline`].
    pub trait PipelineExt {
        /// Put all pipeline processes into a shared process group.
        ///
        /// The first process becomes the group leader (via `setpgid(0, 0)`) and
        /// subsequent processes join its group.  This allows signaling the entire
        /// pipeline as a unit using [`JobExt::send_signal_group`].
        ///
        /// For single processes that spawn children, use [`ExecExt::setpgid`] instead.
        fn setpgid(self) -> Self;
    }

    impl PipelineExt for Pipeline {
        fn setpgid(mut self) -> Pipeline {
            self.set_setpgid(true);
            self
        }
    }
}

#[cfg(any(windows, docsrs))]
pub mod windows {
    use std::ffi::OsString;

    use super::Exec;
    #[cfg(windows)]
    use crate::spawn::Arg;

    /// Process creation flag: The process does not have a console window.
    pub const CREATE_NO_WINDOW: u32 = 0x08000000;

    /// Process creation flag: The new process has a new console.
    pub const CREATE_NEW_CONSOLE: u32 = 0x00000010;

    /// Process creation flag: The new process is the root of a new process
    /// group.
    pub const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;

    /// Process creation flag: The process does not inherit its parent's
    /// console.
    pub const DETACHED_PROCESS: u32 = 0x00000008;

    /// Extension trait for Windows-specific process creation options.
    pub trait ExecExt {
        /// Set process creation flags for Windows.
        ///
        /// This value is passed to the `dwCreationFlags` parameter of
        /// `CreateProcessW`. Use this to control process creation behavior
        /// such as creating the process without a console window.
        fn creation_flags(self, flags: u32) -> Self;

        /// Appends `arg` to the command line without quoting or escaping.
        ///
        /// This is useful for passing arguments to programs that use non-standard command
        /// line parsing, such as `cmd.exe /c`. For example, passing `git commit -m "feat:
        /// widget"` through [`arg`](super::Exec::arg) would apply MSVC-style argv
        /// quoting, producing backslash escapes that `cmd.exe` would interpret literally.
        ///
        /// [`Exec::shell`](super::Exec::shell) uses this method to pass the command
        /// string to `cmd.exe /c`.
        ///
        /// # Background
        ///
        /// On Windows, process arguments are not passed as an array (as on Unix) but as a
        /// single command-line string to `CreateProcessW`. The regular
        /// [`arg`](super::Exec::arg) method applies MSVC C runtime quoting rules so that
        /// programs using standard `CommandLineToArgvW` parsing can reconstruct the
        /// original arguments. `raw_arg` bypasses all quoting and passes its argument to
        /// the command line verbatim. This is equivalent to [`raw_arg` in the standard
        /// library](https://doc.rust-lang.org/std/os/windows/process/trait.CommandExt.html#tymethod.raw_arg).
        ///
        /// Only use `raw_arg` with hardcoded or carefully validated input, as no quoting
        /// or escaping is applied.  [`Exec::shell`](super::Exec::shell) is an exception -
        /// a shell command must reach the shell verbatim, so quoting would corrupt it
        /// rather than protect it.
        fn raw_arg(self, arg: impl Into<OsString>) -> Self;
    }

    impl ExecExt for Exec {
        fn creation_flags(mut self, flags: u32) -> Exec {
            #[cfg(windows)]
            {
                self.os_options.creation_flags = flags;
                self
            }
            #[cfg(not(windows))]
            {
                let _ = flags;
                unimplemented!()
            }
        }

        fn raw_arg(mut self, arg: impl Into<OsString>) -> Exec {
            #[cfg(windows)]
            {
                self.args.push(Arg::Raw(arg.into()));
                self
            }
            #[cfg(not(windows))]
            {
                let _ = arg;
                unimplemented!()
            }
        }
    }
}