fun_run 0.7.0

The fun way to run your Rust Command
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
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
//! # Fun Run
//!
//! What does the "Zombie Zoom 5K", the "Wibbly wobbly log jog", and the "Turkey Trot" have in common?
//! They're runs with a fun name! That's exactly what `fun_run` does. It makes running your Rust [`Command`]s
//! more fun, by naming them.
//!
//! ## What is Fun Run?
//!
//! Fun run is designed for the use case where not only do you want to run a [`Command`] you want to
//! output what you're running and what happened. Building a CLI tool is a great use case. Another is
//! creating [a buildpack](https://github.com/heroku/buildpacks-ruby/tree/4f514f6046568ada523eefd41b3024f86f1c67ce).
//!
//! Here's some things you can do with fun_run:
//!
//! - Advertise the command being run before execution
//! - Customize how commands are displayed
//! - Return error messages with the command name.
//! - Turn non-zero status results into an error
//! - Embed stdout and stderr into errors (when not streamed)
//! - Store stdout and stderr for debug and diagnosis without displaying them (when streamed)
//!
//! Just like you don't need to dress up in a giant turkey costume to run a 5K you also don't **need**
//! `fun_run` to do these things. Though, unlike the turkey costume, using `fun_run` will also make the
//! experience easier.
//!
//! ## Install
//!
//! ```shell
//! $ cargo add fun_run
//! ```
//!
//! ## Ready to Roll
//!
//! For a quick and easy fun run you can use the `fun_run::CommandWithName` trait extension to stream
//! output:
//!
//! ```rust,no_run
//! use fun_run::CommandWithName;
//! use std::process::Command;
//!
//! let mut cmd = Command::new("bundle");
//! cmd.args(["install"]);
//!
//! // Advertise the command being run before execution
//! println!("Running `{name}`", name = cmd.name());
//!
//! // Stream output to the end user
//! // Turn non-zero status results into an error
//! let result = cmd
//!     .stream_output(std::io::stdout(), std::io::stderr());
//!
//! // Command name is persisted on success or failure
//! match result {
//!     Ok(output) => {
//!         assert_eq!("bundle install", &output.name())
//!     },
//!     Err(cmd_error) => {
//!         assert_eq!("bundle install", &cmd_error.name())
//!     }
//! }
//! ```
//!
//! ## Pretty (good) errors
//!
//! Fun run comes with nice errors by default:
//!
//! ```rust
//! use fun_run::CommandWithName;
//! use std::process::Command;
//!
//! let mut cmd = Command::new("becho");
//! cmd.args(["hello", "world"]);
//!
//! let expected = r#"Could not run command `becho hello world`. No such file or directory"#;
//! match cmd.stream_output(std::io::stdout(), std::io::stderr()) {
//!     Ok(_) => todo!(),
//!     Err(cmd_error) => {
//!         let actual = cmd_error.to_string();
//!         assert!(actual.contains(expected), "Expected {actual:?} to contain {expected:?}, but it did not")
//!     }
//! }
//! ```
//!
//! And commands that don't return an exit code 0 return an Err so you don't accidentally ignore a
//! failure, and the output of the command is captured:
//!
//! ```rust
//! use fun_run::CommandWithName;
//! use std::process::Command;
//!
//! let mut cmd = Command::new("bash");
//! cmd.arg("-c");
//! cmd.arg("echo -n 'hello world' && exit 1");
//!
//! // Quietly gets output
//! match cmd.named_output() {
//!     Ok(_) => todo!(),
//!     Err(cmd_error) => {
//!         let expected = r#"
//! Command failed `bash -c "echo -n 'hello world' && exit 1"`
//! exit status: 1
//! stdout: hello world
//! stderr: <empty>
//!         "#;
//!
//!         let actual = cmd_error.to_string();
//!         assert!(
//!             actual.trim().contains(expected.trim()),
//!             "Expected {:?} to contain {:?}, but it did not", actual.trim(), expected.trim()
//!         )
//!     }
//! }
//! ```
//!
//! By default, streamed output won't duplicated in error messages (but is still there if you want
//! to inspect it in your program):
//!
//! ```rust
//! use fun_run::CommandWithName;
//! use std::process::Command;
//!
//! let mut cmd = Command::new("bash");
//! cmd.arg("-c");
//! cmd.arg("echo -n 'hello world' && exit 1");
//!
//!
//! let expected = r#"
//! Command failed `bash -c "echo -n 'hello world' && exit 1"`
//! exit status: 1
//! stdout: <see above>
//! stderr: <see above>
//! "#;
//!
//! // Quietly gets output
//! match cmd.stream_output(std::io::stdout(), std::io::stderr()) {
//!     Ok(_) => todo!(),
//!     Err(cmd_error) => {
//!         let actual = cmd_error.to_string();
//!         assert!(
//!             actual.trim().contains(expected.trim()),
//!             "Expected {:?} to contain {:?}, but it did not", actual.trim(), expected.trim()
//!         );
//!
//!         let named_output: fun_run::NamedOutput = cmd_error.into();
//!
//!         assert_eq!(
//!             "hello world",
//!             named_output.stdout_lossy().trim()
//!         );
//!
//!         assert_eq!(
//!             "bash -c \"echo -n 'hello world' && exit 1\"",
//!             named_output.name()
//!         );
//!     }
//! }
//! ```
//!
//! ## Renaming
//!
//! If you need to provide an alternate display for your command you can rename it, this is useful
//! for omitting implementation details.
//!
//! ```rust
//! use fun_run::CommandWithName;
//! use std::process::Command;
//!
//! let mut cmd = Command::new("bash");
//! cmd.arg("-c");
//! cmd.arg("echo -n 'hello world' && exit 1");
//!
//! let mut renamed_cmd = cmd.named("echo 'hello world'");
//!
//! assert_eq!("echo 'hello world'", &renamed_cmd.name());
//! ```
//!
//! This is also useful for adding additional information, such as environment variables:
//!
//! ```rust
//! use fun_run::CommandWithName;
//! use std::process::Command;
//!
//! let mut cmd = Command::new("bundle");
//! cmd.arg("install");
//!
//! let env_vars = std::env::vars();
//! # let mut env_vars = std::collections::HashMap::<String, String>::new();
//! # env_vars.insert("RAILS_ENV".to_string(), "production".to_string());
//!
//! let mut renamed_cmd = cmd.named_fn(|cmd| fun_run::display_with_env_keys(
//!     cmd,
//!     env_vars,
//!     ["RAILS_ENV"]
//! ));
//!
//! assert_eq!(r#"RAILS_ENV="production" bundle install"#, renamed_cmd.name())
//! ```
//!
//! ## Debugging system failures with `which_problem`
//!
//! When a command execution returns an Err due to a system error (and not because the program it
//! executed launched but returned non-zero status), it's usually because the executable couldn't be
//! found, or if it was found, it couldn't be launched, for example due to a permissions error. The
//! [which_problem](https://github.com/schneems/which_problem) crate is designed to add debugging errors
//! to help you identify why the command couldn't be launched.
//!
//! The name `which_problem` works like `which` but helps you identify common mistakes such as typos:
//!
//! ```shell
//! $ cargo whichp zuby
//! Program "zuby" not found
//!
//! Info: No other executables with the same name are found on the PATH
//!
//! Info: These executables have the closest spelling to "zuby" but did not match:
//!       "hub", "ruby", "subl"
//! ```
//!
//! Fun run supports `which_problem` integration through the `which_problem` feature. In your `Cargo.toml`:
//!
//! ```toml
//! # Cargo.toml
//! fun_run = { version = <version.here>, features = ["which_problem"] }
//! ```
//!
//! And annotate errors:
//!
//! ```rust,no_run
//! use fun_run::CommandWithName;
//! use std::process::Command;
//!
//! let mut cmd = Command::new("becho");
//! cmd.args(["hello", "world"]);
//!
//! #[cfg(feature = "which_problem")]
//! cmd.stream_output(std::io::stdout(), std::io::stderr())
//!     .map_err(|error| fun_run::map_which_problem(error, cmd.mut_cmd(), std::env::var_os("PATH"))).unwrap();
//! ```
//!
//! Now if the system cannot find a `becho` program on your system the output will give you all the
//! info you need to diagnose the underlying issue.
//!
//! Note that `which_problem` integration is not enabled by default because it outputs information
//! about the contents of your disk such as layout and file permissions.
//!
//! ## What won't it do?
//!
//! The `fun_run` library doesn't support executing a [`Command`] in ways that do not produce an
//! [`Output`], for example calling [`Command::spawn`](https://doc.rust-lang.org/std/process/struct.Command.html#method.spawn) returns a `Result<std::process::Child, std::io::Error>`
//! (Which doesn't contain an [`Output`]). If you want to run-for-fun in the background, spawn a thread
//! and join it manually:
//!
//! ```no_run
//! use fun_run::CommandWithName;
//! use std::process::Command;
//! use std::thread;
//!
//! let mut cmd = Command::new("bundle");
//! cmd.args(["install"]);
//!
//! // Advertise the command being run before execution
//! println!("Quietly Running `{name}` in the background", name = cmd.name());
//!
//! let result = thread::spawn(move || {
//!     cmd.named_output()
//! }).join().unwrap();
//!
//! // Command name is persisted on success or failure
//! match result {
//!     Ok(output) => {
//!         assert_eq!("bundle install", &output.name())
//!     },
//!     Err(cmd_error) => {
//!         assert_eq!("bundle install", &cmd_error.name())
//!     }
//! }
//! ```
//!
//! ## FUN(ctional)
//!
//! If you don't want to use the trait, you can still use `fun_run` by functionally mapping the
//! features you want:
//!
//! ```no_run
//! let mut cmd = std::process::Command::new("bundle");
//! cmd.args(["install"]);
//!
//! let name = fun_run::display(&mut cmd);
//!
//! cmd.output()
//!     .map_err(|error| fun_run::on_system_error(name.clone(), error))
//!     .and_then(|output| fun_run::nonzero_captured(name.clone(), output))
//!     .unwrap();
//! ```
//!
//! Here's some fun functions you can use to help you run:
//!
//! - [`on_system_error`] - Convert [`std::io::Error`] into [`CmdError`]
//! - [`nonzero_streamed`] - Produces a [`NamedOutput`] from [`Output`] that has already been streamed to
//!   the user
//! - [`nonzero_captured`] - Like [`nonzero_streamed`] but for when the user hasn't already seen the
//!   output
//! - [`display`] - Converts an `&mut Command` into a human readable string
//! - [`display_with_env_keys`] - Like [`display`] but selectively shows environment variables.
//!
//! ## Async
//!
//! This library uses synchronous command execution. If you’re using this library in an async context,
//! you’ll want to use an async wrapper like [tokio::task::block_in_place](https://docs.rs/tokio/latest/tokio/task/fn.block_in_place.html).

