cmd-proc 0.5.0

Process command builder with capture support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
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
#![doc = include_str!("../README.md")]

use std::borrow::Cow;
use std::ffi::OsStr;
use std::marker::PhantomData;

#[derive(Debug, thiserror::Error)]
pub enum CommandError {
    #[error("command IO failure")]
    Io(#[source] std::io::Error),
    #[error("command exited with {0}")]
    ExitStatus(std::process::ExitStatus),
}

async fn write_stdin(
    child: &mut tokio::process::Child,
    stdin_data: Option<Vec<u8>>,
) -> Result<(), CommandError> {
    use tokio::io::AsyncWriteExt;

    if let Some(data) = stdin_data {
        child
            .stdin
            .take()
            .unwrap()
            .write_all(&data)
            .await
            .map_err(CommandError::Io)?;
    }

    Ok(())
}

async fn run_and_wait(
    mut child: tokio::process::Child,
    stdin_data: Option<Vec<u8>>,
    start: std::time::Instant,
) -> Result<std::process::Output, CommandError> {
    write_stdin(&mut child, stdin_data).await?;

    let output = child.wait_with_output().await.map_err(CommandError::Io)?;

    log::debug!(
        "exit_status={:?} runtime={:?}",
        output.status,
        start.elapsed()
    );

    Ok(output)
}

async fn run_and_wait_status(
    mut child: tokio::process::Child,
    stdin_data: Option<Vec<u8>>,
    start: std::time::Instant,
) -> Result<std::process::ExitStatus, CommandError> {
    write_stdin(&mut child, stdin_data).await?;

    let status = child.wait().await.map_err(CommandError::Io)?;

    log::debug!("exit_status={:?} runtime={:?}", status, start.elapsed());

    Ok(status)
}

/// Validated environment variable name.
///
/// Ensures the name is non-empty and does not contain `=`.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct EnvVariableName<'a>(Cow<'a, str>);

impl EnvVariableName<'_> {
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl AsRef<OsStr> for EnvVariableName<'_> {
    fn as_ref(&self) -> &OsStr {
        self.0.as_ref().as_ref()
    }
}

impl std::fmt::Display for EnvVariableName<'_> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl EnvVariableName<'static> {
    /// Validated environment variable name for `'static` inputs.
    ///
    /// # Panics
    ///
    /// Panics at compile time when used in a `const` context, or at runtime otherwise,
    /// if the name is empty or contains `=`.
    #[must_use]
    pub const fn from_static_or_panic(s: &'static str) -> Self {
        match validate_env_variable_name(s) {
            Ok(()) => {}
            Err(EnvVariableNameError::Empty) => {
                panic!("Environment variable name cannot be empty");
            }
            Err(EnvVariableNameError::ContainsEquals) => {
                panic!("Environment variable name cannot contain '='");
            }
        }
        Self(Cow::Borrowed(s))
    }
}

#[derive(Debug, thiserror::Error)]
pub enum EnvVariableNameError {
    #[error("Environment variable name cannot be empty")]
    Empty,
    #[error("Environment variable name cannot contain '='")]
    ContainsEquals,
}

impl std::str::FromStr for EnvVariableName<'static> {
    type Err = EnvVariableNameError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        validate_env_variable_name(s).map(|()| Self(Cow::Owned(s.to_string())))
    }
}

const fn validate_env_variable_name(s: &str) -> Result<(), EnvVariableNameError> {
    if s.is_empty() {
        return Err(EnvVariableNameError::Empty);
    }
    let bytes = s.as_bytes();
    let mut i = 0;
    // Iterator helpers are not const-stable yet; use a manual loop.
    while i < bytes.len() {
        if bytes[i] == b'=' {
            return Err(EnvVariableNameError::ContainsEquals);
        }
        i += 1;
    }
    Ok(())
}

mod sealed {
    pub trait Sealed {}
}

/// Marker trait for stream type parameters.
pub trait StreamMarker: sealed::Sealed {}

/// Marker type for stdout stream.
pub struct Stdout;

/// Marker type for stderr stream.
pub struct Stderr;

