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
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
//! A cross-platform library for running child processes and building
//! pipelines.
//!
//! `duct` wants to make shelling out in Rust as easy and flexible as it
//! is in Bash. It also takes care of [tricky
//! inconsistencies](https://github.com/oconnor663/duct.py/blob/master/spec.md#consistent-behavior-for-dir)
//! in the way different platforms shell out. And it's a cross-language
//! library; the [original
//! implementation](https://github.com/oconnor663/duct.py) is in Python,
//! with an identical API.
//!
//! - [Docs](https://docs.rs/duct)
//! - [Crate](https://crates.io/crates/duct)
//! - [Repo](https://github.com/oconnor663/duct.rs)
//!
//! # Example
//!
//! `duct` tries to be as concise as possible, so that you don't wish you were
//! back writing shell scripts. At the same time, it's explicit about what
//! happens to output, and strict about error codes in child processes.
//!
//! ```rust,no_run
//! #[macro_use]
//! extern crate duct;
//!
//! use duct::{cmd, sh};
//!
//! fn main() {
//!     // Read the name of the current git branch. If git exits with an error
//!     // code here (because we're not in a git repo, for example), `read` will
//!     // return an error too. `sh` commands run under the real system shell,
//!     // /bin/sh on Unix or cmd.exe on Windows.
//!     let current_branch = sh("git symbolic-ref --short HEAD").read().unwrap();
//!
//!     // Log the current branch, with git taking over the terminal as usual.
//!     // `cmd!` commands are spawned directly, without going through the
//!     // shell, so there aren't any escaping issues with variable arguments.
//!     cmd!("git", "log", current_branch).run().unwrap();
//!
//!     // More complicated expressions become trees. Here's a pipeline with two
//!     // child processes on the left, just because we can. In Bash this would
//!     // be: stdout=$((echo -n part one "" && echo part two) | sed s/p/sm/g)
//!     let part_one = &["-n", "part", "one", ""];
//!     let stdout = cmd("echo", part_one)
//!         .then(sh("echo part two"))
//!         .pipe(cmd!("sed", "s/p/sm/g"))
//!         .read()
//!         .unwrap();
//!     assert_eq!("smart one smart two", stdout);
//! }
//! ```
//!
//! `duct` uses [`os_pipe`](https://github.com/oconnor663/os_pipe.rs)
//! internally, and the docs for that one include a [big
//! example](https://docs.rs/os_pipe#example) that takes a dozen lines of code
//! to read both stdout and stderr from a child process. `duct` can do that in
//! one line:
//!
//! ```rust
//! use duct::sh;
//!
//! // This works on Windows too!
//! let output = sh("echo foo && echo bar >&2").stderr_to_stdout().read().unwrap();
//!
//! assert!(output.split_whitespace().eq(vec!["foo", "bar"]));
//! ```

extern crate os_pipe;

use os_pipe::FromFile;

use std::collections::HashMap;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio, Output, ExitStatus};
use std::thread::JoinHandle;
use std::sync::Arc;

// enums defined below
use ExpressionInner::*;
use IoExpressionInner::*;

/// Create a command given a program name and a collection of arguments. See
/// also the [`cmd!`](macro.cmd.html) macro, which doesn't require a collection.
///
/// # Example
///
/// ```
/// use duct::cmd;
///
/// let args = vec!["foo", "bar", "baz"];
///
/// # // NOTE: Normally this wouldn't work on Windows, but we have an "echo"
/// # // binary that gets built for our main tests, and it's sitting around by
/// # // the time we get here. If this ever stops working, then we can disable
/// # // the tests that depend on it.
/// let output = cmd("echo", &args).read();
///
/// assert_eq!("foo bar baz", output.unwrap());
/// ```
pub fn cmd<T, U, V>(program: T, args: U) -> Expression
    where T: ToExecutable,
          U: IntoIterator<Item = V>,
          V: Into<OsString>
{
    let mut argv_vec = Vec::new();
    argv_vec.push(program.to_executable());
    argv_vec.extend(args.into_iter().map(Into::<OsString>::into));
    Expression::new(Cmd(argv_vec))
}

/// Create a command with any number of of positional arguments, which may be
/// different types (anything that implements
/// [`Into<OsString>`](https://doc.rust-lang.org/std/convert/trait.From.html)).
/// See also the [`cmd`](fn.cmd.html) function, which takes a collection of
/// arguments.
///
/// # Example
///
/// ```
/// #[macro_use]
/// extern crate duct;
/// use std::path::Path;
///
/// fn main() {
///     let arg1 = "foo";
///     let arg2 = "bar".to_owned();
///     let arg3 = Path::new("baz");
///
///     let output = cmd!("echo", arg1, arg2, arg3).read();
///
///     assert_eq!("foo bar baz", output.unwrap());
/// }
/// ```
#[macro_export]
macro_rules! cmd {
    ( $program:expr ) => {
        {
            use std::ffi::OsString;
            use std::iter::empty;
            $crate::cmd($program, empty::<OsString>())
        }
    };
    ( $program:expr $(, $arg:expr )* ) => {
        {
            use std::ffi::OsString;
            let mut args: Vec<OsString> = Vec::new();
            $(
                args.push(Into::<OsString>::into($arg));
            )*
            $crate::cmd($program, args)
        }
    };
}

/// Create a command from a string of shell code.
///
/// This invokes the operating system's shell to execute the string:
/// `/bin/sh` on Unix-like systems and `cmd.exe` on Windows. This can be
/// very convenient sometimes, especially in small scripts and examples.
/// You don't need to quote each argument, and all the operators like
/// `|` and `>` work as usual.
///
/// However, building shell commands at runtime brings up tricky whitespace and
/// escaping issues, so avoid using `sh` and `format!` together. Prefer
/// [`cmd!`](macro.cmd.html) instead in those cases. Also note that shell
/// commands don't tend to be portable between Unix and Windows.
///
/// # Example
///
/// ```
/// use duct::sh;
///
/// let output = sh("echo foo bar baz").read();
///
/// assert_eq!("foo bar baz", output.unwrap());
/// ```
pub fn sh<T: ToExecutable>(command: T) -> Expression {
    Expression::new(Sh(command.to_executable()))
}

/// The central objects in `duct`, Expressions are created with
/// [`cmd`](fn.cmd.html), [`cmd!`](macro.cmd.html), or [`sh`](fn.sh.html), then
/// combined with [`pipe`](struct.Expression.html#method.pipe) or
/// [`then`](struct.Expression.html#method.then), and finally executed with
/// [`start`](struct.Expression.html#method.start),
/// [`run`](struct.Expression.html#method.run), or
/// [`read`](struct.Expression.html#method.read). They also support several
/// methods to control their execution, like
/// [`input`](struct.Expression.html#method.input),
/// [`env`](struct.Expression.html#method.env), and
/// [`unchecked`](struct.Expression.html#method.unchecked). Expressions are
/// immutable, and they do a lot of
/// [`Arc`](https://doc.rust-lang.org/std/sync/struct.Arc.html) sharing
/// internally, so all of these methods take `&self` and return a new
/// `Expression` cheaply.
#[derive(Clone, Debug)]
#[must_use]
pub struct Expression(Arc<ExpressionInner>);