use command::output_and_write_streams;
use regex::Regex;
use std::ffi::OsString;
use std::fmt::Display;
use std::io::Write;
use std::process::Command;
use std::process::ExitStatus;
use std::process::Output;
use std::sync::LazyLock;
#[cfg(feature = "which_problem")]
use which_problem::Which;

mod command;

/// Rename your commands:
///
/// ```no_run
/// use fun_run::CommandWithName;
/// use std::process::Command;
///
/// let result = Command::new("gem")
///     .args(["install", "bundler", "-v", "2.4.1.7"])
///     // Overwrites default command name which would include extra arguments
///     .named("gem install")
///     .stream_output(std::io::stdout(), std::io::stderr());
///
/// match result {
///     Ok(output) => {
///         assert_eq!("bundle install", &output.name())
///     },
///     Err(variant) => {
///         assert_eq!("bundle install", &variant.name())
///     }
/// }
/// ```
///
/// Or include important env vars in the name:
///
/// ```no_run
/// use fun_run::{self, CommandWithName};
/// use std::process::Command;
/// use std::collections::HashMap;
///
/// let env = std::env::vars_os().collect::<HashMap<_, _>>();
///
///  let result = Command::new("gem")
///      .args(["install", "bundler", "-v", "2.4.1.7"])
///      .envs(&env)
///      // Overwrites default command name
///      .named_fn(|cmd| {
///          // Annotate command with GEM_HOME env var
///          fun_run::display_with_env_keys(cmd, &env, ["GEM_HOME"])
///      })
///      .stream_output(std::io::stdout(), std::io::stderr());
///
///  match result {
///      Ok(output) => {
///          assert_eq!(
///              "GEM_HOME=\"/usr/bin/local/.gems\" gem install bundler -v 2.4.1.7",
///              &output.name()
///          )
///      }
///      Err(variant) => {
///          assert_eq!(
///              "GEM_HOME=\"/usr/bin/local/.gems\" gem install bundler -v 2.4.1.7",
///              &variant.name()
///          )
///      }
///  }
/// ```
pub trait CommandWithName {
    /// Returns the desired display name of the command
    fn name(&mut self) -> String;