impl sealed::Sealed for Stdout {}
impl sealed::Sealed for Stderr {}
impl StreamMarker for Stdout {}
impl StreamMarker for Stderr {}

/// Result from capturing a single stream.
#[derive(Debug)]
pub struct CaptureSingleResult {
    pub bytes: Vec<u8>,
    pub status: std::process::ExitStatus,
}

/// Result from capturing both stdout and stderr.
#[derive(Debug)]
pub struct CaptureAllResult {
    pub stdout: Vec<u8>,
    pub stderr: Vec<u8>,
    pub status: std::process::ExitStatus,
}

async fn run_capture(
    mut command: Command,
    accept_nonzero_exit: bool,
) -> Result<std::process::Output, CommandError> {
    log::debug!("{:#?}", command.inner);

    if command.stdin_data.is_some() {
        command.inner.stdin(std::process::Stdio::piped());
    }

    let start = std::time::Instant::now();

    let child = command.inner.spawn().map_err(CommandError::Io)?;

    let output = run_and_wait(child, command.stdin_data, start).await?;

    if accept_nonzero_exit || output.status.success() {
        Ok(output)
    } else {
        Err(CommandError::ExitStatus(output.status))
    }
}

/// Builder for capturing a single stream from a command.
///
/// The type parameter `S` indicates which stream is being captured:
/// `Stdout` or `Stderr`.
pub struct CaptureSingle<S: StreamMarker> {
    inner: tokio::process::Command,
    stdin_data: Option<Vec<u8>>,
    accept_nonzero_exit: bool,
    _marker: PhantomData<S>,
}

impl<S: StreamMarker> CaptureSingle<S> {
    /// Accept non-zero exit status instead of treating it as an error.
    #[must_use]
    pub fn accept_nonzero_exit(mut self) -> Self {
        self.accept_nonzero_exit = true;
        self
    }
}

impl CaptureSingle<Stdout> {
    /// Also capture stderr, transitioning to [`CaptureAll`].
    #[must_use]
    pub fn stderr_capture(mut self) -> CaptureAll {
        self.inner.stdout(std::process::Stdio::piped());
        self.inner.stderr(std::process::Stdio::piped());
        CaptureAll {
            inner: self.inner,
            stdin_data: self.stdin_data,
            accept_nonzero_exit: self.accept_nonzero_exit,
        }
    }

    /// Redirect stderr to /dev/null.
    #[must_use]
    pub fn stderr_null(mut self) -> Self {
        self.inner.stderr(std::process::Stdio::null());
        self
    }

    /// Inherit stderr from the parent process (default).
    #[must_use]
    pub fn stderr_inherit(mut self) -> Self {
        self.inner.stderr(std::process::Stdio::inherit());
        self
    }

    /// Stop capturing stdout (null), transitioning back to [`Command`].
    #[must_use]
    pub fn stdout_null(mut self) -> Command {
        self.inner.stdout(std::process::Stdio::null());
        Command {
            inner: self.inner,
            stdin_data: self.stdin_data,
        }
    }

    /// Stop capturing stdout (inherit), transitioning back to [`Command`].
    #[must_use]
    pub fn stdout_inherit(mut self) -> Command {
        self.inner.stdout(std::process::Stdio::inherit());
        Command {
            inner: self.inner,
            stdin_data: self.stdin_data,
        }
    }

    /// Execute the command and return captured stdout.
    pub async fn run(mut self) -> Result<CaptureSingleResult, CommandError> {
        self.inner.stdout(std::process::Stdio::piped());

        let command = Command {
            inner: self.inner,
            stdin_data: self.stdin_data,
        };

        let output = run_capture(command, self.accept_nonzero_exit).await?;

        Ok(CaptureSingleResult {
            bytes: output.stdout,
            status: output.status,
        })
    }

    /// Execute the command and return captured stdout as bytes.
    pub async fn bytes(self) -> Result<Vec<u8>, CommandError> {
        Ok(self.run().await?.bytes)
    }