impl Expression {
    /// Execute an expression, wait for it to complete, and return a
    /// [`std::process::Output`](https://doc.rust-lang.org/std/process/struct.Output.html)
    /// object containing the results. Nothing is captured by default, but if
    /// you build the expression with
    /// [`stdout_capture`](struct.Expression.html#method.stdout_capture) or
    /// [`stderr_capture`](struct.Expression.html#method.stderr_capture) then
    /// the `Output` will hold those captured bytes.
    ///
    /// # Errors
    ///
    /// In addition to all the IO errors possible with
    /// [`std::process::Command`](https://doc.rust-lang.org/std/process/struct.Command.html),
    /// `run` will return a [`Status`](enum.Error.html) error if the exit status
    /// of the child is non-zero. The `Output` is available through that error
    /// type if you catch it, but if you want a non-zero exit status to be `Ok`
    /// then you should use the
    /// [`unchecked`](struct.Expression.html#method.unchecked) method.
    ///
    /// # Example
    ///
    /// ```
    /// # #[macro_use] extern crate duct;
    /// # fn main() {
    /// # if cfg!(not(windows)) {
    /// let output = cmd!("echo", "hi").stdout_capture().run().unwrap();
    /// assert_eq!(b"hi\n".to_vec(), output.stdout);
    /// # }
    /// # }
    /// ```
    pub fn run(&self) -> Result<Output, Error> {
        let (context, stdout_reader, stderr_reader) = IoContext::new()?;
        let status = self.0.exec(context)?;
        let is_checked_error = status.is_checked_error();
        // These unwraps propagate any panics from the other thread,
        // but regular errors return normally.
        let stdout_vec = stdout_reader.join().unwrap()?;
        let stderr_vec = stderr_reader.join().unwrap()?;
        let output = Output {
            status: status.into_inner(),
            stdout: stdout_vec,
            stderr: stderr_vec,
        };
        if is_checked_error {
            Err(Error::Status(output))
        } else {
            Ok(output)
        }
    }

    /// Execute an expression, capture its standard output, and return the
    /// captured output as a `String`. This is a convenience wrapper around
    /// [`run`](struct.Expression.html#method.run). Like backticks and `$()` in
    /// the shell, `read` trims trailing newlines.
    ///
    /// # Errors
    ///
    /// In addition to all the errors possible with
    /// [`run`](struct.Expression.html#method.run), `read` can return a wrapped
    /// [`std::str::Utf8Error`](https://doc.rust-lang.org/stable/std/str/struct.Utf8Error.html)
    /// if the output of the expression is not valid UTF-8.
    ///
    /// # Example
    ///
    /// ```
    /// # #[macro_use] extern crate duct;
    /// # fn main() {
    /// # if cfg!(not(windows)) {
    /// let output = cmd!("echo", "hi").stdout_capture().read().unwrap();
    /// assert_eq!("hi", output);
    /// # }
    /// # }
    /// ```
    pub fn read(&self) -> Result<String, Error> {
        let output = self.stdout_capture().run()?;
        let output_str = std::str::from_utf8(&output.stdout)?;
        Ok(trim_right_newlines(output_str).to_owned())
    }

    /// Start running an expression, and immediately return a
    /// [`WaitHandle`](struct.WaitHandle.html). This is equivalent to
    /// [`run`](struct.Expression.html#method.run), except it doesn't block the
    /// current thread until you call
    /// [`wait`](struct.WaitHandle.html#method.wait) on the handle.
    ///
    /// # Example
    ///
    /// ```
    /// # #[macro_use] extern crate duct;
    /// # fn main() {
    /// # if cfg!(not(windows)) {
    /// let handle = cmd!("echo", "hi").stdout_capture().start();
    /// let output = handle.wait().unwrap();
    /// assert_eq!(b"hi\n".to_vec(), output.stdout);
    /// # }
    /// # }
    /// ```
    pub fn start(&self) -> WaitHandle {
        // Note that this returns a `WaitHandle` directly, not an
        // `io::Result<WaitHandle>`. That means that even IO errors that happen
        // during spawn (like a misspelled program name) won't show up until you
        // `wait` on the handle. The reason we can't report spawn errors
        // immediately is that it wouldn't work well with
        // [`then`](struct.Expression.html#method.then) and
        // [`pipe`](struct.Expression.html#method.pipe).
        //
        // The problem with `then` is that spawn errors in the right child don't
        // happen on the main thread. Instead there's a worker thread waiting on
        // the left child to finish, and it's that worker's job to spawn the
        // right child. The only way to return errors at that point is through
        // the WaitHandle, so a "return spawn errors immediately" design would
        // be inconsistent at best.
        //
        // The problem with `pipe` is worse. Both children start immediately, so
        // if a spawn error happens on the right, the left is already running.
        // Someone has to wait on it, or we'll leak a zombie process. But the
        // left child might take a long time to finish, and it's not ok for
        // `start` to block. Instead, we need the caller to `wait` as usual, so
        // that we can do this cleanup.
        //
        // Implementation note: This is currently implemented with a background
        // thread, so it's not as efficient as it could be.
        let clone = Expression(self.0.clone());
        WaitHandle(std::thread::spawn(move || clone.run()))
    }

    /// Join two expressions into a pipe, with the standard output of the left
    /// hooked up to the standard input of the right, like `|` in the shell. If
    /// either side of the pipe returns a non-zero exit status, that becomes the
    /// status of the whole pipe, similar to Bash's `pipefail` option. If both
    /// sides return non-zero, and one of them is
    /// [`unchecked`](struct.Expression.html#method.unchecked), then the checked
    /// side wins. Otherwise the right side wins.
    ///
    /// # Example
    ///
    /// ```
    /// # #[macro_use] extern crate duct;
    /// # fn main() {
    /// # if cfg!(not(windows)) {
    /// let output = cmd!("echo", "hi").pipe(cmd!("sed", "s/h/p/")).read();
    /// assert_eq!("pi", output.unwrap());
    /// # }
    /// # }
    /// ```
    pub fn pipe(&self, right: Expression) -> Expression {
        Self::new(Pipe(self.clone(), right.clone()))
    }

    /// Chain two expressions together to run in series, like `&&` in the shell.
    /// If the left child returns a non-zero exit status, the right child
    /// doesn't run. (You can use
    /// [`unchecked`](struct.Expression.html#method.unchecked) on the left child
    /// to make sure the right child always runs.) The exit status of this
    /// expression is the status of the last child that ran.
    ///
    /// # Example
    ///
    /// ```
    /// # use duct::sh;
    /// # fn main() {
    /// # if cfg!(not(windows)) {
    /// // Both echoes share the same stdout, so both go through `sed`.
    /// let output = sh("echo -n bar")
    ///     .then(sh("echo baz"))
    ///     .pipe(sh("sed s/b/f/g")).read();
    /// assert_eq!("farfaz", output.unwrap());
    /// # }
    /// # }
    /// ```
    pub fn then(&self, right: Expression) -> Expression {
        Self::new(Then(self.clone(), right.clone()))
    }

    /// Use bytes or a string as input for an expression, like `<<<` in the
    /// shell. A worker thread will be spawned at runtime to write this input.
    ///
    /// # Example
    ///
    /// ```
    /// # #[macro_use] extern crate duct;
    /// # fn main() {
    /// # if cfg!(not(windows)) {
    /// // Many types implement Into<Vec<u8>>. Here's a string.
    /// let output = cmd!("cat").input("foo").read().unwrap();
    /// assert_eq!("foo", output);
    ///
    /// // And here's a byte slice.
    /// let output = cmd!("cat").input(&b"foo"[..]).read().unwrap();
    /// assert_eq!("foo", output);
    /// # }
    /// # }
    /// ```
    pub fn input<T: Into<Vec<u8>>>(&self, input: T) -> Self {
        Self::new(Io(Input(Arc::new(input.into())), self.clone()))
    }