    /// Returns a reference to `&mut Command`
    ///
    /// This is useful for passing to other libraries.
    fn mut_cmd(&mut self) -> &mut Command;

    /// Rename a command via a given string
    ///
    /// This can be useful if a part of the command is distracting or surprising or if you
    /// desire to include additional information such as displaying environment variables.
    ///
    /// Alternatively see [CommandWithName::named_fn]
    ///
    /// Example:
    ///
    /// ```
    /// use fun_run::CommandWithName;
    ///
    /// let mut command = std::process::Command::new("bin/bundle");
    /// command.arg("install");
    /// command.arg("--no-doc");
    ///
    /// let mut cmd = command.named("bundle install");
    /// assert_eq!("bundle install", cmd.name());
    /// ```
    fn named(&mut self, s: impl AsRef<str>) -> NamedCommand<'_> {
        let name = s.as_ref().to_string();
        let command = self.mut_cmd();
        NamedCommand { name, command }
    }

    /// Rename a command via a given function
    ///
    /// This can be useful if a part of the command is distracting or surprising or if you
    /// desire to include additional information such as displaying environment variables.
    ///
    /// Alternatively see [CommandWithName::named]
    ///
    /// Example:
    ///
    /// ```
    /// use fun_run::CommandWithName;
    ///
    /// let mut command = std::process::Command::new("bundle");
    /// command.arg("install");
    ///
    /// let mut cmd = command.named_fn(|cmd| cmd.name().replace("bundle", "bin/bundle").to_string());
    /// assert_eq!("bin/bundle install", cmd.name());
    /// ```
    #[allow(clippy::needless_lifetimes)]
    fn named_fn<'a>(&'a mut self, f: impl FnOnce(&mut Command) -> String) -> NamedCommand<'a> {
        let cmd = self.mut_cmd();
        let name = f(cmd);
        self.named(name)
    }

    /// Runs the command without streaming
    ///
    /// # Errors
    ///
    /// Returns `CmdError::SystemError` if the system is unable to run the command.
    /// Returns `CmdError::NonZeroExitNotStreamed` if the exit code is not zero.
    fn named_output(&mut self) -> Result<NamedOutput, CmdError> {
        let name = self.name();
        self.mut_cmd()
            .output()
            .map_err(|io_error| CmdError::SystemError(name.clone(), io_error))
            .map(|output| NamedOutput {
                name: name.clone(),
                output,
            })
            .and_then(NamedOutput::nonzero_captured)
    }

    /// Runs the command and streams to the given writers
    ///
    /// # Errors
    ///
    /// Returns `CmdError::SystemError` if the system is unable to run the command
    /// Returns `CmdError::NonZeroExitAlreadyStreamed` if the exit code is not zero.
    fn stream_output<OW, EW>(
        &mut self,
        stdout_write: OW,
        stderr_write: EW,
    ) -> Result<NamedOutput, CmdError>
    where
        OW: Write + Send,
        EW: Write + Send,
    {
        let name = &self.name();
        let cmd = self.mut_cmd();

        output_and_write_streams(cmd, stdout_write, stderr_write)
            .map_err(|io_error| CmdError::SystemError(name.clone(), io_error))
            .map(|output| NamedOutput {
                name: name.clone(),
                output,
            })
            .and_then(NamedOutput::nonzero_streamed)
    }
}

impl CommandWithName for Command {
    fn name(&mut self) -> String {
        crate::display(self)
    }

    fn mut_cmd(&mut self) -> &mut Command {
        self
    }
}

impl CommandWithName for &mut Command {
    fn name(&mut self) -> String {
        crate::display(self)
    }

    fn mut_cmd(&mut self) -> &mut Command {
        self
    }
}