    /// Execute the command and return captured stdout as a UTF-8 string.
    pub async fn string(self) -> Result<String, CommandError> {
        let bytes = self.bytes().await?;
        String::from_utf8(bytes).map_err(|utf8_error| {
            CommandError::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                utf8_error,
            ))
        })
    }
}

impl CaptureSingle<Stderr> {
    /// Also capture stdout, transitioning to [`CaptureAll`].
    #[must_use]
    pub fn stdout_capture(mut self) -> CaptureAll {
        self.inner.stdout(std::process::Stdio::piped());
        self.inner.stderr(std::process::Stdio::piped());
        CaptureAll {
            inner: self.inner,
            stdin_data: self.stdin_data,
            accept_nonzero_exit: self.accept_nonzero_exit,
        }
    }

    /// Redirect stdout to /dev/null.
    #[must_use]
    pub fn stdout_null(mut self) -> Self {
        self.inner.stdout(std::process::Stdio::null());
        self
    }

    /// Inherit stdout from the parent process (default).
    #[must_use]
    pub fn stdout_inherit(mut self) -> Self {
        self.inner.stdout(std::process::Stdio::inherit());
        self
    }

    /// Stop capturing stderr (null), transitioning back to [`Command`].
    #[must_use]
    pub fn stderr_null(mut self) -> Command {
        self.inner.stderr(std::process::Stdio::null());
        Command {
            inner: self.inner,
            stdin_data: self.stdin_data,
        }
    }

    /// Stop capturing stderr (inherit), transitioning back to [`Command`].
    #[must_use]
    pub fn stderr_inherit(mut self) -> Command {
        self.inner.stderr(std::process::Stdio::inherit());
        Command {
            inner: self.inner,
            stdin_data: self.stdin_data,
        }
    }

    /// Execute the command and return captured stderr.
    pub async fn run(mut self) -> Result<CaptureSingleResult, CommandError> {
        self.inner.stderr(std::process::Stdio::piped());

        let command = Command {
            inner: self.inner,
            stdin_data: self.stdin_data,
        };

        let output = run_capture(command, self.accept_nonzero_exit).await?;

        Ok(CaptureSingleResult {
            bytes: output.stderr,
            status: output.status,
        })
    }

    /// Execute the command and return captured stderr as bytes.
    pub async fn bytes(self) -> Result<Vec<u8>, CommandError> {
        Ok(self.run().await?.bytes)
    }

    /// Execute the command and return captured stderr as a UTF-8 string.
    pub async fn string(self) -> Result<String, CommandError> {
        let bytes = self.bytes().await?;
        String::from_utf8(bytes).map_err(|utf8_error| {
            CommandError::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                utf8_error,
            ))
        })
    }
}

/// Builder for capturing both stdout and stderr from a command.
pub struct CaptureAll {
    inner: tokio::process::Command,
    stdin_data: Option<Vec<u8>>,
    accept_nonzero_exit: bool,
}

impl CaptureAll {
    /// Accept non-zero exit status instead of treating it as an error.
    #[must_use]
    pub fn accept_nonzero_exit(mut self) -> Self {
        self.accept_nonzero_exit = true;
        self
    }

    /// Stop capturing stdout (null), transitioning to [`CaptureSingle<Stderr>`].
    #[must_use]
    pub fn stdout_null(mut self) -> CaptureSingle<Stderr> {
        self.inner.stdout(std::process::Stdio::null());
        CaptureSingle {
            inner: self.inner,
            stdin_data: self.stdin_data,
            accept_nonzero_exit: self.accept_nonzero_exit,
            _marker: PhantomData,
        }
    }

    /// Stop capturing stdout (inherit), transitioning to [`CaptureSingle<Stderr>`].
    #[must_use]
    pub fn stdout_inherit(mut self) -> CaptureSingle<Stderr> {
        self.inner.stdout(std::process::Stdio::inherit());
        CaptureSingle {
            inner: self.inner,
            stdin_data: self.stdin_data,
            accept_nonzero_exit: self.accept_nonzero_exit,
            _marker: PhantomData,
        }
    }