    /// Open a file at the given path and use it as input for an expression, like
    /// `<` in the shell.
    ///
    /// # Example
    ///
    /// ```
    /// # use duct::sh;
    /// # if cfg!(not(windows)) {
    /// // Many types implement Into<PathBuf>, including &str.
    /// let output = sh("head -c 3").stdin("/dev/zero").read().unwrap();
    /// assert_eq!("\0\0\0", output);
    /// # }
    /// ```
    pub fn stdin<T: Into<PathBuf>>(&self, path: T) -> Self {
        Self::new(Io(Stdin(path.into()), self.clone()))
    }

    /// Use an already opened file as input for an expression.
    ///
    /// # Example
    ///
    /// ```
    /// # use duct::sh;
    /// # if cfg!(not(windows)) {
    /// let input_file = std::fs::File::open("/dev/zero").unwrap();
    /// let output = sh("head -c 3").stdin_file(input_file).read().unwrap();
    /// assert_eq!("\0\0\0", output);
    /// # }
    /// ```
    pub fn stdin_file(&self, file: File) -> Self {
        Self::new(Io(StdinFile(file), self.clone()))
    }

    /// Use `/dev/null` (or `NUL` on Windows) as input for an expression.
    ///
    /// # Example
    ///
    /// ```
    /// # #[macro_use] extern crate duct;
    /// # fn main() {
    /// # if cfg!(not(windows)) {
    /// let output = cmd!("cat").stdin_null().read().unwrap();
    /// assert_eq!("", output);
    /// # }
    /// # }
    /// ```
    pub fn stdin_null(&self) -> Self {
        Self::new(Io(StdinNull, self.clone()))
    }

    /// Open a file at the given path and use it as output for an expression,
    /// like `>` in the shell.
    ///
    /// # Example
    ///
    /// ```
    /// # use duct::sh;
    /// # use std::io::prelude::*;
    /// # if cfg!(not(windows)) {
    /// // Many types implement Into<PathBuf>, including &str.
    /// let path = "/tmp/duct_test_tmp.txt";
    /// sh("echo wee").stdout(path).run().unwrap();
    /// let mut output = String::new();
    /// std::fs::File::open(path).unwrap().read_to_string(&mut output).unwrap();
    /// assert_eq!("wee\n", output);
    /// # }
    /// ```
    pub fn stdout<T: Into<PathBuf>>(&self, path: T) -> Self {
        Self::new(Io(Stdout(path.into()), self.clone()))
    }

    /// Use an already opened file as output for an expression.
    ///
    /// # Example
    ///
    /// ```
    /// # use duct::sh;
    /// # use std::io::prelude::*;
    /// # if cfg!(not(windows)) {
    /// let path = "/tmp/duct_test_tmp.txt";
    /// let file = std::fs::File::create(path).unwrap();
    /// sh("echo wee").stdout_file(file).run().unwrap();
    /// let mut output = String::new();
    /// std::fs::File::open(path).unwrap().read_to_string(&mut output).unwrap();
    /// assert_eq!("wee\n", output);
    /// # }
    /// ```
    pub fn stdout_file(&self, file: File) -> Self {
        Self::new(Io(StdoutFile(file), self.clone()))
    }

    /// Use `/dev/null` (or `NUL` on Windows) as output for an expression.
    ///
    /// # Example
    ///
    /// ```
    /// # use duct::sh;
    /// // This echo command won't print anything.
    /// sh("echo foo bar baz").stdout_null().run().unwrap();
    ///
    /// // And you won't get anything even if you try to read its output! The
    /// // null redirect happens farther down in the expression tree than the
    /// // implicit `stdout_capture`, and so it takes precedence.
    /// let output = sh("echo foo bar baz").stdout_null().read().unwrap();
    /// assert_eq!("", output);
    /// ```
    pub fn stdout_null(&self) -> Self {
        Self::new(Io(StdoutNull, self.clone()))
    }

    /// Capture the standard output of an expression. The captured bytes will be
    /// available on the `stdout` field of the
    /// [`std::process::Output`](https://doc.rust-lang.org/std/process/struct.Output.html)
    /// object returned by [`run`](struct.Expression.html#method.run) or
    /// [`wait`](struct.WaitHandle.html#method.wait). In the simplest cases,
    /// [`read`](struct.Expression.html#method.read) can be more convenient.
    ///
    /// # Example
    ///
    /// ```
    /// # use duct::sh;
    /// # if cfg!(not(windows)) {
    /// // The most direct way to read stdout bytes is `stdout_capture`.
    /// let output1 = sh("echo foo").stdout_capture().run().unwrap().stdout;
    /// assert_eq!(&b"foo\n"[..], &output1[..]);
    ///
    /// // The `read` method is a shorthand for `stdout_capture`, and it also
    /// // does string parsing and newline trimming.
    /// let output2 = sh("echo foo").read().unwrap();
    /// assert_eq!("foo", output2)
    /// # }
    /// ```
    pub fn stdout_capture(&self) -> Self {
        Self::new(Io(StdoutCapture, self.clone()))
    }

    /// Join the standard output of an expression to its standard error pipe,
    /// similar to `1>&2` in the shell.
    ///
    /// # Example
    ///
    /// ```
    /// # use duct::sh;
    /// # if cfg!(not(windows)) {
    /// let output = sh("echo foo").stdout_to_stderr().stderr_capture().run().unwrap();
    /// assert_eq!(&b"foo\n"[..], &output.stderr[..]);
    /// # }
    /// ```
    pub fn stdout_to_stderr(&self) -> Self {
        Self::new(Io(StdoutToStderr, self.clone()))
    }

    /// Open a file at the given path and use it as error output for an
    /// expression, like `2>` in the shell.
    ///
    /// # Example
    ///
    /// ```
    /// # use duct::sh;
    /// # use std::io::prelude::*;
    /// # if cfg!(not(windows)) {
    /// // Many types implement Into<PathBuf>, including &str.
    /// let path = "/tmp/duct_test_tmp.txt";
    /// sh("echo wee >&2").stderr(path).run().unwrap();
    /// let mut error_output = String::new();
    /// std::fs::File::open(path).unwrap().read_to_string(&mut error_output).unwrap();
    /// assert_eq!("wee\n", error_output);
    /// # }
    /// ```
    pub fn stderr<T: Into<PathBuf>>(&self, path: T) -> Self {
        Self::new(Io(Stderr(path.into()), self.clone()))
    }

    /// Use an already opened file as error output for an expression.
    ///
    /// # Example
    ///
    /// ```
    /// # use duct::sh;
    /// # use std::io::prelude::*;
    /// # if cfg!(not(windows)) {
    /// let path = "/tmp/duct_test_tmp.txt";
    /// let file = std::fs::File::create(path).unwrap();
    /// sh("echo wee >&2").stderr_file(file).run().unwrap();
    /// let mut error_output = String::new();
    /// std::fs::File::open(path).unwrap().read_to_string(&mut error_output).unwrap();
    /// assert_eq!("wee\n", error_output);
    /// # }
    /// ```
    pub fn stderr_file(&self, file: File) -> Self {
        Self::new(Io(StderrFile(file.into()), self.clone()))
    }