/// It's a command, with a name
///
/// This struct allows us to re-name an existing [Command] via the [CommandWithName] trait associated
/// functions. When one of those functions such as [CommandWithName::named_fn] or [CommandWithName::named]
/// are called, Rust needs somewhere for the new name string to live, so we move it over into this struct
/// which also implements [CommandWithName]. You can gain access to the original [Command] reference
/// via [`CommandWithName::mut_cmd`]
pub struct NamedCommand<'a> {
    name: String,
    command: &'a mut Command,
}

impl<'a> From<&'a mut Command> for NamedCommand<'a> {
    /// Convert a [Command] reference into a [NamedCommand]
    ///
    /// Useful to "shorten" a command (to hide additional/unexpected flags).
    ///
    /// ```
    /// use fun_run::{NamedCommand, CommandWithName};
    ///
    /// let mut command = std::process::Command::new("go");
    /// let mut short: NamedCommand = command
    ///     .args(["list", "-tags", "heroku"])
    ///     .into();
    ///
    /// short
    ///     .mut_cmd()
    ///     .args([
    ///         "-f",
    ///         "{{ if eq .Name \"main\" }}{{ .ImportPath }}{{ end }}",
    ///         "./...",
    ///     ]);
    ///
    /// // Short name
    /// assert_eq!("go list -tags heroku", &short.name());
    /// // Full args
    /// assert_eq!("go", short.mut_cmd().get_program().to_str().unwrap());
    /// assert_eq!(
    ///     "list -tags heroku -f {{ if eq .Name \"main\" }}{{ .ImportPath }}{{ end }} ./...",
    ///     short
    ///         .mut_cmd()
    ///         .get_args()
    ///         .map(|arg| arg.to_str().unwrap())
    ///         .collect::<Vec<&str>>()
    ///         .join(" ")
    /// );
    /// ```
    fn from(command: &'a mut Command) -> Self {
        // Eventually we can deprecate `CommandWithName::named(String)` and change it
        // to `CommandWithName::rename(String)` and then have `CommandWithName::named()`
        // return a NamedCommand for better ergonomics
        NamedCommand {
            name: command.name(),
            command,
        }
    }
}

impl CommandWithName for NamedCommand<'_> {
    fn name(&mut self) -> String {
        self.name.to_string()
    }

    fn mut_cmd(&mut self) -> &mut Command {
        self.command
    }
}

impl CommandWithName for &mut NamedCommand<'_> {
    fn name(&mut self) -> String {
        self.name.to_string()
    }

    fn mut_cmd(&mut self) -> &mut Command {
        self.command
    }
}

/// Extension trait for [`Output`] to generate [`NamedOutput`]
///
/// The primary use case is exercising a function that takes [`NamedOutput`] in its arguments in a test.
///
/// ## Example
///
/// ```
/// use fun_run::OutputWithName;
///
/// let output = std::process::Output {
///     status: std::process::ExitStatus::default(),
///     stdout: Vec::new(),
///     stderr: Vec::new()
/// };
///
/// let named: fun_run::NamedOutput = output.named("exit 0");
/// assert_eq!(String::from("exit 0"), named.name());
/// ```
///
/// For generating an [`Output`] with a non-zero status on Unix you can use [`ExitStatusFromCode::from_code`],
/// which builds the [`ExitStatus`] from a plain exit code without you having to bit-shift the raw wait status yourself:
///
/// ```
/// use fun_run::{OutputWithName, ExitStatusFromCode};
///
/// let output = std::process::Output {
///     status: std::process::ExitStatus::from_code(42),
///     stdout: Vec::new(),
///     stderr: Vec::new()
/// };
///
/// assert_eq!(42, output.status.code().unwrap());
///
/// let named: fun_run::NamedOutput = output.named("exit 42");
/// let result = named.nonzero_captured();
/// assert!(result.is_err());
/// ```
pub trait OutputWithName {
    #[must_use]
    fn named(self, s: impl AsRef<str>) -> NamedOutput;
}

impl OutputWithName for Output {
    fn named(self, s: impl AsRef<str>) -> NamedOutput {
        NamedOutput {
            name: s.as_ref().to_string(),
            output: self,
        }
    }
}

/// Extension trait for [`ExitStatus`] to build an instance based on exit code
///
/// Confusingly the [`std::os::unix::process::ExitStatusExt::from_raw`] function does NOT return its own input on Unix:
///
/// ```
/// # #[cfg(unix)] {
/// use std::process::ExitStatus;
/// use std::os::unix::process::ExitStatusExt;
///
/// let status = ExitStatus::from_raw(41);
/// assert_eq!(None, status.code());
///
/// // The input has to be bit-shifted by 8 to get it to work:
/// let status = ExitStatus::from_raw(41<<8);
/// assert_eq!(Some(41), status.code());
/// # }
/// ```
///
/// That's because the input isn't an exit code but rather data structure from `wait` <https://pubs.opengroup.org/onlinepubs/9799919799/functions/wait.html>.
/// To input a known status code, you can bitshift it by 8 OR you can use this nice helper extension
/// trait:
///
/// ```
/// use std::process::ExitStatus;
/// use fun_run::ExitStatusFromCode;
///
/// let status = ExitStatus::from_code(41);
/// assert_eq!(Some(41), status.code());
/// ```
///
/// The main use case for generating a manual [`ExitStatus`] is for unit testing.
pub trait ExitStatusFromCode {
    /// Build an [`ExitStatus`] from an exit code.
    ///
    /// Takes a [`u8`] on Unix because exit codes there are limited to
    /// `0..=255`. Non-uniform type signature with windows provides infallible api
    /// for a correctness tradeoff.
    #[cfg(unix)]
    #[must_use]
    fn from_code(code: u8) -> ExitStatus;