    /// Stop capturing stderr (null), transitioning to [`CaptureSingle<Stdout>`].
    #[must_use]
    pub fn stderr_null(mut self) -> CaptureSingle<Stdout> {
        self.inner.stderr(std::process::Stdio::null());
        CaptureSingle {
            inner: self.inner,
            stdin_data: self.stdin_data,
            accept_nonzero_exit: self.accept_nonzero_exit,
            _marker: PhantomData,
        }
    }

    /// Stop capturing stderr (inherit), transitioning to [`CaptureSingle<Stdout>`].
    #[must_use]
    pub fn stderr_inherit(mut self) -> CaptureSingle<Stdout> {
        self.inner.stderr(std::process::Stdio::inherit());
        CaptureSingle {
            inner: self.inner,
            stdin_data: self.stdin_data,
            accept_nonzero_exit: self.accept_nonzero_exit,
            _marker: PhantomData,
        }
    }

    /// Execute the command and return captured output from both streams.
    pub async fn run(mut self) -> Result<CaptureAllResult, CommandError> {
        self.inner.stdout(std::process::Stdio::piped());
        self.inner.stderr(std::process::Stdio::piped());

        let command = Command {
            inner: self.inner,
            stdin_data: self.stdin_data,
        };

        let output = run_capture(command, self.accept_nonzero_exit).await?;

        Ok(CaptureAllResult {
            stdout: output.stdout,
            stderr: output.stderr,
            status: output.status,
        })
    }
}

pub struct Command {
    inner: tokio::process::Command,
    stdin_data: Option<Vec<u8>>,
}

impl Command {
    pub fn new(value: impl AsRef<OsStr>) -> Self {
        Command {
            inner: tokio::process::Command::new(value),
            stdin_data: None,
        }
    }

    /// Asserts that two commands are equal by comparing their `Debug` representations.
    ///
    /// This is useful for testing that a command builder produces the expected command
    /// without actually executing it.
    ///
    /// # Panics
    ///
    /// Panics if the `Debug` output of the two commands' inner `tokio::process::Command` differ.
    #[cfg(feature = "test-utils")]
    pub fn test_eq(&self, other: &Self) {
        assert_eq!(format!("{:?}", self.inner), format!("{:?}", other.inner));
    }

    pub fn argument(mut self, value: impl AsRef<OsStr>) -> Self {
        self.inner.arg(value);
        self
    }

    pub fn optional_argument(mut self, optional: Option<impl AsRef<OsStr>>) -> Self {
        if let Some(value) = optional {
            self.inner.arg(value);
        }
        self
    }

    /// Adds a flag argument only if the condition is `true`.
    ///
    /// ```rust
    /// let verbose = true;
    /// cmd_proc::Command::new("echo")
    ///     .optional_flag(verbose, "--verbose");
    /// ```
    pub fn optional_flag(mut self, condition: bool, flag: impl AsRef<OsStr>) -> Self {
        if condition {
            self.inner.arg(flag);
        }
        self
    }