    /// Use `/dev/null` (or `NUL` on Windows) as error output for an expression.
    ///
    /// # Example
    ///
    /// ```
    /// # use duct::sh;
    /// // This echo-to-stderr command won't print anything.
    /// sh("echo foo bar baz >&2").stderr_null().run().unwrap();
    /// ```
    pub fn stderr_null(&self) -> Self {
        Self::new(Io(StderrNull, self.clone()))
    }

    /// Capture the error output of an expression. The captured bytes will be
    /// available on the `stderr` field of the `Output` object returned by
    /// [`run`](struct.Expression.html#method.run) or
    /// [`wait`](struct.WaitHandle.html#method.wait).
    ///
    /// # Example
    ///
    /// ```
    /// # use duct::sh;
    /// # if cfg!(not(windows)) {
    /// let output_obj = sh("echo foo >&2").stderr_capture().run().unwrap();
    /// assert_eq!(&b"foo\n"[..], &output_obj.stderr[..]);
    /// # }
    /// ```
    pub fn stderr_capture(&self) -> Self {
        Self::new(Io(StderrCapture, self.clone()))
    }

    /// Join the standard error of an expression to its standard output pipe,
    /// similar to `2>&1` in the shell.
    ///
    /// # Example
    ///
    /// ```
    /// # use duct::sh;
    /// # if cfg!(not(windows)) {
    /// let error_output = sh("echo foo >&2").stderr_to_stdout().read().unwrap();
    /// assert_eq!("foo", error_output);
    /// # }
    /// ```
    pub fn stderr_to_stdout(&self) -> Self {
        Self::new(Io(StderrToStdout, self.clone()))
    }

    /// Set the working directory where the expression will execute.
    ///
    /// Note that in some languages (Rust and Python at least), there are tricky
    /// platform differences in the way relative exe paths interact with child
    /// working directories. In particular, the exe path will be interpreted
    /// relative to the child dir on Unix, but relative to the parent dir on
    /// Windows. `duct` considers the Windows behavior correct, so in order to
    /// get that behavior consistently it calls
    /// [`std::fs::canonicalize`](https://doc.rust-lang.org/std/fs/fn.canonicalize.html)
    /// on relative exe paths when `dir` is in use. Paths in this sense are any
    /// program name containing a path separator, regardless of the type. (Note
    /// also that `Path` and `PathBuf` program names get a `./` prepended to
    /// them automatically by the [`ToExecutable`](trait.ToExecutable.html)
    /// trait, and so will always contain a separator.)
    ///
    /// # Errors
    ///
    /// Canonicalization can fail on some filesystems, or if the current
    /// directory has been removed, and
    /// [`run`](struct.Expression.html#method.run) will return those errors
    /// rather than trying any sneaky workarounds.
    ///
    /// # Example
    ///
    /// ```
    /// # #[macro_use] extern crate duct;
    /// # fn main() {
    /// # if cfg!(not(windows)) {
    /// let output = cmd!("pwd").dir("/").read().unwrap();
    /// assert_eq!("/", output);
    /// # }
    /// # }
    /// ```
    pub fn dir<T: Into<PathBuf>>(&self, path: T) -> Self {
        Self::new(Io(Dir(path.into()), self.clone()))
    }

    /// Set a variable in the expression's environment.
    ///
    /// # Example
    ///
    /// ```
    /// # use duct::sh;
    /// # if cfg!(not(windows)) {
    /// let output = sh("echo $FOO").env("FOO", "bar").read().unwrap();
    /// assert_eq!("bar", output);
    /// # }
    /// ```
    pub fn env<T, U>(&self, name: T, val: U) -> Self
        where T: Into<OsString>,
              U: Into<OsString>
    {
        Self::new(Io(Env(name.into(), val.into()), self.clone()))
    }

    /// Set the expression's entire environment, from a collection of name-value
    /// pairs (like a `HashMap`). You can use this method to clear specific
    /// variables for example, by collecting the parent's enironment, removing
    /// some names from the collection, and passing the result to `full_env`.
    /// Note that some environment variables are required for normal program
    /// execution (like `SystemRoot` on Windows), so copying the parent's
    /// environment is usually preferable to starting with an empty one.
    ///
    /// # Example
    ///
    /// ```
    /// # use duct::sh;
    /// # use std::collections::HashMap;
    /// # if cfg!(not(windows)) {
    /// let mut env_map: HashMap<_, _> = std::env::vars().collect();
    /// env_map.insert("FOO".into(), "bar".into());
    /// let output = sh("echo $FOO").full_env(env_map).read().unwrap();
    /// assert_eq!("bar", output);
    ///
    /// // The IntoIterator/Into<OsString> bounds are pretty flexible. A shared
    /// // reference works here too.
    /// # let mut env_map: HashMap<_, _> = std::env::vars().collect();
    /// # env_map.insert("FOO".into(), "bar".into());
    /// let output = sh("echo $FOO").full_env(&env_map).read().unwrap();
    /// assert_eq!("bar", output);
    /// # }
    /// ```
    pub fn full_env<T, U, V>(&self, name_vals: T) -> Self
        where T: IntoIterator<Item = (U, V)>,
              U: Into<OsString>,
              V: Into<OsString>
    {
        let env_map = name_vals.into_iter()
            .map(|(k, v)| (k.into(), v.into()))
            .collect();
        Self::new(Io(FullEnv(env_map), self.clone()))
    }

    /// Prevent a non-zero exit status from short-circuiting a
    /// [`then`](struct.Expression.html#method.then) expression or from causing
    /// [`run`](struct.Expression.html#method.run) and friends to return an
    /// error. The unchecked exit code will still be there on the `Output`
    /// returned by `run`; its value doesn't change.
    ///
    /// "Uncheckedness" sticks to an exit code as it bubbles up through
    /// complicated expressions, but it doesn't "infect" other exit codes. So
    /// for example, if only one sub-expression in a pipe has `unchecked`, then
    /// errors returned by the other side will still be checked. That said,
    /// usually you'll just call `unchecked` right before `run`, and it'll apply
    /// to an entire expression. This sub-expression stuff doesn't usually come
    /// up unless you have a big pipeline built out of lots of different pieces.
    ///
    /// # Example
    ///
    /// ```
    /// # #[macro_use] extern crate duct;
    /// # fn main() {
    /// # if cfg!(not(windows)) {
    /// // Normally the `false` command (which does nothing but return a
    /// // non-zero exit status) would short-circuit the `then` expression and
    /// // also make `read` return an error. `unchecked` prevents this.
    /// cmd!("false").unchecked().then(cmd!("echo", "hi")).read().unwrap();
    /// # }
    /// # }
    /// ```
    pub fn unchecked(&self) -> Self {
        Self::new(Io(Unchecked, self.clone()))
    }

    fn new(inner: ExpressionInner) -> Self {
        Expression(Arc::new(inner))
    }
}

/// Returned by the [`start`](struct.Expression.html#method.start) method.
/// Calling `start` followed by [`wait`](struct.WaitHandle.html#method.wait) on
/// the handle is equivalent to [`run`](struct.Expression.html#method.run).
pub struct WaitHandle(JoinHandle<Result<Output, Error>>);