    /// Build an [`ExitStatus`] from an exit code.
    ///
    /// Takes a [`u32`] on Windows because exit codes there are full 32-bit
    /// `DWORD` values.  Non-uniform type signature with unix provides infallible api
    /// for a correctness tradeoff.
    #[cfg(windows)]
    #[must_use]
    fn from_code(code: u32) -> ExitStatus;
}

impl ExitStatusFromCode for ExitStatus {
    #[cfg(unix)]
    fn from_code(code: u8) -> ExitStatus {
        status_from_code(code.into())
    }

    #[cfg(windows)]
    fn from_code(code: u32) -> ExitStatus {
        status_from_code(code)
    }
}

/// Holds an [`Output`] of a command's execution along with its "name"
///
/// When paired with [`CmdError`] a `Result<NamedOutput, CmdError>` will retain the
/// "name" of the command regardless of success or failure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NamedOutput {
    name: String,
    output: Output,
}

impl NamedOutput {
    /// Check status and convert into an error if nonzero (include output in error)
    ///
    /// Because the [NamedOutput] does not contain information about whether it was originally
    /// streamed or not, use this associated function when the output has not been made
    /// available to the user. This has the effect of showing it in the event of [CmdError].
    ///
    /// If the output was streamed to the user use [NamedOutput::nonzero_streamed]
    ///
    /// # Errors
    ///
    /// Returns an error if the status is not zero
    pub fn nonzero_captured(self) -> Result<NamedOutput, CmdError> {
        nonzero_captured(self.name, self.output)
    }

    /// Check status and convert into an error if nonzero (hide output in error)
    ///
    /// Because the [NamedOutput] does not contain information about whether it was originally
    /// streamed or not, use this associated function when the output has was streamed to the user.
    /// This has the effect of hiding the output in the event of [CmdError] to prevent including
    /// duplicate information twice.
    ///
    /// If the output was not streamed to the user use [NamedOutput::nonzero_captured]
    ///
    /// # Errors
    ///
    /// Returns an error if the status is not zero
    pub fn nonzero_streamed(self) -> Result<NamedOutput, CmdError> {
        nonzero_streamed(self.name, self.output)
    }

    /// Return the ExitStatus of the output
    #[must_use]
    pub fn status(&self) -> &ExitStatus {
        &self.output.status
    }

    /// Return raw stdout
    #[must_use]
    pub fn stdout(&self) -> &Vec<u8> {
        &self.output.stdout
    }

    /// Return raw stderr
    #[must_use]
    pub fn stderr(&self) -> &Vec<u8> {
        &self.output.stderr
    }

    /// Return lossy stdout as a String
    #[must_use]
    pub fn stdout_lossy(&self) -> String {
        String::from_utf8_lossy(&self.output.stdout).to_string()
    }

    /// Return lossy stderr as a String
    #[must_use]
    pub fn stderr_lossy(&self) -> String {
        String::from_utf8_lossy(&self.output.stderr).to_string()
    }

    /// Return name of the command that was run
    #[must_use]
    pub fn name(&self) -> String {
        self.name.clone()
    }

    /// Return reference of the original [Output]
    #[must_use]
    pub fn output(&self) -> &Output {
        &self.output
    }
}

impl AsRef<Output> for NamedOutput {
    fn as_ref(&self) -> &Output {
        &self.output
    }
}

impl<'a> From<&'a NamedOutput> for &'a Output {
    fn from(value: &'a NamedOutput) -> Self {
        &value.output
    }
}

impl From<NamedOutput> for Output {
    fn from(value: NamedOutput) -> Self {
        value.output
    }
}

// https://github.com/jimmycuadra/rust-shellwords/blob/d23b853a850ceec358a4137d5e520b067ddb7abc/src/lib.rs#L23
static QUOTE_ARG_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"([^A-Za-z0-9_\-.,:/@\n])").expect("clippy checked"));

/// Converts a command and its arguments into a user readable string
///
/// Example
///
/// ```rust
/// use std::process::Command;
/// use fun_run;
///
/// let name = fun_run::display(Command::new("bundle").arg("install"));
/// assert_eq!(String::from("bundle install"), name);
/// ```
#[must_use]
pub fn display(command: &mut Command) -> String {
    vec![command.get_program().to_string_lossy().to_string()]
        .into_iter()
        .chain(
            command
                .get_args()
                .map(std::ffi::OsStr::to_string_lossy)
                .map(|arg| {
                    if QUOTE_ARG_RE.is_match(&arg) {
                        format!("{arg:?}")
                    } else {
                        format!("{arg}")
                    }
                }),
        )
        .collect::<Vec<String>>()
        .join(" ")
}

/// Converts a command, arguments, and specified environment variables to user readable string
///
/// Example
///
/// ```rust
/// use std::process::Command;
/// use fun_run;
/// use std::collections::HashMap;
///
/// let mut env = std::env::vars().collect::<HashMap<_,_>>();
/// env.insert("RAILS_ENV".to_string(), "production".to_string());
///
/// let mut command = Command::new("bundle");
/// command.arg("install").envs(&env);
///
/// let name = fun_run::display_with_env_keys(&mut command, &env, ["RAILS_ENV"]);
/// assert_eq!(String::from(r#"RAILS_ENV="production" bundle install"#), name);
/// ```
#[must_use]
pub fn display_with_env_keys<E, K, V, I, O>(cmd: &mut Command, env: E, keys: I) -> String
where
    E: IntoIterator<Item = (K, V)>,
    K: Into<OsString>,
    V: Into<OsString>,
    I: IntoIterator<Item = O>,
    O: Into<OsString>,
{
    let env = env
        .into_iter()
        .map(|(k, v)| (k.into(), v.into()))
        .collect::<std::collections::HashMap<OsString, OsString>>();

    keys.into_iter()
        .map(|key| {
            let key = key.into();
            format!(
                "{}={:?}",
                key.to_string_lossy(),
                env.get(&key).cloned().unwrap_or_else(|| OsString::from(""))
            )
        })
        .chain([display(cmd)])
        .collect::<Vec<String>>()
        .join(" ")
}