    /// Adds a CLI option (name + value).
    ///
    /// ```rust
    /// cmd_proc::Command::new("git")
    ///     .option("--message", "hello");
    /// // equivalent to: .argument("--message").argument("hello")
    /// ```
    pub fn option(mut self, name: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> Self {
        self.inner.arg(name);
        self.inner.arg(value);
        self
    }

    /// Adds a CLI option (name + value) only if the value is `Some`.
    ///
    /// ```rust
    /// cmd_proc::Command::new("git")
    ///     .optional_option("--author", Some("Alice"));
    /// // adds "--author Alice" only if Some
    /// ```
    pub fn optional_option(
        mut self,
        name: impl AsRef<OsStr>,
        value: Option<impl AsRef<OsStr>>,
    ) -> Self {
        if let Some(value) = value {
            self.inner.arg(name);
            self.inner.arg(value);
        }
        self
    }

    pub fn arguments<T: AsRef<OsStr>>(mut self, value: impl IntoIterator<Item = T>) -> Self {
        self.inner.args(value);
        self
    }

    pub fn working_directory(mut self, dir: impl AsRef<std::path::Path>) -> Self {
        self.inner.current_dir(dir);
        self
    }

    pub fn env(mut self, key: &EnvVariableName<'_>, val: impl AsRef<OsStr>) -> Self {
        self.inner.env(key, val);
        self
    }

    pub fn envs<'a, I, V>(mut self, vars: I) -> Self
    where
        I: IntoIterator<Item = (EnvVariableName<'a>, V)>,
        V: AsRef<OsStr>,
    {
        for (key, val) in vars {
            self.inner.env(key, val);
        }
        self
    }

    /// Remove an environment variable from the child process.
    #[must_use]
    pub fn env_remove(mut self, key: &EnvVariableName<'_>) -> Self {
        self.inner.env_remove(key);
        self
    }

    #[must_use]
    pub fn stdin_bytes(mut self, data: impl Into<Vec<u8>>) -> Self {
        self.stdin_data = Some(data.into());
        self
    }

    /// Capture stdout from this command.
    #[must_use]
    pub fn stdout_capture(self) -> CaptureSingle<Stdout> {
        CaptureSingle {
            inner: self.inner,
            stdin_data: self.stdin_data,
            accept_nonzero_exit: false,
            _marker: PhantomData,
        }
    }

    /// Capture stderr from this command.
    #[must_use]
    pub fn stderr_capture(self) -> CaptureSingle<Stderr> {
        CaptureSingle {
            inner: self.inner,
            stdin_data: self.stdin_data,
            accept_nonzero_exit: false,
            _marker: PhantomData,
        }
    }

    /// Redirect stdout to /dev/null.
    #[must_use]
    pub fn stdout_null(mut self) -> Self {
        self.inner.stdout(std::process::Stdio::null());
        self
    }

    /// Redirect stderr to /dev/null.
    #[must_use]
    pub fn stderr_null(mut self) -> Self {
        self.inner.stderr(std::process::Stdio::null());
        self
    }

    /// Inherit stdout from the parent process (default).
    #[must_use]
    pub fn stdout_inherit(mut self) -> Self {
        self.inner.stdout(std::process::Stdio::inherit());
        self
    }

    /// Inherit stderr from the parent process (default).
    #[must_use]
    pub fn stderr_inherit(mut self) -> Self {
        self.inner.stderr(std::process::Stdio::inherit());
        self
    }

    /// Consume the builder and return the underlying `tokio::process::Command`.
    ///
    /// Use this when you need full control over the child process (e.g.
    /// interactive stdin/stdout piping) beyond what the capture API provides.
    #[must_use]
    pub fn build(self) -> tokio::process::Command {
        self.inner
    }

    /// Execute the command and return success or an error.
    pub async fn status(mut self) -> Result<(), CommandError> {
        use std::process::Stdio;

        log::debug!("{:#?}", self.inner);

        if self.stdin_data.is_some() {
            self.inner.stdin(Stdio::piped());
        }

        let start = std::time::Instant::now();

        let child = self.inner.spawn().map_err(CommandError::Io)?;

        let exit_status = run_and_wait_status(child, self.stdin_data, start).await?;

        if exit_status.success() {
            Ok(())
        } else {
            Err(CommandError::ExitStatus(exit_status))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_stdout_bytes_success() {
        assert_eq!(
            Command::new("echo")
                .argument("hello")
                .stdout_capture()
                .bytes()
                .await
                .unwrap(),
            b"hello\n"
        );
    }

    #[tokio::test]
    async fn test_stdout_bytes_nonzero_exit() {
        let error = Command::new("sh")
            .arguments(["-c", "exit 42"])
            .stdout_capture()
            .bytes()
            .await
            .unwrap_err();
        let CommandError::ExitStatus(status) = error else {
            panic!("expected ExitStatus, got {error:?}");
        };
        assert_eq!(status.code(), Some(42));
    }

    #[tokio::test]
    async fn test_stdout_bytes_io_error() {
        let error = Command::new("./nonexistent")
            .stdout_capture()
            .bytes()
            .await
            .unwrap_err();
        let CommandError::Io(io_error) = error else {
            panic!("expected Io, got {error:?}");
        };
        assert_eq!(io_error.kind(), std::io::ErrorKind::NotFound);
    }

    #[tokio::test]
    async fn test_stdout_string_success() {
        assert_eq!(
            Command::new("echo")
                .argument("hello")
                .stdout_capture()
                .string()
                .await
                .unwrap(),
            "hello\n"
        );
    }

    #[tokio::test]
    async fn test_stderr_bytes_success() {
        assert_eq!(
            Command::new("sh")
                .arguments(["-c", "echo error >&2"])
                .stderr_capture()
                .bytes()
                .await
                .unwrap(),
            b"error\n"
        );
    }

    #[tokio::test]
    async fn test_stderr_string_success() {
        assert_eq!(
            Command::new("sh")
                .arguments(["-c", "echo error >&2"])
                .stderr_capture()
                .string()
                .await
                .unwrap(),
            "error\n"
        );
    }

    #[tokio::test]
    async fn test_status_success() {
        assert!(Command::new("true").status().await.is_ok());
    }

    #[tokio::test]
    async fn test_status_nonzero_exit() {
        let error = Command::new("sh")
            .arguments(["-c", "exit 42"])
            .status()
            .await
            .unwrap_err();
        let CommandError::ExitStatus(status) = error else {
            panic!("expected ExitStatus, got {error:?}");
        };
        assert_eq!(status.code(), Some(42));
    }

    #[tokio::test]
    async fn test_status_io_error() {
        let error = Command::new("./nonexistent").status().await.unwrap_err();
        let CommandError::Io(io_error) = error else {
            panic!("expected Io, got {error:?}");
        };
        assert_eq!(io_error.kind(), std::io::ErrorKind::NotFound);
    }

    #[test]
    fn test_env_variable_name_from_static_or_panic() {
        const NAME: EnvVariableName<'static> = EnvVariableName::from_static_or_panic("PATH");
        assert_eq!(NAME.as_str(), "PATH");
    }

    #[test]
    fn test_env_variable_name_parse() {
        let name: EnvVariableName = "HOME".parse().unwrap();
        assert_eq!(name.as_str(), "HOME");
    }

    #[test]
    fn test_env_variable_name_empty() {
        let result: Result<EnvVariableName, _> = "".parse();
        assert!(matches!(result, Err(EnvVariableNameError::Empty)));
    }

    #[test]
    fn test_env_variable_name_contains_equals() {
        let result: Result<EnvVariableName, _> = "FOO=BAR".parse();
        assert!(matches!(result, Err(EnvVariableNameError::ContainsEquals)));
    }

    #[tokio::test]
    async fn test_env_with_variable() {
        let name: EnvVariableName = "MY_VAR".parse().unwrap();
        let output = Command::new("sh")
            .arguments(["-c", "echo $MY_VAR"])
            .env(&name, "hello")
            .stdout_capture()
            .string()
            .await
            .unwrap();
        assert_eq!(output, "hello\n");
    }

    #[tokio::test]
    async fn test_stdin_bytes() {
        let output = Command::new("cat")
            .stdin_bytes(b"hello world".as_slice())
            .stdout_capture()
            .string()
            .await
            .unwrap();
        assert_eq!(output, "hello world");
    }

    #[tokio::test]
    async fn test_stdin_bytes_vec() {
        let output = Command::new("cat")
            .stdin_bytes(vec![104, 105])
            .stdout_capture()
            .string()
            .await
            .unwrap();
        assert_eq!(output, "hi");
    }

    #[tokio::test]
    async fn test_capture_all_success() {
        let result = Command::new("echo")
            .argument("hello")
            .stdout_capture()
            .stderr_capture()
            .run()
            .await
            .unwrap();
        assert!(result.status.success());
        assert_eq!(result.stdout, b"hello\n");
        assert!(result.stderr.is_empty());
    }

    #[tokio::test]
    async fn test_capture_all_failure_with_stderr() {
        let result = Command::new("sh")
            .arguments(["-c", "echo error >&2; exit 1"])
            .stdout_capture()
            .stderr_capture()
            .accept_nonzero_exit()
            .run()
            .await
            .unwrap();
        assert!(!result.status.success());
        assert_eq!(String::from_utf8(result.stderr).unwrap(), "error\n");
    }

    #[tokio::test]
    async fn test_capture_all_io_error() {
        let error = Command::new("./nonexistent")
            .stdout_capture()
            .stderr_capture()
            .run()
            .await
            .unwrap_err();
        let CommandError::Io(io_error) = error else {
            panic!("expected Io, got {error:?}");
        };
        assert_eq!(io_error.kind(), std::io::ErrorKind::NotFound);
    }

    #[tokio::test]
    async fn test_build() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        let mut child = Command::new("cat")
            .build()
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .spawn()
            .unwrap();

        child
            .stdin
            .as_mut()
            .unwrap()
            .write_all(b"hello")
            .await
            .unwrap();
        drop(child.stdin.take());

        let mut output = String::new();
        child
            .stdout
            .as_mut()
            .unwrap()
            .read_to_string(&mut output)
            .await
            .unwrap();
        assert_eq!(output, "hello");

        let status = child.wait().await.unwrap();
        assert!(status.success());
    }

    #[tokio::test]
    async fn test_option() {
        let output = Command::new("echo")
            .option("-n", "hello")
            .stdout_capture()
            .string()
            .await
            .unwrap();
        assert_eq!(output, "hello");
    }

    #[tokio::test]
    async fn test_optional_option_some() {
        let output = Command::new("echo")
            .optional_option("-n", Some("hello"))
            .stdout_capture()
            .string()
            .await
            .unwrap();
        assert_eq!(output, "hello");
    }

    #[tokio::test]
    async fn test_optional_option_none() {
        let output = Command::new("echo")
            .optional_option("-n", None::<&str>)
            .argument("hello")
            .stdout_capture()
            .string()
            .await
            .unwrap();
        assert_eq!(output, "hello\n");
    }

    #[tokio::test]
    async fn test_optional_flag_true() {
        let output = Command::new("echo")
            .optional_flag(true, "-n")
            .argument("hello")
            .stdout_capture()
            .string()
            .await
            .unwrap();
        assert_eq!(output, "hello");
    }

    #[tokio::test]
    async fn test_optional_flag_false() {
        let output = Command::new("echo")
            .optional_flag(false, "-n")
            .argument("hello")
            .stdout_capture()
            .string()
            .await
            .unwrap();
        assert_eq!(output, "hello\n");
    }

    #[tokio::test]
    async fn test_stdout_null() {
        // stdout_null should discard output; command should still succeed
        Command::new("echo")
            .argument("hello")
            .stdout_null()
            .status()
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn test_stderr_null() {
        // stderr_null should discard stderr; command should still succeed
        Command::new("sh")
            .arguments(["-c", "echo error >&2"])
            .stderr_null()
            .status()
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn test_stdout_capture_stderr_null() {
        let output = Command::new("sh")
            .arguments(["-c", "echo out; echo err >&2"])
            .stdout_capture()
            .stderr_null()
            .string()
            .await
            .unwrap();
        assert_eq!(output, "out\n");
    }

    #[tokio::test]
    async fn test_accept_nonzero_exit_stdout() {
        let result = Command::new("sh")
            .arguments(["-c", "echo out; exit 42"])
            .stdout_capture()
            .accept_nonzero_exit()
            .run()
            .await
            .unwrap();
        assert!(!result.status.success());
        assert_eq!(result.bytes, b"out\n");
    }

    #[tokio::test]
    async fn test_accept_nonzero_exit_capture_all() {
        let result = Command::new("sh")
            .arguments(["-c", "echo out; echo err >&2; exit 42"])
            .stdout_capture()
            .stderr_capture()
            .accept_nonzero_exit()
            .run()
            .await
            .unwrap();
        assert!(!result.status.success());
        assert_eq!(result.stdout, b"out\n");
        assert_eq!(result.stderr, b"err\n");
    }
}