impl WaitHandle {
    /// Wait for the running expression to finish, and return its output.
    /// Calling `start` followed by [`wait`](struct.WaitHandle.html#method.wait)
    /// is equivalent to [`run`](struct.Expression.html#method.run).
    pub fn wait(self) -> Result<Output, Error> {
        self.0.join().unwrap()
    }
}

#[derive(Debug)]
enum ExpressionInner {
    Cmd(Vec<OsString>),
    Sh(OsString),
    Pipe(Expression, Expression),
    Then(Expression, Expression),
    Io(IoExpressionInner, Expression),
}

impl ExpressionInner {
    fn exec(&self, context: IoContext) -> io::Result<ExpressionStatus> {
        match *self {
            Cmd(ref argv) => exec_argv(argv, context),
            Sh(ref command) => exec_sh(command, context),
            Pipe(ref left, ref right) => exec_pipe(left, right, context),
            Then(ref left, ref right) => exec_then(left, right, context),
            Io(ref io_inner, ref expr) => exec_io(io_inner, expr, context),
        }
    }
}

fn maybe_canonicalize_exe_path(exe_name: &OsStr, context: &IoContext) -> io::Result<OsString> {
    // There's a tricky interaction between exe paths and `dir`. Exe
    // paths can be relative, and so we have to ask: Is an exe path
    // interpreted relative to the parent's cwd, or the child's? The
    // answer is that it's platform dependent! >.< (Windows uses the
    // parent's cwd, but because of the fork-chdir-exec pattern, Unix
    // usually uses the child's.)
    //
    // We want to use the parent's cwd consistently, because that saves
    // the caller from having to worry about whether `dir` will have
    // side effects, and because it's easy for the caller to use
    // Path::join if they want to. That means that when `dir` is in use,
    // we need to detect exe names that are relative paths, and
    // absolutify them. We want to do that as little as possible though,
    // both because canonicalization can fail, and because we prefer to
    // let the caller control the child's argv[0].
    //
    // We never want to absolutify a name like "emacs", because that's
    // probably a program in the PATH rather than a local file. So we
    // look for slashes in the name to determine what's a filepath and
    // what isn't. Note that anything given as a std::path::Path will
    // always have a slash by the time we get here, because we
    // specialize the ToExecutable trait to prepend a ./ to them when
    // they're relative. This leaves the case where Windows users might
    // pass a local file like "foo.bat" as a string, which we can't
    // distinguish from a global program name. However, because the
    // Windows has the preferred "relative to parent's cwd" behavior
    // already, this case actually works without our help. (The thing
    // Windows users have to watch out for instead is local files
    // shadowing global program names, which I don't think we can or
    // should prevent.)

    let has_separator = exe_name.to_string_lossy().chars().any(std::path::is_separator);
    let is_relative = Path::new(exe_name).is_relative();
    if context.dir.is_some() && has_separator && is_relative {
        Path::new(exe_name).canonicalize().map(Into::into)
    } else {
        Ok(exe_name.to_owned())
    }
}

fn exec_argv(argv: &[OsString], context: IoContext) -> io::Result<ExpressionStatus> {
    let exe = maybe_canonicalize_exe_path(&argv[0], &context)?;
    let mut command = Command::new(exe);
    command.args(&argv[1..]);
    // TODO: Avoid unnecessary dup'ing here.
    command.stdin(context.stdin.into_stdio()?);
    command.stdout(context.stdout.into_stdio()?);
    command.stderr(context.stderr.into_stdio()?);
    if let Some(dir) = context.dir {
        command.current_dir(dir);
    }
    command.env_clear();
    for (name, val) in context.env {
        command.env(name, val);
    }
    command.status().map(ExpressionStatus::Checked)
}

#[cfg(unix)]
fn shell_command_argv(command: OsString) -> [OsString; 3] {
    [OsStr::new("/bin/sh").to_owned(), OsStr::new("-c").to_owned(), command]
}

#[cfg(windows)]
fn shell_command_argv(command: OsString) -> [OsString; 3] {
    let comspec = std::env::var_os("COMSPEC").unwrap_or(OsStr::new("cmd.exe").to_owned());
    [comspec, OsStr::new("/C").to_owned(), command]
}

fn exec_sh(command: &OsString, context: IoContext) -> io::Result<ExpressionStatus> {
    exec_argv(&shell_command_argv(command.clone()), context)
}

fn exec_pipe(left: &Expression,
             right: &Expression,
             context: IoContext)
             -> io::Result<ExpressionStatus> {
    let (reader, writer) = os_pipe::pipe()?;
    let mut left_context = context.try_clone()?;  // dup'ing stdin/stdout isn't strictly necessary, but no big deal
    left_context.stdout = IoValue::File(File::from_file(writer));
    let mut right_context = context;
    right_context.stdin = IoValue::File(File::from_file(reader));

    let left_clone = Expression(left.0.clone());
    let left_joiner = std::thread::spawn(move || left_clone.0.exec(left_context));
    let right_result = right.0.exec(right_context);
    let left_result = left_joiner.join().unwrap();

    // First return any IO errors, with the right side taking precedence.
    let right_status = right_result?;
    let left_status = left_result?;

    // Now return one of the two statuses. The rules of precedence are:
    // 1) Checked errors trump unchecked errors.
    // 2) Unchecked errors trump success.
    // 3) All else equal, right side wins.
    Ok(if right_status.is_checked_error() {
        right_status
    } else if left_status.is_checked_error() {
        left_status
    } else if !right_status.success() {
        right_status
    } else {
        left_status
    })
}

fn exec_then(left: &Expression,
             right: &Expression,
             context: IoContext)
             -> io::Result<ExpressionStatus> {
    let status = left.0.exec(context.try_clone()?)?;
    if status.is_checked_error() {
        // Checked status errors are `Ok` because they're not literally IO
        // errors, but we short circuit and bubble them up.
        Ok(status)
    } else {
        right.0.exec(context)
    }
}

fn exec_io(io_inner: &IoExpressionInner,
           expr: &Expression,
           context: IoContext)
           -> io::Result<ExpressionStatus> {
    {
        let (new_context, maybe_writer_thread) = io_inner.update_context(context)?;
        let exec_result = expr.0.exec(new_context);
        let writer_result = join_maybe_writer_thread(maybe_writer_thread);
        // Propagate any exec errors first.
        let exec_status = exec_result?;
        // Then propagate any writer thread errors.
        writer_result?;
        // Finally, implement unchecked() status suppression here.
        if let &Unchecked = io_inner {
            Ok(ExpressionStatus::Unchecked(exec_status.into_inner()))
        } else {
            Ok(exec_status)
        }
    }
}

#[derive(Debug)]
enum IoExpressionInner {
    Input(Arc<Vec<u8>>),
    Stdin(PathBuf),
    StdinFile(File),
    StdinNull,
    Stdout(PathBuf),
    StdoutFile(File),
    StdoutNull,
    StdoutCapture,
    StdoutToStderr,
    Stderr(PathBuf),
    StderrFile(File),
    StderrNull,
    StderrCapture,
    StderrToStdout,
    Dir(PathBuf),
    Env(OsString, OsString),
    FullEnv(HashMap<OsString, OsString>),
    Unchecked,
}

