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
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
#[cfg(unix)]
mod os {
    pub const NULL_DEVICE: &str = "/dev/null";
    pub const SHELL: [&str; 2] = ["sh", "-c"];
}

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

pub use self::exec::{CaptureData, Exec, NullFile};
pub use self::os::*;
pub use self::pipeline::Pipeline;

#[cfg(unix)]
pub use exec::unix;

mod exec {
    use std::ffi::{OsStr, OsString};
    use std::fmt;
    use std::fs::{File, OpenOptions};
    use std::io::{Read, Result as IoResult, Write};
    use std::ops::BitOr;
    use std::path::Path;

    use crate::os_common::ExitStatus;
    use crate::popen::{Popen, PopenConfig, Redirection, Result as PopenResult};

    use super::os::*;
    use super::Pipeline;

    /// A builder for [`Popen`] instances, providing control and
    /// convenience methods.
    ///
    /// `Exec` provides a builder API for [`Popen::create`], 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() -> 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() -> Result<()> {
    /// Exec::shell("shutdown -h now").join()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Start a subprocess and obtain its output as a `Read` trait object,
    /// like C's `popen`:
    ///
    /// ```
    /// # use subprocess::*;
    /// # fn dummy() -> 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() -> Result<()> {
    /// let out = Exec::cmd("ls")
    ///   .stdout(Redirection::Pipe)
    ///   .capture()?
    ///   .stdout_str();
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Redirect errors to standard output, and capture both in a single stream:
    ///
    /// ```
    /// # use subprocess::*;
    /// # fn dummy() -> Result<()> {
    /// let out_and_err = Exec::cmd("ls")
    ///   .stdout(Redirection::Pipe)
    ///   .stderr(Redirection::Merge)
    ///   .capture()?
    ///   .stdout_str();
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Provide input to the command and read its output:
    ///
    /// ```
    /// # use subprocess::*;
    /// # fn dummy() -> Result<()> {
    /// let out = Exec::cmd("sort")
    ///   .stdin("b\nc\na\n")
    ///   .stdout(Redirection::Pipe)
    ///   .capture()?
    ///   .stdout_str();
    /// assert!(out == "a\nb\nc\n");
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`Popen`]: struct.Popen.html
    /// [`Popen::create`]: struct.Popen.html#method.create

    pub struct Exec {
        command: OsString,
        args: Vec<OsString>,
        config: PopenConfig,
        stdin_data: Option<Vec<u8>>,
    }

    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 AsRef<OsStr>) -> Exec {
            Exec {
                command: command.as_ref().to_owned(),
                args: vec![],
                config: PopenConfig::default(),
                stdin_data: None,
            }
        }

        /// 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")`.
        ///
        /// `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 AsRef<OsStr>) -> Exec {
            Exec::cmd(SHELL[0]).args(&SHELL[1..]).arg(cmdstr)
        }

        /// Appends `arg` to argument list.
        pub fn arg(mut self, arg: impl AsRef<OsStr>) -> Exec {
            self.args.push(arg.as_ref().to_owned());
            self
        }

        /// Extends the argument list with `args`.
        pub fn args(mut self, args: &[impl AsRef<OsStr>]) -> Exec {
            self.args.extend(args.iter().map(|x| x.as_ref().to_owned()));
            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.config.detached = true;
            self
        }

        fn ensure_env(&mut self) {
            if self.config.env.is_none() {
                self.config.env = Some(PopenConfig::current_env());
            }
        }

        /// 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.config.env = Some(Vec::new());
            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 AsRef<OsStr>, value: impl AsRef<OsStr>) -> Exec {
            self.ensure_env();
            self.config
                .env
                .as_mut()
                .unwrap()
                .push((key.as_ref().to_owned(), value.as_ref().to_owned()));
            self
        }

        /// Sets multiple environment variables in the child process.
        ///
        /// The keys and values of the variables are specified by the
        /// slice.  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 AsRef<OsStr>, impl AsRef<OsStr>)]) -> Exec {
            self.ensure_env();
            {
                let envvec = self.config.env.as_mut().unwrap();
                for &(ref k, ref v) in vars {
                    envvec.push((k.as_ref().to_owned(), v.as_ref().to_owned()));
                }
            }
            self
        }

        /// Removes an environment variable from the child process.
        ///
        /// Other environment variables are inherited by default.
        pub fn env_remove(mut self, key: impl AsRef<OsStr>) -> Exec {
            self.ensure_env();
            self.config
                .env
                .as_mut()
                .unwrap()
                .retain(|&(ref k, ref _v)| k != key.as_ref());
            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.config.cwd = Some(dir.as_ref().as_os_str().to_owned());
            self
        }

        /// Specifies how to set up the standard input of the child process.
        ///
        /// Argument can be:
        ///
        /// * a [`Redirection`];
        /// * a `File`, which is a shorthand for `Redirection::File(file)`;
        /// * a `Vec<u8>` or `&str`, which will set up a `Redirection::Pipe`
        ///   for stdin, making sure that `capture` feeds that data into the
        ///   standard input of the subprocess;
        /// * [`NullFile`], which will redirect the standard input to read from
        ///    `/dev/null`.
        ///
        /// [`Redirection`]: struct.Redirection.html
        /// [`NullFile`]: struct.NullFile.html
        pub fn stdin<T: Into<InputRedirection>>(mut self, stdin: T) -> Exec {
            match (&self.config.stdin, stdin.into()) {
                (&Redirection::None, InputRedirection::AsRedirection(new)) => {
                    self.config.stdin = new
                }
                (&Redirection::Pipe, InputRedirection::AsRedirection(Redirection::Pipe)) => (),
                (&Redirection::None, InputRedirection::FeedData(data)) => {
                    self.config.stdin = Redirection::Pipe;
                    self.stdin_data = Some(data);
                }
                (_, _) => panic!("stdin is already set"),
            }
            self
        }

        /// Specifies how to set up the standard output of the child process.
        ///
        /// Argument can be:
        ///
        /// * a [`Redirection`];
        /// * a `File`, which is a shorthand for `Redirection::File(file)`;
        /// * [`NullFile`], which will redirect the standard output to go to
        ///    `/dev/null`.
        ///
        /// [`Redirection`]: struct.Redirection.html
        /// [`NullFile`]: struct.NullFile.html
        pub fn stdout<T: Into<OutputRedirection>>(mut self, stdout: T) -> Exec {
            match (&self.config.stdout, stdout.into().into_redirection()) {
                (&Redirection::None, new) => self.config.stdout = new,
                (&Redirection::Pipe, Redirection::Pipe) => (),
                (_, _) => panic!("stdout is already set"),
            }
            self
        }

        /// Specifies how to set up the standard error of the child process.
        ///
        /// Argument can be:
        ///
        /// * a [`Redirection`];
        /// * a `File`, which is a shorthand for `Redirection::File(file)`;
        /// * [`NullFile`], which will redirect the standard error to go to
        ///    `/dev/null`.
        ///
        /// [`Redirection`]: struct.Redirection.html
        /// [`NullFile`]: struct.NullFile.html
        pub fn stderr<T: Into<OutputRedirection>>(mut self, stderr: T) -> Exec {
            match (&self.config.stderr, stderr.into().into_redirection()) {
                (&Redirection::None, new) => self.config.stderr = new,
                (&Redirection::Pipe, Redirection::Pipe) => (),
                (_, _) => panic!("stderr is already set"),
            }
            self
        }

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

        // Terminators

        /// Starts the process, returning a `Popen` for the running process.
        pub fn popen(mut self) -> PopenResult<Popen> {
            self.check_no_stdin_data("popen");
            self.args.insert(0, self.command);
            let p = Popen::create(&self.args, self.config)?;
            Ok(p)
        }

        /// Starts the process, waits for it to finish, and returns
        /// the exit status.
        ///
        /// This method will wait for as long as necessary for the
        /// process to finish.  If a timeout is needed, use
        /// `popen()?.wait_timeout(...)` instead.
        pub fn join(self) -> PopenResult<ExitStatus> {
            self.check_no_stdin_data("join");
            self.popen()?.wait()
        }

        /// 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()`.
        pub fn stream_stdout(self) -> PopenResult<impl Read> {
            self.check_no_stdin_data("stream_stdout");
            let p = self.stdout(Redirection::Pipe).popen()?;
            Ok(ReadOutAdapter(p))
        }

        /// 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()`.
        pub fn stream_stderr(self) -> PopenResult<impl Read> {
            self.check_no_stdin_data("stream_stderr");
            let p = self.stderr(Redirection::Pipe).popen()?;
            Ok(ReadErrAdapter(p))
        }

        /// 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()`.
        pub fn stream_stdin(self) -> PopenResult<impl Write> {
            self.check_no_stdin_data("stream_stdin");
            let p = self.stdin(Redirection::Pipe).popen()?;
            Ok(WriteAdapter(p))
        }

        /// 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.
        ///
        /// Unlike `Popen::communicate`, this method actually 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) -> PopenResult<CaptureData> {
            let stdin_data = self.stdin_data.take();
            if let (&Redirection::None, &Redirection::None) =
                (&self.config.stdout, &self.config.stderr)
            {
                self = self.stdout(Redirection::Pipe);
            }
            let mut p = self.popen()?;
            let (maybe_out, maybe_err) =
                p.communicate_bytes(stdin_data.as_ref().map(|v| &v[..]))?;
            let out = maybe_out.unwrap_or_else(Vec::new);
            let err = maybe_err.unwrap_or_else(Vec::new);
            let status = p.wait()?;
            Ok(CaptureData {
                stdout: out,
                stderr: err,
                exit_status: status,
            })
        }

        /// Show Exec as command-line string quoted in the Unix style.
        pub fn to_cmdline_lossy(&self) -> String {
            fn nice_char(c: char) -> bool {
                match c {
                    '-' | '_' | '.' | ',' | '/' => true,
                    c if c.is_ascii_alphanumeric() => true,
                    _ => false,
                }
            }
            fn write_quoted(out: &mut String, s: &str) {
                if !s.chars().all(nice_char) {
                    out.push_str(&format!("'{}'", s.replace("'", r#"'\''"#)));
                } else {
                    out.push_str(s);
                }
            }
            let mut out = String::new();
            write_quoted(&mut out, &self.command.to_string_lossy());
            for arg in &self.args {
                out.push(' ');
                write_quoted(&mut out, &arg.to_string_lossy());
            }
            out
        }
    }

    impl Clone for Exec {
        /// Returns a copy of the value.
        ///
        /// This method is guaranteed not to fail as long as none of
        /// the `Redirection` values contain a `Redirection::File`
        /// variant.  If a redirection to `File` is present, cloning
        /// that field will use `File::try_clone` method, which
        /// duplicates a file descriptor and can (but is not likely
        /// to) fail.  In that scenario, `Exec::clone` panics.
        fn clone(&self) -> Exec {
            Exec {
                command: self.command.clone(),
                args: self.args.clone(),
                config: self.config.try_clone().unwrap(),
                stdin_data: self.stdin_data.as_ref().cloned(),
            }
        }
    }

    impl BitOr for Exec {
        type Output = Pipeline;

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

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

    #[derive(Debug)]
    struct ReadOutAdapter(Popen);

    impl Read for ReadOutAdapter {
        fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
            self.0.stdout.as_mut().unwrap().read(buf)
        }
    }

    #[derive(Debug)]
    struct ReadErrAdapter(Popen);

    impl Read for ReadErrAdapter {
        fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
            self.0.stderr.as_mut().unwrap().read(buf)
        }
    }

    #[derive(Debug)]
    struct WriteAdapter(Popen);

    impl Write for WriteAdapter {
        fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
            self.0.stdin.as_mut().unwrap().write(buf)
        }
        fn flush(&mut self) -> IoResult<()> {
            self.0.stdin.as_mut().unwrap().flush()
        }
    }

    // We must implement Drop in order to close the stream.  The typical
    // use case for stream_stdin() is a process that reads something from
    // stdin.  WriteAdapter going out of scope invokes Popen::drop(),
    // which waits for the process to exit.  Without closing stdin, this
    // deadlocks because the child process hangs reading its stdin.

    impl Drop for WriteAdapter {
        fn drop(&mut self) {
            self.0.stdin.take();
        }
    }

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

    impl CaptureData {
        /// 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()
        }
    }

    pub enum InputRedirection {
        AsRedirection(Redirection),
        FeedData(Vec<u8>),
    }

    impl From<Redirection> for InputRedirection {
        fn from(r: Redirection) -> Self {
            if let Redirection::Merge = r {
                panic!("Redirection::Merge is only allowed for output streams");
            }
            InputRedirection::AsRedirection(r)
        }
    }

    impl From<File> for InputRedirection {
        fn from(f: File) -> Self {
            InputRedirection::AsRedirection(Redirection::File(f))
        }
    }

    /// Marker value for [`stdin`], [`stdout`], and [`stderr`] methods
    /// of [`Exec`] and [`Pipeline`].
    ///
    /// Use of this value means that the corresponding stream should
    /// be redirected to the devnull device.
    ///
    /// [`stdin`]: struct.Exec.html#method.stdin
    /// [`stdout`]: struct.Exec.html#method.stdout
    /// [`stderr`]: struct.Exec.html#method.stderr
    /// [`Exec`]: struct.Exec.html
    /// [`Pipeline`]: struct.Pipeline.html
    #[derive(Debug)]
    pub struct NullFile;

    impl From<NullFile> for InputRedirection {
        fn from(_nf: NullFile) -> Self {
            let null_file = OpenOptions::new().read(true).open(NULL_DEVICE).unwrap();
            InputRedirection::AsRedirection(Redirection::File(null_file))
        }
    }

    impl From<Vec<u8>> for InputRedirection {
        fn from(v: Vec<u8>) -> Self {
            InputRedirection::FeedData(v)
        }
    }

    impl<'a> From<&'a str> for InputRedirection {
        fn from(s: &'a str) -> Self {
            InputRedirection::FeedData(s.as_bytes().to_vec())
        }
    }

    #[derive(Debug)]
    pub struct OutputRedirection(Redirection);

    impl OutputRedirection {
        pub fn into_redirection(self) -> Redirection {
            self.0
        }
    }

    impl From<Redirection> for OutputRedirection {
        fn from(r: Redirection) -> Self {
            OutputRedirection(r)
        }
    }

    impl From<File> for OutputRedirection {
        fn from(f: File) -> Self {
            OutputRedirection(Redirection::File(f))
        }
    }

    impl From<NullFile> for OutputRedirection {
        fn from(_nf: NullFile) -> Self {
            let null_file = OpenOptions::new().write(true).open(NULL_DEVICE).unwrap();
            OutputRedirection(Redirection::File(null_file))
        }
    }

    #[cfg(unix)]
    pub mod unix {
        use super::Exec;

        pub trait ExecExt {
            fn setuid(self, uid: u32) -> Self;
            fn setgid(self, gid: u32) -> Self;
        }

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

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

mod pipeline {
    use std::fmt;
    use std::fs::File;
    use std::io::{Read, Result as IoResult, Write};
    use std::ops::BitOr;
    use std::rc::Rc;

    use crate::communicate;
    use crate::os_common::ExitStatus;
    use crate::popen::{Popen, Redirection, Result as PopenResult};

    use super::exec::{CaptureData, Exec, InputRedirection, OutputRedirection};

    /// A builder for multiple [`Popen`] instances connected via
    /// pipes.
    ///
    /// A pipeline is a sequence of two or more [`Exec`] commands
    /// connected via pipes.  Just like in a Unix shell pipeline, each
    /// command receives standard input from the previous command, and
    /// passes standard output to the next command.  Optionally, the
    /// standard input of the first command can be provided from the
    /// outside, and the output of the last command can be captured.
    ///
    /// In most cases you do not need to create [`Pipeline`] instances
    /// directly; instead, combine [`Exec`] instances using the `|`
    /// operator which produces `Pipeline`.
    ///
    /// # Examples
    ///
    /// Execute a pipeline and return the exit status of the last command:
    ///
    /// ```no_run
    /// # use subprocess::*;
    /// # fn dummy() -> Result<()> {
    /// let exit_status =
    ///   (Exec::shell("ls *.bak") | Exec::cmd("xargs").arg("rm")).join()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Capture the pipeline's output:
    ///
    /// ```no_run
    /// # use subprocess::*;
    /// # fn dummy() -> Result<()> {
    /// let dir_checksum = {
    ///     Exec::cmd("find . -type f") | Exec::cmd("sort") | Exec::cmd("sha1sum")
    /// }.capture()?.stdout_str();
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`Popen`]: struct.Popen.html
    /// [`Exec`]: struct.Exec.html
    /// [`Pipeline`]: struct.Pipeline.html

    pub struct Pipeline {
        cmds: Vec<Exec>,
        stdin: Redirection,
        stdout: Redirection,
        stderr_file: Option<File>,
        stdin_data: Option<Vec<u8>>,
    }

    impl Pipeline {
        /// Creates a new pipeline by combining two commands.
        ///
        /// Equivalent to `cmd1 | cmd2`.
        pub fn new(cmd1: Exec, cmd2: Exec) -> Pipeline {
            Pipeline {
                cmds: vec![cmd1, cmd2],
                stdin: Redirection::None,
                stdout: Redirection::None,
                stderr_file: None,
                stdin_data: None,
            }
        }

        /// Specifies how to set up the standard input of the first
        /// command in the pipeline.
        ///
        /// Argument can be:
        ///
        /// * a [`Redirection`];
        /// * a `File`, which is a shorthand for `Redirection::File(file)`;
        /// * a `Vec<u8>` or `&str`, which will set up a `Redirection::Pipe`
        ///   for stdin, making sure that `capture` feeds that data into the
        ///   standard input of the subprocess.
        /// * `NullFile`, which will redirect the standard input to read from
        ///    /dev/null.
        ///
        /// [`Redirection`]: struct.Redirection.html
        pub fn stdin<T: Into<InputRedirection>>(mut self, stdin: T) -> Pipeline {
            match stdin.into() {
                InputRedirection::AsRedirection(r) => self.stdin = r,
                InputRedirection::FeedData(data) => {
                    self.stdin = Redirection::Pipe;
                    self.stdin_data = Some(data);
                }
            };
            self
        }

        /// Specifies how to set up the standard output of the last
        /// command in the pipeline.
        ///
        /// Argument can be:
        ///
        /// * a [`Redirection`];
        /// * a `File`, which is a shorthand for `Redirection::File(file)`;
        /// * `NullFile`, which will redirect the standard output to write to
        ///    /dev/null.
        ///
        /// [`Redirection`]: struct.Redirection.html
        pub fn stdout<T: Into<OutputRedirection>>(mut self, stdout: T) -> Pipeline {
            self.stdout = stdout.into().into_redirection();
            self
        }

        /// Specifies a file to which to redirect the standard error of all
        /// the commands in the pipeline.
        ///
        /// It is useful for capturing the standard error of the pipeline as a
        /// whole.  Unlike `stdout()`, which only affects the last command in
        /// the pipeline, this affects all commands.  The difference is
        /// because standard output is piped from one command to the next, so
        /// only the output of the last command is "free".  In contrast, the
        /// standard errors are not connected in any way.  This is also the
        /// reason only a `File` is supported - it allows for efficient
        /// sharing of the same file by all commands.
        pub fn stderr_to(mut self, to: File) -> Pipeline {
            self.stderr_file = Some(to);
            self
        }

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

        // Terminators:

        /// Starts all commands in the pipeline, and returns a
        /// `Vec<Popen>` whose members correspond to running commands.
        ///
        /// If some command fails to start, the remaining commands
        /// will not be started, and the appropriate error will be
        /// returned.  The commands that have already started will be
        /// waited to finish (but will probably exit immediately due
        /// to missing output), except for the ones for which
        /// `detached()` was called.  This is equivalent to what the
        /// shell does.
        pub fn popen(mut self) -> PopenResult<Vec<Popen>> {
            self.check_no_stdin_data("popen");
            assert!(self.cmds.len() >= 2);

            if let Some(stderr_to) = self.stderr_file {
                let stderr_to = Rc::new(stderr_to);
                self.cmds = self
                    .cmds
                    .into_iter()
                    .map(|cmd| cmd.stderr(Redirection::RcFile(stderr_to.clone())))
                    .collect();
            }

            let first_cmd = self.cmds.drain(..1).next().unwrap();
            self.cmds.insert(0, first_cmd.stdin(self.stdin));

            let last_cmd = self.cmds.drain(self.cmds.len() - 1..).next().unwrap();
            self.cmds.push(last_cmd.stdout(self.stdout));

            let mut ret = Vec::<Popen>::new();
            let cnt = self.cmds.len();

            for (idx, mut runner) in self.cmds.into_iter().enumerate() {
                if idx != 0 {
                    let prev_stdout = ret[idx - 1].stdout.take().unwrap();
                    runner = runner.stdin(prev_stdout);
                }
                if idx != cnt - 1 {
                    runner = runner.stdout(Redirection::Pipe);
                }
                ret.push(runner.popen()?);
            }
            Ok(ret)
        }

        /// Starts the pipeline, waits for it to finish, and returns
        /// the exit status of the last command.
        pub fn join(self) -> PopenResult<ExitStatus> {
            self.check_no_stdin_data("join");
            let mut v = self.popen()?;
            // Waiting on a pipeline waits for all commands, but
            // returns the status of the last one.  This is how the
            // shells do it.  If the caller needs more precise control
            // over which status is returned, they can call popen().
            v.last_mut().unwrap().wait()
        }

        /// Starts the pipeline and returns a value implementing the `Read`
        /// trait that reads from the standard output of the last command.
        ///
        /// 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
        /// pipeline to finish.  If this is undesirable, use
        /// `detached()`.
        pub fn stream_stdout(self) -> PopenResult<impl Read> {
            self.check_no_stdin_data("stream_stdout");
            let v = self.stdout(Redirection::Pipe).popen()?;
            Ok(ReadPipelineAdapter(v))
        }

        /// Starts the pipeline and returns a value implementing the `Write`
        /// trait that writes to the standard input of the last command.
        ///
        /// 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()`.
        pub fn stream_stdin(self) -> PopenResult<impl Write> {
            self.check_no_stdin_data("stream_stdin");
            let v = self.stdin(Redirection::Pipe).popen()?;
            Ok(WritePipelineAdapter(v))
        }

        /// Starts the pipeline, collects its output, and waits for
        /// all commands to finish.
        ///
        /// The return value provides the standard output of the last command,
        /// the combined standard error of all commands, and the exit status
        /// of the last command.  The captured outputs can be accessed as
        /// bytes or strings.
        ///
        /// Unlike `Popen::communicate`, this method actually waits for the
        /// processes to finish, rather than simply waiting for the output to
        /// close.  If this is undesirable, use `detached()`.
        pub fn capture(mut self) -> PopenResult<CaptureData> {
            assert!(self.cmds.len() >= 2);

            let (err_read, err_write) = crate::popen::make_pipe()?;
            self = self.stderr_to(err_write);

            let stdin_data = self.stdin_data.take();
            let mut v = self.stdout(Redirection::Pipe).popen()?;

            let mut first = v.drain(..1).next().unwrap();
            let vlen = v.len();
            let mut last = v.drain(vlen - 1..).next().unwrap();

            let (out, err) = communicate::communicate(
                &mut first.stdin,
                &mut last.stdout,
                &mut Some(err_read),
                stdin_data.as_ref().map(|v| &v[..]),
            )?;
            let out = out.unwrap_or_else(Vec::new);
            let err = err.unwrap();

            let status = last.wait()?;

            Ok(CaptureData {
                stdout: out,
                stderr: err,
                exit_status: status,
            })
        }
    }

    impl Clone for Pipeline {
        /// Returns a copy of the value.
        ///
        /// This method is guaranteed not to fail as long as none of
        /// the `Redirection` values contain a `Redirection::File`
        /// variant.  If a redirection to `File` is present, cloning
        /// that field will use `File::try_clone` method, which
        /// duplicates a file descriptor and can (but is not likely
        /// to) fail.  In that scenario, `Exec::clone` panics.
        fn clone(&self) -> Pipeline {
            Pipeline {
                cmds: self.cmds.clone(),
                stdin: self.stdin.try_clone().unwrap(),
                stdout: self.stdout.try_clone().unwrap(),
                stderr_file: self.stderr_file.as_ref().map(|f| f.try_clone().unwrap()),
                stdin_data: self.stdin_data.clone(),
            }
        }
    }

    impl BitOr<Exec> for Pipeline {
        type Output = Pipeline;

        /// Append a command to the pipeline and return a new pipeline.
        fn bitor(mut self, rhs: Exec) -> Pipeline {
            self.cmds.push(rhs);
            self
        }
    }

    impl BitOr for Pipeline {
        type Output = Pipeline;

        /// Append a pipeline to the pipeline and return a new pipeline.
        fn bitor(mut self, rhs: Pipeline) -> Pipeline {
            self.cmds.extend(rhs.cmds);
            self.stdout = rhs.stdout;
            self
        }
    }

    impl fmt::Debug for Pipeline {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            let mut args = Vec::new();
            for cmd in &self.cmds {
                args.push(cmd.to_cmdline_lossy());
            }
            write!(f, "Pipeline {{ {} }}", args.join(" | "))
        }
    }

    #[derive(Debug)]
    struct ReadPipelineAdapter(Vec<Popen>);

    impl Read for ReadPipelineAdapter {
        fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
            let last = self.0.last_mut().unwrap();
            last.stdout.as_mut().unwrap().read(buf)
        }
    }

    #[derive(Debug)]
    struct WritePipelineAdapter(Vec<Popen>);

    impl WritePipelineAdapter {
        fn stdin(&mut self) -> &mut File {
            let first = self.0.first_mut().unwrap();
            first.stdin.as_mut().unwrap()
        }
    }

    impl Write for WritePipelineAdapter {
        fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
            self.stdin().write(buf)
        }
        fn flush(&mut self) -> IoResult<()> {
            self.stdin().flush()
        }
    }

    impl Drop for WritePipelineAdapter {
        // the same rationale as Drop for WriteAdapter
        fn drop(&mut self) {
            let first = &mut self.0[0];
            first.stdin.take();
        }
    }
}