/// Who says ([`Command`]) errors can't be fun?
///
/// Fun run errors include all the info a user needs to debug, like
/// the name of the command that failed and any outputs (like error messages
/// in stderr).
///
/// Fun run errors don't overwhelm end users, so by default if stderr is already
/// streamed the output won't be duplicated.
///
/// Enjoy if you want, skip if you don't. Fun run errors are not mandatory.
///
/// Error output formatting is unstable
#[derive(Debug)]
#[allow(clippy::module_name_repetitions)]
pub enum CmdError {
    /// Command encountered an [`std::io::Error`] while trying to run
    ///
    /// The reasons why this can happen are platform specific, mostly it means that the process
    /// could not be launched for some reason. The most common reason is that program name
    /// doesn't exist or cannot be found:
    ///
    /// ```
    /// use fun_run::CommandWithName;
    ///
    /// let result = std::process::Command::new("commandDoesNotExist").named_output();
    /// match result{
    ///     Err(fun_run::CmdError::SystemError(_, _)) => println!("could not boot"),
    ///     _ => unimplemented!()
    /// }
    /// ```
    SystemError(String, std::io::Error),

    /// Command booted, but [`ExitStatus::success`] reported that it failed.
    ///
    /// Will display the stdout/stderr to the user when displayed (since it wasn't previously)
    /// streamed.
    NonZeroExitNotStreamed(NamedOutput),

    /// Command booted, but [`ExitStatus::success`] reported that it failed.
    ///
    /// The command WAS streamed to the end user, so stdout/stderr does not
    /// need to be printed again when rendering the error.
    NonZeroExitAlreadyStreamed(NamedOutput),
}

/// Unix does not return a code for a process that was terminated
/// via a signal (like SIGKILL). People are used to bash convention
/// where a SIGKILL-ing something would give `$?` of `143`. That
/// is because bash makes a simplifying assumption to collapse signal and exit code
/// into a single shared number:
///
/// [From GNU bash](https://web.archive.org/web/20260625050034/https://www.gnu.org/software/bash/manual/bash.html#Exit-Status-1)
///
/// > [...] a fatal signal whose number is N, Bash uses the value 128+N as the exit status.
///
/// People expect this number implicitly, so we replicate that behavior.
fn bashify(status: &ExitStatus) -> i32 {
    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt;

        status
            .code()
            .or_else(|| status.signal().map(|s| 128 + s))
            .unwrap_or(1)
    }
    #[cfg(windows)]
    {
        status.code().unwrap_or(1)
    }
}

/// Returns a printable description of the signal that killed a process
/// (if it was killed by a signal)
fn signal_line(status: &ExitStatus) -> Option<String> {
    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt;

        status.signal().map(|signal| {
            // https://pubs.opengroup.org/onlinepubs/9799919799/utilities/kill.html
            let name = match signal {
                1 => "SIGHUP",
                2 => "SIGINT",
                3 => "SIGQUIT",
                6 => "SIGABRT",
                9 => "SIGKILL",
                14 => "SIGALRM",
                15 => "SIGTERM",
                _ => "",
            };

            if name.is_empty() {
                format!("signal: {signal}")
            } else {
                format!("signal: {signal} ({name})")
            }
        })
    }
    #[cfg(windows)]
    {
        let _ = status;
        None
    }
}

impl Display for CmdError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CmdError::SystemError(name, error) => {
                write!(f, "Could not run command `{name}`. {error}")
            }
            CmdError::NonZeroExitNotStreamed(named_output) => {
                let stdout = display_out_or_empty(&named_output.output.stdout);
                let stderr = display_out_or_empty(&named_output.output.stderr);

                writeln!(f, "Command failed `{name}`", name = named_output.name())?;
                writeln!(
                    f,
                    "exit status: {status}",
                    status = bashify(&named_output.output.status)
                )?;
                if let Some(signal_line) = signal_line(&named_output.output.status) {
                    writeln!(f, "{signal_line}")?;
                }
                writeln!(f, "stdout: {stdout}",)?;
                write!(f, "stderr: {stderr}",)
            }
            CmdError::NonZeroExitAlreadyStreamed(named_output) => {
                writeln!(f, "Command failed `{name}`", name = named_output.name())?;
                writeln!(
                    f,
                    "exit status: {status}",
                    status = bashify(&named_output.output.status)
                )?;
                if let Some(signal_line) = signal_line(&named_output.output.status) {
                    writeln!(f, "{signal_line}")?;
                }
                writeln!(f, "stdout: <see above>")?;
                write!(f, "stderr: <see above>")
            }
        }
    }
}

impl std::error::Error for CmdError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            CmdError::SystemError(_, io_err) => Some(io_err),
            CmdError::NonZeroExitNotStreamed(_) | CmdError::NonZeroExitAlreadyStreamed(_) => None,
        }
    }
}