impl IoExpressionInner {
    fn update_context(&self,
                      mut context: IoContext)
                      -> io::Result<(IoContext, Option<WriterThread>)> {
        let mut maybe_thread = None;
        match *self {
            Input(ref v) => {
                let (reader, thread) = pipe_with_writer_thread(v)?;
                context.stdin = IoValue::File(reader);
                maybe_thread = Some(thread)
            }
            Stdin(ref p) => {
                context.stdin = IoValue::File(File::open(p)?);
            }
            StdinFile(ref f) => {
                context.stdin = IoValue::File(f.try_clone()?);
            }
            StdinNull => {
                context.stdin = IoValue::Null;
            }
            Stdout(ref p) => {
                context.stdout = IoValue::File(File::create(p)?);
            }
            StdoutFile(ref f) => {
                context.stdout = IoValue::File(f.try_clone()?);
            }
            StdoutNull => {
                context.stdout = IoValue::Null;
            }
            StdoutCapture => context.stdout = IoValue::File(context.stdout_capture.try_clone()?),
            StdoutToStderr => {
                context.stdout = context.stderr.try_clone()?;
            }
            Stderr(ref p) => {
                context.stderr = IoValue::File(File::create(p)?);
            }
            StderrFile(ref f) => {
                context.stderr = IoValue::File(f.try_clone()?);
            }
            StderrNull => {
                context.stderr = IoValue::Null;
            }
            StderrCapture => context.stderr = IoValue::File(context.stderr_capture.try_clone()?),
            StderrToStdout => {
                context.stderr = context.stdout.try_clone()?;
            }
            Dir(ref p) => {
                context.dir = Some(p.clone());
            }
            Env(ref name, ref val) => {
                context.env.insert(name.clone(), val.clone());
            }
            FullEnv(ref map) => {
                context.env = map.clone();
            }
            Unchecked => {
                // No-op. Unchecked is handled in exec_io().
            }
        }
        Ok((context, maybe_thread))
    }
}

// We want to allow Path("foo") to refer to the local file "./foo" on
// Unix, and we want to *prevent* Path("echo") from referring to the
// global "echo" command on either Unix or Windows. Prepend a dot to all
// relative paths to accomplish both of those.
fn sanitize_exe_path<T: Into<PathBuf>>(path: T) -> PathBuf {
    let path_buf = path.into();
    // Don't try to be too clever with checking parent(). The parent of "foo" is
    // Some(""). See https://github.com/rust-lang/rust/issues/36861. Also we
    // don't strictly need the has_root check, because joining a leading dot is
    // a no-op in that case, but explicitly checking it is clearer.
    if path_buf.is_absolute() || path_buf.has_root() {
        path_buf
    } else {
        Path::new(".").join(path_buf)
    }
}

/// `duct` provides several impls of this trait to handle the difference between
/// [`Path`](https://doc.rust-lang.org/std/path/struct.Path.html)/[`PathBuf`](https://doc.rust-lang.org/std/path/struct.PathBuf.html)
/// and other types of strings. In particular, `duct` automatically prepends a
/// leading dot to relative paths (though not other string types) before
/// executing them. This is required for single-component relative paths to work
/// at all on Unix, and it prevents aliasing with programs in the global `PATH`
/// on both Unix and Windows. See the trait bounds on [`cmd`](fn.cmd.html) and
/// [`sh`](fn.sh.html).
pub trait ToExecutable {
    fn to_executable(self) -> OsString;
}

// TODO: Get rid of most of these impls once specialization lands.

impl<'a> ToExecutable for &'a Path {
    fn to_executable(self) -> OsString {
        sanitize_exe_path(self).into()
    }
}

impl ToExecutable for PathBuf {
    fn to_executable(self) -> OsString {
        sanitize_exe_path(self).into()
    }
}

impl<'a> ToExecutable for &'a PathBuf {
    fn to_executable(self) -> OsString {
        sanitize_exe_path(&**self).into()
    }
}

impl<'a> ToExecutable for &'a str {
    fn to_executable(self) -> OsString {
        self.into()
    }
}

impl ToExecutable for String {
    fn to_executable(self) -> OsString {
        self.into()
    }
}

impl<'a> ToExecutable for &'a String {
    fn to_executable(self) -> OsString {
        self.into()
    }
}

impl<'a> ToExecutable for &'a OsStr {
    fn to_executable(self) -> OsString {
        self.into()
    }
}

impl ToExecutable for OsString {
    fn to_executable(self) -> OsString {
        self
    }
}

impl<'a> ToExecutable for &'a OsString {
    fn to_executable(self) -> OsString {
        self.into()
    }
}

#[derive(Debug)]
pub enum Error {
    Io(io::Error),
    Status(Output),
    Utf8(std::str::Utf8Error),
}

impl From<io::Error> for Error {
    fn from(err: io::Error) -> Error {
        Error::Io(err)
    }
}

impl From<std::str::Utf8Error> for Error {
    fn from(err: std::str::Utf8Error) -> Error {
        Error::Utf8(err)
    }
}

// An IoContext represents the file descriptors child processes are talking to at execution time.
// It's initialized in run(), with dups of the stdin/stdout/stderr pipes, and then passed down to
// sub-expressions. Compound expressions will clone() it, and redirections will modify it.
#[derive(Debug)]
struct IoContext {
    stdin: IoValue,
    stdout: IoValue,
    stderr: IoValue,
    stdout_capture: File,
    stderr_capture: File,
    dir: Option<PathBuf>,
    env: HashMap<OsString, OsString>,
}

impl IoContext {
    // Returns (context, stdout_reader, stderr_reader).
    fn new() -> io::Result<(IoContext, ReaderThread, ReaderThread)> {
        let (stdout_capture, stdout_reader) = pipe_with_reader_thread()?;
        let (stderr_capture, stderr_reader) = pipe_with_reader_thread()?;
        let mut env = HashMap::new();
        for (name, val) in std::env::vars_os() {
            env.insert(name, val);
        }
        let context = IoContext {
            stdin: IoValue::ParentStdin,
            stdout: IoValue::ParentStdout,
            stderr: IoValue::ParentStderr,
            stdout_capture: stdout_capture,
            stderr_capture: stderr_capture,
            dir: None,
            env: env,
        };
        Ok((context, stdout_reader, stderr_reader))
    }

    fn try_clone(&self) -> io::Result<IoContext> {
        Ok(IoContext {
            stdin: self.stdin.try_clone()?,
            stdout: self.stdout.try_clone()?,
            stderr: self.stderr.try_clone()?,
            stdout_capture: self.stdout_capture.try_clone()?,
            stderr_capture: self.stderr_capture.try_clone()?,
            dir: self.dir.clone(),
            env: self.env.clone(),
        })
    }
}

#[derive(Debug)]
enum IoValue {
    ParentStdin,
    ParentStdout,
    ParentStderr,
    Null,
    File(File),
}

impl IoValue {
    fn try_clone(&self) -> io::Result<IoValue> {
        Ok(match self {
            &IoValue::ParentStdin => IoValue::ParentStdin,
            &IoValue::ParentStdout => IoValue::ParentStdout,
            &IoValue::ParentStderr => IoValue::ParentStderr,
            &IoValue::Null => IoValue::Null,
            &IoValue::File(ref f) => IoValue::File(f.try_clone()?),
        })
    }

    fn into_stdio(self) -> io::Result<Stdio> {
        match self {
            IoValue::ParentStdin => os_pipe::parent_stdin(),
            IoValue::ParentStdout => os_pipe::parent_stdout(),
            IoValue::ParentStderr => os_pipe::parent_stderr(),
            IoValue::Null => Ok(Stdio::null()),
            IoValue::File(f) => Ok(Stdio::from_file(f)),
        }
    }
}

type ReaderThread = JoinHandle<io::Result<Vec<u8>>>;

fn pipe_with_reader_thread() -> io::Result<(File, ReaderThread)> {
    let (mut reader, writer) = os_pipe::pipe()?;
    let thread = std::thread::spawn(move || {
        let mut output = Vec::new();
        reader.read_to_end(&mut output)?;
        Ok(output)
    });
    Ok((File::from_file(writer), thread))
}

type WriterThread = JoinHandle<io::Result<()>>;

fn pipe_with_writer_thread(input: &Arc<Vec<u8>>) -> io::Result<(File, WriterThread)> {
    let (reader, mut writer) = os_pipe::pipe()?;
    let new_arc = input.clone();
    let thread = std::thread::spawn(move || {
        writer.write_all(&new_arc)?;
        Ok(())
    });
    Ok((File::from_file(reader), thread))
}

fn join_maybe_writer_thread(maybe_writer_thread: Option<WriterThread>) -> io::Result<()> {
    if let Some(thread) = maybe_writer_thread {
        // A broken pipe error happens if the process on the other end exits before
        // we're done writing. We ignore those but return any other errors to the
        // caller.
        suppress_broken_pipe_errors(thread.join().unwrap())
    } else {
        Ok(())
    }
}

// This is split out to make it easier to get test coverage.
fn suppress_broken_pipe_errors(r: io::Result<()>) -> io::Result<()> {
    if let &Err(ref io_error) = &r {
        if io_error.kind() == io::ErrorKind::BrokenPipe {
            return Ok(());
        }
    }
    r
}

fn trim_right_newlines(s: &str) -> &str {
    s.trim_right_matches(|c| c == '\n' || c == '\r')
}

// This enum allows `unchecked` to keep the original non-zero exit status,
// while suppressing the errors it would normally cause.
enum ExpressionStatus {
    Checked(ExitStatus),
    Unchecked(ExitStatus),
}

impl ExpressionStatus {
    fn into_inner(self) -> ExitStatus {
        match self {
            ExpressionStatus::Checked(status) => status,
            ExpressionStatus::Unchecked(status) => status,
        }
    }

    fn is_checked_error(&self) -> bool {
        match *self {
            ExpressionStatus::Checked(ref status) => !status.success(),
            ExpressionStatus::Unchecked(_) => false,
        }
    }

    fn success(&self) -> bool {
        match *self {
            ExpressionStatus::Checked(ref status) => status.success(),
            ExpressionStatus::Unchecked(ref status) => status.success(),
        }
    }
}

#[cfg(test)]
mod test {
    extern crate tempdir;
    use self::tempdir::TempDir;

    use os_pipe::FromFile;

    use super::*;
    use std::collections::HashMap;
    use std::env;
    use std::env::consts::EXE_EXTENSION;
    use std::ffi::{OsStr, OsString};
    use std::fs::File;
    use std::io;
    use std::io::prelude::*;
    use std::path::{Path, PathBuf};
    use std::process::Command;
    use std::str;
    use std::sync::{Once, ONCE_INIT};

    fn path_to_exe(name: &str) -> PathBuf {
        // This project defines some associated binaries for testing, and we shell out to them in
        // these tests. `cargo test` doesn't automatically build associated binaries, so this
        // function takes care of building them explicitly.
        static CARGO_BUILD_ONCE: Once = ONCE_INIT;
        CARGO_BUILD_ONCE.call_once(|| {
            let build_status = Command::new("cargo")
                .arg("build")
                .arg("--quiet")
                .status()
                .unwrap();
            assert!(build_status.success(),
                    "Cargo failed to build associated binaries.");
        });

        Path::new("target").join("debug").join(name).with_extension(EXE_EXTENSION)
    }

    fn true_cmd() -> Expression {
        cmd!(path_to_exe("status"), "0")
    }

    fn false_cmd() -> Expression {
        cmd!(path_to_exe("status"), "1")
    }

    #[test]
    fn test_cmd() {
        let output = cmd!(path_to_exe("echo"), "hi").read().unwrap();
        assert_eq!("hi", output);
    }

    #[test]
    fn test_sh() {
        // Windows compatible.
        let output = sh("echo hi").read().unwrap();
        assert_eq!("hi", output);
    }

    #[test]
    fn test_start() {
        let handle = cmd!(path_to_exe("echo"), "hi").stdout_capture().start();
        let output = handle.wait().unwrap();
        assert_eq!("hi", str::from_utf8(&output.stdout).unwrap().trim());
    }

    #[test]
    fn test_error() {
        let result = false_cmd().run();
        if let Err(Error::Status(output)) = result {
            // Check that the status is non-zero.
            assert!(!output.status.success());
        } else {
            panic!("Expected a status error.");
        }
    }

    #[test]
    fn test_unchecked() {
        let unchecked_false = false_cmd().unchecked();
        // Unchecked errors shouldn't prevent the right side of `then` from
        // running, and they shouldn't cause `run` to return an error.
        let output = unchecked_false.then(cmd!(path_to_exe("echo"), "waa"))
            .then(unchecked_false)
            .stdout_capture()
            .run()
            .unwrap();
        // The value of the exit code is preserved.
        assert_eq!(1, output.status.code().unwrap());
        assert_eq!("waa", String::from_utf8_lossy(&output.stdout).trim());
    }

    #[test]
    fn test_unchecked_in_pipe() {
        let zero = cmd!(path_to_exe("status"), "0");
        let one = cmd!(path_to_exe("status"), "1");
        let two = cmd!(path_to_exe("status"), "2");

        // Right takes precedence over left.
        let output = one.pipe(two.clone()).unchecked().run().unwrap();
        assert_eq!(2, output.status.code().unwrap());

        // Except that checked on the left takes precedence over unchecked on
        // the right.
        let output = one.pipe(two.unchecked()).unchecked().run().unwrap();
        assert_eq!(1, output.status.code().unwrap());

        // Right takes precedence over the left again if they're both unchecked.
        let output = one.unchecked().pipe(two.unchecked()).unchecked().run().unwrap();
        assert_eq!(2, output.status.code().unwrap());

        // Except that if the right is a success, the left takes precedence.
        let output = one.unchecked().pipe(zero.unchecked()).unchecked().run().unwrap();
        assert_eq!(1, output.status.code().unwrap());

        // Even if the right is checked.
        let output = one.unchecked().pipe(zero).unchecked().run().unwrap();
        assert_eq!(1, output.status.code().unwrap());
    }

    #[test]
    fn test_pipe() {
        let output = sh("echo xxx").pipe(cmd!(path_to_exe("x_to_y"))).read().unwrap();
        assert_eq!("yyy", output);

        // Check that errors on either side are propagated.
        let result = true_cmd().pipe(false_cmd()).run();
        match result {
            Err(Error::Status(output)) => {
                assert!(output.status.code().unwrap() == 1);
            }
            _ => panic!("should never get here"),
        }

        let result = false_cmd().pipe(true_cmd()).run();
        match result {
            Err(Error::Status(output)) => {
                assert!(output.status.code().unwrap() == 1);
            }
            _ => panic!("should never get here"),
        }
    }