impl CmdError {
    /// Returns a display representation of the command that failed
    ///
    /// Example:
    ///
    /// ```no_run
    /// use fun_run::CommandWithName;
    /// use std::process::Command;
    ///
    /// let result = Command::new("cat")
    ///     .arg("mouse.txt")
    ///     .named_output();
    ///
    /// match result {
    ///     Ok(_) => unimplemented!(),
    ///     Err(error) => assert_eq!(error.name().to_string(), "cat mouse.txt")
    /// }
    /// ```
    #[must_use]
    pub fn name(&self) -> std::borrow::Cow<'_, str> {
        match self {
            CmdError::SystemError(name, _) => name.into(),
            CmdError::NonZeroExitNotStreamed(out) | CmdError::NonZeroExitAlreadyStreamed(out) => {
                out.name.as_str().into()
            }
        }
    }

    /// Returns the OS [`ExitStatus`] of the command.
    ///
    /// For [`CmdError::SystemError`] the command never ran, so there is no real
    /// OS exit status. In that case a value derived from the underlying
    /// [`std::io::Error`] is returned. It is only guaranteed to be non-zero, so
    /// prefer inspecting the [`std::io::Error`] and its [`std::io::ErrorKind`]
    /// directly rather than relying on the exact code.
    pub fn status(&self) -> ExitStatus {
        match self {
            CmdError::SystemError(_, error) => status_from_error(error),
            CmdError::NonZeroExitNotStreamed(named_output) => named_output.status().to_owned(),
            CmdError::NonZeroExitAlreadyStreamed(named_output) => named_output.status().to_owned(),
        }
    }
}

impl From<CmdError> for NamedOutput {
    /// When the error is a [`CmdError::SystemError`], the resulting
    /// [`ExitStatus`] is synthetic and imprecise. The only stability guarantee
    /// is that it will be non-zero.
    fn from(value: CmdError) -> Self {
        match value {
            CmdError::SystemError(name, error) => NamedOutput {
                name,
                output: Output {
                    status: status_from_error(&error),
                    stdout: Vec::new(),
                    stderr: error.to_string().into_bytes(),
                },
            },
            CmdError::NonZeroExitNotStreamed(named)
            | CmdError::NonZeroExitAlreadyStreamed(named) => named,
        }
    }
}

#[cfg(not(any(unix, windows)))]
compile_error!(
    "fun_run constructs `ExitStatus` values and only supports `unix` and `windows` targets"
);

fn status_from_code(code: u32) -> ExitStatus {
    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt;
        // `from_raw` expects a `wait`-style status (exit code in the upper 8
        // bits) as an i32. `code & 0xff` is always 0..=255, so `as i32` is a
        // safe widening (the unsafe direction would be `i32 as u32`).
        ExitStatus::from_raw(((code & 0xff) as i32) << 8)
    }
    #[cfg(windows)]
    {
        use std::os::windows::process::ExitStatusExt;
        // On Windows `from_raw` takes the exit code directly. Unlike Unix there
        // is no `wait`-style encoding, so no `& 0xff` masking/shifting is needed
        // (Windows exit codes are full u32 values, not limited to 0..=255).
        ExitStatus::from_raw(code)
    }
}

fn status_from_error(error: &std::io::Error) -> ExitStatus {
    use std::io::ErrorKind;

    let code = match error.kind() {
        ErrorKind::NotFound => 127, // ENOENT
        // Found but not executable -> "cannot execute"
        ErrorKind::PermissionDenied      // EACCES
        | ErrorKind::IsADirectory        // EISDIR
        | ErrorKind::NotADirectory       // ENOTDIR
        | ErrorKind::ArgumentListTooLong // E2BIG
        | ErrorKind::OutOfMemory         // ENOMEM
        | ErrorKind::ExecutableFileBusy  // ETXTBSY
        => 126,
        _ => 1,
    };
    status_from_code(code)
}

fn display_out_or_empty(contents: &[u8]) -> String {
    let contents = String::from_utf8_lossy(contents);
    if contents.trim().is_empty() {
        "<empty>".to_string()
    } else {
        contents.to_string()
    }
}

/// Converts a [`std::io::Error`] into a [`CmdError`] which includes the formatted command name
#[must_use]
pub fn on_system_error(name: String, error: std::io::Error) -> CmdError {
    CmdError::SystemError(name, error)
}

/// Converts an [`Output`] into an error when status is non-zero
///
/// When calling a [`Command`] and streaming the output to stdout/stderr
/// it can be jarring to have the contents emitted again in the error. When this
/// error is displayed those outputs will not be repeated.
///
/// Use when the [`Output`] comes from a source that was already streamed.
///
/// To to include the results of stdout/stderr in the display of the error
/// use [`nonzero_captured`] instead.
///
/// # Errors
///
/// Returns Err when the [`Output`] status is non-zero
pub fn nonzero_streamed(name: String, output: impl Into<Output>) -> Result<NamedOutput, CmdError> {
    let output = output.into();
    if output.status.success() {
        Ok(NamedOutput { name, output })
    } else {
        Err(CmdError::NonZeroExitAlreadyStreamed(NamedOutput {
            name,
            output,
        }))
    }
}

/// Converts an [`Output`] into an error when status is non-zero
///
/// Use when the [`Output`] comes from a source that was not streamed
/// to stdout/stderr so it will be included in the error display by default.
///
/// To avoid double printing stdout/stderr when streaming use [`nonzero_streamed`]
///
/// # Errors
///
/// Returns Err when the [`Output`] status is non-zero
pub fn nonzero_captured(name: String, output: impl Into<Output>) -> Result<NamedOutput, CmdError> {
    let output = output.into();
    if output.status.success() {
        Ok(NamedOutput { name, output })
    } else {
        Err(CmdError::NonZeroExitNotStreamed(NamedOutput {
            name,
            output,
        }))
    }
}

/// Adds diagnostic information to a [`CmdError`] using `which_problem` if it is a [`CmdError::SystemError`]
///
/// A `CmdError::SystemError` means that the command could not be run (different than, it ran but
/// emitted an error). When that happens it usually means that either there's a typo in the command
/// program name, or there's an error with the system. For example if the PATH is empty, then the
/// OS will be be unable to find and run the executable.
///
/// To make this type of system debugging easier the `which_problem` crate simulates the logic of
/// `which <program name>` but emits detailed diagnostic information about the system including
/// things like missing or broken symlinks, invalid permissions, directories on the PATH that are
/// empty etc.
///
/// It's best used as a diagnostic for developers for why a CmdError::SystemError might have occurred.
/// For example, if the programmer executed the command with an empty PATH, this debugging tool
/// would help them find and fix the (otherwise) tedious to debug problem.
///
/// Using this feature may leak sensitive information about the system if the input is untrusted so
/// consider who has access to inputs, and who will view the outputs.
///
/// See the `which_problem` crate for more details.
///
/// This feature is experimental and may change in the future.
///
/// ```no_run
/// use fun_run::{self, CommandWithName};
/// use std::process::Command;
///
/// let mut cmd = Command::new("bundle");
/// cmd.arg("install");
/// cmd.named_output().map_err(|error| {
///     fun_run::map_which_problem(error, cmd.mut_cmd(), std::env::var_os("PATH"))
/// }).unwrap();
/// ```
#[cfg(feature = "which_problem")]
pub fn map_which_problem(
    error: CmdError,
    cmd: &mut Command,
    path_env: Option<OsString>,
) -> CmdError {
    match error {
        CmdError::SystemError(name, error) => {
            CmdError::SystemError(name, annotate_which_problem(error, cmd, path_env))
        }
        CmdError::NonZeroExitNotStreamed(_) | CmdError::NonZeroExitAlreadyStreamed(_) => error,
    }
}

/// Adds diagnostic information to an `std::io::Error` using `which_problem`
///
/// This feature is experimental
#[must_use]
#[cfg(feature = "which_problem")]
fn annotate_which_problem(
    error: std::io::Error,
    cmd: &mut Command,
    path_env: Option<OsString>,
) -> std::io::Error {
    let program = cmd.get_program().to_os_string();
    let current_working_dir = cmd.get_current_dir().map(std::path::Path::to_path_buf);
    let problem = Which {
        cwd: current_working_dir,
        program,
        path_env,
        ..Which::default()
    }
    .diagnose();

    let annotation = match problem {
        Ok(details) => format!("\nSystem diagnostic information:\n\n{details}"),
        Err(error) => {
            format!("\nInternal error while gathering diagnostic information:\n\n{error}")
        }
    };

    annotate_io_error(error, annotation)
}

/// Returns an IO error that displays the given annotation starting on
/// the next line.
///
/// Internal API used by `annotate_which_problem`
#[must_use]
#[cfg(feature = "which_problem")]
fn annotate_io_error(source: std::io::Error, annotation: String) -> std::io::Error {
    IoErrorAnnotation::new(source, annotation).into_io_error()
}

#[derive(Debug)]
#[cfg(feature = "which_problem")]
pub(crate) struct IoErrorAnnotation {
    source: std::io::Error,
    annotation: String,
}

#[cfg(feature = "which_problem")]
impl IoErrorAnnotation {
    pub(crate) fn new(source: std::io::Error, annotation: String) -> Self {
        Self { source, annotation }
    }

    pub(crate) fn into_io_error(self) -> std::io::Error {
        std::io::Error::new(self.source.kind(), self)
    }
}

#[cfg(feature = "which_problem")]
impl std::fmt::Display for IoErrorAnnotation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "{}", self.source)?;
        f.write_str(&self.annotation)?;
        Ok(())
    }
}

#[cfg(feature = "which_problem")]
impl std::error::Error for IoErrorAnnotation {
    fn cause(&self) -> Option<&dyn std::error::Error> {
        self.source()
    }

    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.source)
    }
}

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

    #[test]
    fn test_status_from_code() {
        for code in 0..=255 {
            let status = ExitStatus::from_code(code);
            assert_eq!(Some(code as i32), status.code());
        }
    }

    #[test]
    fn maps_error_kinds_to_shell_codes() {
        use std::io::{Error, ErrorKind};

        assert_eq!(
            Some(127),
            status_from_error(&Error::from(ErrorKind::NotFound)).code()
        );
        assert_eq!(
            Some(126),
            status_from_error(&Error::from(ErrorKind::PermissionDenied)).code()
        );
        assert_eq!(
            Some(1),
            status_from_error(&Error::from(ErrorKind::Other)).code()
        );
    }

    #[test]
    #[cfg(unix)]
    fn maps_signal_to_exit() {
        use std::os::unix::process::ExitStatusExt;

        let sigterm = 15;
        let status = ExitStatus::from_raw(sigterm);
        assert_eq!(None, status.code());
        assert_eq!(Some(15), status.signal());

        let code = bashify(&status);
        assert_eq!(143, code);
    }

    #[test]
    #[cfg(unix)]
    fn maps_signal_to_human_readable_output() {
        use std::os::unix::process::ExitStatusExt;

        let sigterm = 15;
        let status = ExitStatus::from_raw(sigterm);
        assert_eq!(None, status.code());
        assert_eq!(Some(15), status.signal());

        assert_eq!(
            String::from("signal: 15 (SIGTERM)"),
            signal_line(&status).unwrap()
        );

        let signal = 126;
        let status = ExitStatus::from_raw(signal);
        assert_eq!(None, status.code());
        assert_eq!(Some(126), status.signal());

        assert_eq!(String::from("signal: 126"), signal_line(&status).unwrap());
    }
}