    #[test]
    fn test_then() {
        let output = true_cmd().then(sh("echo lo")).read().unwrap();
        assert_eq!("lo", output);

        // Check that errors on either side are propagated.
        let result = true_cmd().then(false_cmd()).run();
        match result {
            Err(Error::Status(output)) => {
                assert!(output.status.code().unwrap() == 1);
            }
            _ => panic!("should never get here"),
        }

        let result = false_cmd().then(true_cmd()).run();
        match result {
            Err(Error::Status(output)) => {
                assert!(output.status.code().unwrap() == 1);
            }
            _ => panic!("should never get here"),
        }
    }

    #[test]
    fn test_input() {
        let expr = cmd!(path_to_exe("x_to_y")).input("xxx");
        let output = expr.read().unwrap();
        assert_eq!("yyy", output);
    }

    #[test]
    fn test_stderr() {
        let (mut reader, writer) = ::os_pipe::pipe().unwrap();
        sh("echo hi>&2").stderr_file(File::from_file(writer)).run().unwrap();
        let mut s = String::new();
        reader.read_to_string(&mut s).unwrap();
        assert_eq!(s.trim(), "hi");
    }

    #[test]
    fn test_null() {
        let expr = cmd!(path_to_exe("cat"))
            .stdin_null()
            .stdout_null()
            .stderr_null();
        let output = expr.read().unwrap();
        assert_eq!("", output);
    }

    #[test]
    fn test_path() {
        let dir = TempDir::new("test_path").unwrap();
        let input_file = dir.path().join("input_file");
        let output_file = dir.path().join("output_file");
        File::create(&input_file).unwrap().write_all(b"xxx").unwrap();
        let expr = cmd!(path_to_exe("x_to_y"))
            .stdin(&input_file)
            .stdout(&output_file);
        let output = expr.read().unwrap();
        assert_eq!("", output);
        let mut file_output = String::new();
        File::open(&output_file).unwrap().read_to_string(&mut file_output).unwrap();
        assert_eq!("yyy", file_output);
    }

    #[test]
    fn test_swapping() {
        let output = sh("echo hi")
            .stdout_to_stderr()
            .stderr_capture()
            .run()
            .unwrap();
        let stderr = str::from_utf8(&output.stderr).unwrap().trim();
        assert_eq!("hi", stderr);

        // Windows compatible. (Requires no space before the ">".)
        let output = sh("echo hi>&2").stderr_to_stdout().read().unwrap();
        assert_eq!("hi", output);
    }

    #[test]
    fn test_file() {
        let dir = TempDir::new("test_file").unwrap();
        let file = dir.path().join("file");
        File::create(&file).unwrap().write_all(b"example").unwrap();
        let expr = cmd!(path_to_exe("cat")).stdin_file(File::open(&file).unwrap());
        let output = expr.read().unwrap();
        assert_eq!(output, "example");
    }

    #[test]
    fn test_ergonomics() {
        let mystr = "owned string".to_owned();
        let mypathbuf = Path::new("a/b/c").to_owned();
        let myvec = vec![1, 2, 3];
        // These are nonsense expressions. We just want to make sure they compile.
        let _ = sh("true").stdin(&*mystr).input(&*myvec).stdout(&*mypathbuf);
        let _ = sh("true").stdin(mystr).input(myvec).stdout(mypathbuf);

        // Unfortunately, this one doesn't work with our Into<Vec<u8>> bound on input().
        // TODO: Is it worth having these impls for &Vec in other cases?
        // let _ = sh("true").stdin(&mystr).input(&myvec).stdout(&mypathbuf);
    }

    #[test]
    fn test_capture_both() {
        // Windows compatible, no space before ">", and we trim newlines at the end to avoid
        // dealing with the different kinds.
        let output = sh("echo hi")
            .then(sh("echo lo>&2"))
            .stdout_capture()
            .stderr_capture()
            .run()
            .unwrap();
        assert_eq!("hi", str::from_utf8(&output.stdout).unwrap().trim());
        assert_eq!("lo", str::from_utf8(&output.stderr).unwrap().trim());
    }

    #[test]
    fn test_dir() {
        // This test checks the interaction of `dir` and relative exe paths.
        // Make sure that's actually what we're testing.
        let pwd_path = path_to_exe("pwd");
        assert!(pwd_path.is_relative());

        let pwd = cmd!(pwd_path);

        // First assert that ordinary commands happen in the parent's dir.
        let pwd_output = pwd.read().unwrap();
        let pwd_path = Path::new(&pwd_output);
        assert_eq!(pwd_path, env::current_dir().unwrap());

        // Now create a temp dir and make sure we can set dir to it. This
        // also tests the interaction of `dir` and relative exe paths.
        let dir = TempDir::new("duct_test").unwrap();
        let pwd_output = pwd.dir(dir.path()).read().unwrap();
        let pwd_path = Path::new(&pwd_output);
        // pwd_path isn't totally canonical on Windows, because it
        // doesn't have a prefix. Thus we have to canonicalize both
        // sides. (This also handles symlinks in TMP_DIR.)
        assert_eq!(pwd_path.canonicalize().unwrap(),
                   dir.path().canonicalize().unwrap());
    }

    #[test]
    fn test_env() {
        let output = cmd!(path_to_exe("print_env"), "foo")
            .env("foo", "bar")
            .read()
            .unwrap();
        assert_eq!("bar", output);
    }

    #[test]
    fn test_full_env() {
        let var_name = "test_env_remove_var";

        // Capture the parent env, and make sure it does *not* contain our variable.
        let mut clean_env: HashMap<OsString, OsString> = env::vars_os().collect();
        clean_env.remove(AsRef::<OsStr>::as_ref(var_name));

        // Run a child process with that map passed to full_env(). It should be guaranteed not to
        // see our variable, regardless of any outer env() calls or changes in the parent.
        let clean_child = cmd!(path_to_exe("print_env"), var_name).full_env(clean_env);

        // Dirty the parent env. Should be suppressed.
        env::set_var(var_name, "junk1");
        // And make an outer env() call. Should also be suppressed.
        let dirty_child = clean_child.env(var_name, "junk2");

        // Check that neither of those have any effect.
        let output = dirty_child.read().unwrap();
        assert_eq!("", output);
    }

    #[test]
    fn test_broken_pipe() {
        // If the input writing thread fills up its pipe buffer, writing will block. If the process
        // on the other end of the pipe exits while writer is waiting, the write will return an
        // error. We need to swallow that error, rather than returning it.
        let myvec = vec![0; 1_000_000];
        true_cmd().input(myvec).run().unwrap();
    }

    #[test]
    fn test_suppress_broken_pipe() {
        let broken_pipe_error = Err(io::Error::new(io::ErrorKind::BrokenPipe, ""));
        assert!(::suppress_broken_pipe_errors(broken_pipe_error).is_ok());

        let other_error = Err(io::Error::new(io::ErrorKind::Other, ""));
        assert!(::suppress_broken_pipe_errors(other_error).is_err());
    }

    #[test]
    fn test_silly() {
        // A silly test, purely for coverage.
        ::IoValue::Null.try_clone().unwrap();
    }

    #[test]
    fn test_path_sanitization() {
        // We don't do any chdir'ing in this process, because the tests runner is multithreaded,
        // and we don't want to screw up anyone else's relative paths. Instead, we shell out to a
        // small test process that does that for us.
        cmd!(path_to_exe("exe_in_dir"), path_to_exe("status"), "0")
            .run()
            .unwrap();
    }
}