Debian Codegraph @

tests/by-util/test_env.rs

raw
1 // This file is part of the uutils coreutils package.
2 //
3 // For the full copyright and license information, please view the LICENSE
4 // file that was distributed with this source code.
5
6 // spell-checker:ignore (words) bamf chdir rlimit prlimit COMSPEC cout cerr FFFD winsize xpixel ypixel Secho sighandler putenv
7 #![allow(clippy::missing_errors_doc)]
8
9 #[cfg(unix)]
10 use nix::libc;
11 #[cfg(unix)]
12 use nix::sys::signal::Signal;
13 #[cfg(feature = "echo")]
14 use regex::Regex;
15 use std::env;
16 use std::path::Path;
17 #[cfg(unix)]
18 use std::process::Command;
19 use tempfile::tempdir;
20 use uutests::new_ucmd;
21 #[cfg(unix)]
22 use uutests::util::PATH;
23 #[cfg(unix)]
24 use uutests::util::TerminalSimulation;
25 use uutests::util::TestScenario;
26 #[cfg(unix)]
27 use uutests::util::UChild;
28 use uutests::util_name;
29
30 #[cfg(unix)]
31 struct Target {
32 child: UChild,
33 }
34 #[cfg(unix)]
35 impl Target {
36 fn new(signals: &[&str]) -> Self {
37 let mut cmd = new_ucmd!();
38 if signals.is_empty() {
39 cmd.arg("--ignore-signal");
40 } else {
41 cmd.arg(format!("--ignore-signal={}", signals.join(",")));
42 }
43 let mut child = cmd.args(&["sleep", "1000"]).run_no_wait();
44 child.delay(500);
45 Self { child }
46 }
47 fn send_signal(&mut self, signal: Signal) {
48 let _ = Command::new("kill")
49 .args(&[
50 format!("-{}", signal as i32),
51 format!("{}", self.child.id()),
52 ])
53 .spawn()
54 .expect("failed to send signal")
55 .wait();
56 // macOS CI needs a longer delay for process teardown after signal delivery
57 #[cfg(target_vendor = "apple")]
58 self.child.delay(500);
59 #[cfg(not(target_vendor = "apple"))]
60 self.child.delay(100);
61 }
62 fn is_alive(&mut self) -> bool {
63 self.child.is_alive()
64 }
65 }
66 #[cfg(unix)]
67 impl Drop for Target {
68 fn drop(&mut self) {
69 self.child.kill();
70 }
71 }
72
73 #[test]
74 fn test_invalid_arg() {
75 new_ucmd!().arg("--definitely-invalid").fails_with_code(125);
76 }
77
78 #[test]
79 #[cfg(not(windows))]
80 fn test_flags_after_command() {
81 new_ucmd!()
82 // This would cause an error if -u=v were processed because it's malformed
83 .args(&["echo", "-u=v"])
84 .succeeds()
85 .no_stderr()
86 .stdout_is("-u=v\n");
87
88 new_ucmd!()
89 // Ensure the string isn't split
90 // cSpell:disable
91 .args(&["printf", "%s-%s", "-Sfoo bar"])
92 .succeeds()
93 .no_stderr()
94 .stdout_is("-Sfoo bar-");
95 // cSpell:enable
96
97 new_ucmd!()
98 // Ensure -- is recognized
99 .args(&["-i", "--", "-u=v"])
100 .succeeds()
101 .no_stderr()
102 .stdout_is("-u=v\n");
103
104 new_ucmd!()
105 // Recognize echo as the command after a flag that takes a value
106 .args(&["-C", "..", "echo", "-u=v"])
107 .succeeds()
108 .no_stderr()
109 .stdout_is("-u=v\n");
110
111 new_ucmd!()
112 // Recognize echo as the command after a flag that takes an inline value
113 .args(&["-C..", "echo", "-u=v"])
114 .succeeds()
115 .no_stderr()
116 .stdout_is("-u=v\n");
117
118 new_ucmd!()
119 // Recognize echo as the command after a flag that takes a value after another flag
120 .args(&["-iC", "..", "echo", "-u=v"])
121 .succeeds()
122 .no_stderr()
123 .stdout_is("-u=v\n");
124
125 new_ucmd!()
126 // Similar to the last two combined
127 .args(&["-iC..", "echo", "-u=v"])
128 .succeeds()
129 .no_stderr()
130 .stdout_is("-u=v\n");
131 }
132
133 #[test]
134 fn test_env_help() {
135 new_ucmd!()
136 .arg("--help")
137 .succeeds()
138 .no_stderr()
139 .stdout_contains("Options:");
140 }
141
142 #[test]
143 fn test_env_version() {
144 new_ucmd!()
145 .arg("--version")
146 .succeeds()
147 .no_stderr()
148 .stdout_is(format!("env {}\n", uucore::crate_version!()));
149 }
150
151 #[test]
152 #[cfg(unix)]
153 fn test_env_permissions() {
154 // Try to execute `empty` in test fixture, that does not have exec permission.
155 new_ucmd!()
156 .arg("./empty")
157 .fails_with_code(126)
158 .stderr_is("env: './empty': Permission denied\n");
159 }
160
161 #[test]
162 fn test_echo() {
163 #[cfg(windows)]
164 let args = ["cmd", "/d/c", "echo"];
165 #[cfg(not(windows))]
166 let args = ["echo"];
167
168 let result = new_ucmd!().args(&args).arg("FOO-bar").succeeds();
169
170 assert_eq!(result.stdout_str().trim(), "FOO-bar");
171 }
172
173 #[cfg(windows)]
174 #[test]
175 fn test_if_windows_batch_files_can_be_executed() {
176 let result = new_ucmd!().arg("./runBat.bat").succeeds();
177
178 assert!(result.stdout_str().contains("Hello Windows World!"));
179 }
180
181 #[cfg(feature = "echo")]
182 #[test]
183 fn test_debug_1() {
184 let ts = TestScenario::new(util_name!());
185 let result = ts
186 .ucmd()
187 .arg("-v")
188 .arg(&ts.bin_path)
189 .args(&["echo", "hello"])
190 .succeeds();
191 result.stderr_matches(
192 &Regex::new(concat!(
193 r"executing: [^\n]+(\/|\\)coreutils(\.exe)?\n",
194 r" arg\[0\]= '[^\n]+(\/|\\)coreutils(\.exe)?'\n",
195 r" arg\[1\]= 'echo'\n",
196 r" arg\[2\]= 'hello'"
197 ))
198 .unwrap(),
199 );
200 }
201
202 #[cfg(feature = "echo")]
203 #[test]
204 fn test_debug_2() {
205 let ts = TestScenario::new(util_name!());
206 let result = ts
207 .ucmd()
208 .arg("-vv")
209 .arg(&ts.bin_path)
210 .args(&["echo", "hello2"])
211 .succeeds();
212 result.stderr_matches(
213 &Regex::new(concat!(
214 r"input args:\n",
215 r"arg\[0\]: 'env'\n",
216 r"arg\[1\]: '-vv'\n",
217 r"arg\[2\]: '[^\n]+(\/|\\)coreutils(.exe)?'\n",
218 r"arg\[3\]: 'echo'\n",
219 r"arg\[4\]: 'hello2'\n",
220 r"executing: [^\n]+(\/|\\)coreutils(.exe)?\n",
221 r" arg\[0\]= '[^\n]+(\/|\\)coreutils(.exe)?'\n",
222 r" arg\[1\]= 'echo'\n",
223 r" arg\[2\]= 'hello2'"
224 ))
225 .unwrap(),
226 );
227 }
228
229 #[cfg(feature = "echo")]
230 #[test]
231 fn test_debug1_part_of_string_arg() {
232 let ts = TestScenario::new(util_name!());
233
234 let result = ts
235 .ucmd()
236 .arg("-vS FOO=BAR")
237 .arg(&ts.bin_path)
238 .args(&["echo", "hello1"])
239 .succeeds();
240 result.stderr_matches(
241 &Regex::new(concat!(
242 r"executing: [^\n]+(\/|\\)coreutils(\.exe)?\n",
243 r" arg\[0\]= '[^\n]+(\/|\\)coreutils(\.exe)?'\n",
244 r" arg\[1\]= 'echo'\n",
245 r" arg\[2\]= 'hello1'"
246 ))
247 .unwrap(),
248 );
249 }
250
251 #[cfg(feature = "echo")]
252 #[test]
253 fn test_debug2_part_of_string_arg() {
254 let ts = TestScenario::new(util_name!());
255 let result = ts
256 .ucmd()
257 .arg("-vvS FOO=BAR")
258 .arg(&ts.bin_path)
259 .args(&["echo", "hello2"])
260 .succeeds();
261 result.stderr_matches(
262 &Regex::new(concat!(
263 r"input args:\n",
264 r"arg\[0\]: 'env'\n",
265 r"arg\[1\]: '-vvS FOO=BAR'\n",
266 r"arg\[2\]: '[^\n]+(\/|\\)coreutils(.exe)?'\n",
267 r"arg\[3\]: 'echo'\n",
268 r"arg\[4\]: 'hello2'\n",
269 r"executing: [^\n]+(\/|\\)coreutils(.exe)?\n",
270 r" arg\[0\]= '[^\n]+(\/|\\)coreutils(.exe)?'\n",
271 r" arg\[1\]= 'echo'\n",
272 r" arg\[2\]= 'hello2'"
273 ))
274 .unwrap(),
275 );
276 }
277
278 #[test]
279 fn test_file_option() {
280 let out = new_ucmd!()
281 .arg("-f")
282 .arg("vars.conf.txt")
283 .succeeds()
284 .stdout_move_str();
285
286 assert_eq!(
287 out.lines()
288 .filter(|&line| line == "FOO=bar" || line == "BAR=bamf this")
289 .count(),
290 2
291 );
292 }
293
294 #[test]
295 fn test_combined_file_set() {
296 let out = new_ucmd!()
297 .arg("-f")
298 .arg("vars.conf.txt")
299 .arg("FOO=bar.alt")
300 .succeeds()
301 .stdout_move_str();
302
303 assert_eq!(out.lines().filter(|&line| line == "FOO=bar.alt").count(), 1);
304 }
305
306 #[test]
307 fn test_combined_file_set_unset() {
308 let out = new_ucmd!()
309 .arg("-u")
310 .arg("BAR")
311 .arg("-f")
312 .arg("vars.conf.txt")
313 .arg("FOO=bar.alt")
314 .succeeds()
315 .stdout_move_str();
316
317 assert_eq!(
318 out.lines()
319 .filter(|&line| line == "FOO=bar.alt" || line.starts_with("BAR="))
320 .count(),
321 1
322 );
323 }
324
325 #[test]
326 fn test_unset_invalid_variables() {
327 use uucore::display::Quotable;
328
329 // Cannot test input with \0 in it, since output will also contain \0. rlimit::prlimit fails
330 // with this error: Error { kind: InvalidInput, message: "nul byte found in provided data" }
331 for var in ["", "a=b"] {
332 new_ucmd!().arg("-u").arg(var).fails().stderr_only(format!(
333 "env: cannot unset {}: Invalid argument\n",
334 var.quote()
335 ));
336 }
337 }
338
339 #[test]
340 fn test_single_name_value_pair() {
341 new_ucmd!()
342 .arg("FOO=bar")
343 .succeeds()
344 .stdout_str()
345 .lines()
346 .any(|line| line == "FOO=bar");
347 }
348
349 #[test]
350 fn test_multiple_name_value_pairs() {
351 let out = new_ucmd!().arg("FOO=bar").arg("ABC=xyz").succeeds();
352
353 assert_eq!(
354 out.stdout_str()
355 .lines()
356 .filter(|&line| line == "FOO=bar" || line == "ABC=xyz")
357 .count(),
358 2
359 );
360 }
361
362 #[test]
363 fn test_ignore_environment() {
364 let scene = TestScenario::new(util_name!());
365
366 scene.ucmd().arg("-i").succeeds().no_stdout();
367 scene.ucmd().arg("-").succeeds().no_stdout();
368 }
369
370 #[test]
371 fn test_empty_name() {
372 new_ucmd!()
373 .arg("-i")
374 .arg("=xyz")
375 .succeeds()
376 .stderr_only("env: warning: no name specified for value 'xyz'\n");
377 }
378
379 // An empty name is dropped with a warning (GNU injects it via putenv, we
380 // can't with set_var); the other assignments must still go through.
381 #[test]
382 fn test_empty_name_does_not_affect_other_assignments() {
383 let result = new_ucmd!()
384 .args(&["-i", "MOTOR=idle", "=zap", "GEARBOX=locked"])
385 .succeeds();
386 result.stderr_is("env: warning: no name specified for value 'zap'\n");
387
388 // Windows sorts the environment block, so don't depend on the order.
389 let mut vars: Vec<_> = result.stdout_str().lines().collect();
390 vars.sort_unstable();
391 assert_eq!(vars, ["GEARBOX=locked", "MOTOR=idle"]);
392 }
393
394 // "=" alone is name and value both empty; still just a warning, exit 0.
395 #[test]
396 fn test_empty_name_and_empty_value() {
397 new_ucmd!()
398 .args(&["-i", "="])
399 .succeeds()
400 .no_stdout()
401 .stderr_is("env: warning: no name specified for value ''\n");
402 }
403
404 #[test]
405 fn test_null_delimiter() {
406 let out = new_ucmd!()
407 .arg("-i")
408 .arg("--null")
409 .arg("FOO=bar")
410 .arg("ABC=xyz")
411 .succeeds()
412 .stdout_move_str();
413
414 let mut vars: Vec<_> = out.split('\0').collect();
415 assert_eq!(vars.len(), 3);
416 vars.sort_unstable();
417 assert_eq!(vars[0], "");
418 assert_eq!(vars[1], "ABC=xyz");
419 assert_eq!(vars[2], "FOO=bar");
420 }
421
422 #[test]
423 fn test_unset_variable() {
424 let out = TestScenario::new(util_name!())
425 .ucmd()
426 .env("HOME", "FOO")
427 .arg("-u")
428 .arg("HOME")
429 .succeeds()
430 .stdout_move_str();
431
432 assert!(!out.lines().any(|line| line.starts_with("HOME=")));
433 }
434
435 #[test]
436 fn test_fail_null_with_program() {
437 new_ucmd!()
438 .arg("--null")
439 .arg("cd")
440 .fails()
441 .stderr_contains("cannot specify --null (-0) with command");
442 }
443
444 #[cfg(not(windows))]
445 #[test]
446 fn test_change_directory() {
447 let scene = TestScenario::new(util_name!());
448 let temporary_directory = tempdir().unwrap();
449 let temporary_path = std::fs::canonicalize(temporary_directory.path()).unwrap();
450 assert_ne!(env::current_dir().unwrap(), temporary_path);
451
452 // command to print out current working directory
453 let pwd = "pwd";
454
455 let out = scene
456 .ucmd()
457 .arg("--chdir")
458 .arg(&temporary_path)
459 .arg(pwd)
460 .succeeds()
461 .stdout_move_str();
462 assert_eq!(out.trim(), temporary_path.as_os_str());
463 }
464
465 #[cfg(windows)]
466 #[test]
467 fn test_change_directory() {
468 let scene = TestScenario::new(util_name!());
469 let temporary_directory = tempdir().unwrap();
470
471 let temporary_path = temporary_directory.path();
472 let temporary_path = temporary_path
473 .strip_prefix(r"\\?\")
474 .unwrap_or(temporary_path);
475
476 let env_cd = env::current_dir().unwrap();
477 let env_cd = env_cd.strip_prefix(r"\\?\").unwrap_or(&env_cd);
478
479 assert_ne!(env_cd, temporary_path);
480
481 // COMSPEC is a variable that contains the full path to cmd.exe
482 let cmd_path = env::var("COMSPEC").unwrap();
483
484 // command to print out current working directory
485 let pwd = [&*cmd_path, "/C", "cd"];
486
487 let out = scene
488 .ucmd()
489 .arg("--chdir")
490 .arg(temporary_path)
491 .args(&pwd)
492 .succeeds()
493 .stdout_move_str();
494 assert_eq!(out.trim(), temporary_path.as_os_str());
495 }
496
497 #[test]
498 fn test_fail_change_directory() {
499 let scene = TestScenario::new(util_name!());
500 let some_non_existing_path = "some_nonexistent_path";
501 assert!(!Path::new(some_non_existing_path).is_dir());
502
503 let out = scene
504 .ucmd()
505 .arg("--chdir")
506 .arg(some_non_existing_path)
507 .arg("pwd")
508 .fails()
509 .stderr_move_str();
510 assert!(out.contains("env: cannot change directory to "));
511 }
512
513 #[test]
514 fn test_chdir_happens_after_relative_file_loading() {
515 let scene = TestScenario::new(util_name!());
516 scene.fixtures.mkdir("target");
517 scene
518 .fixtures
519 .write("config.env", "CONFIG_SOURCE=from-root\n");
520 scene
521 .fixtures
522 .write("target/config.env", "CONFIG_SOURCE=from-target\n");
523
524 let out = scene
525 .ucmd()
526 .args(&["--chdir", "target", "--file", "config.env", "-i"])
527 .arg(uutests::util::get_tests_binary())
528 .arg(util_name!())
529 .succeeds()
530 .stdout_move_str();
531
532 assert!(
533 out.contains("CONFIG_SOURCE=from-root\n"),
534 "expected config file from invocation directory, got: {out:?}"
535 );
536 assert!(
537 !out.contains("CONFIG_SOURCE=from-target\n"),
538 "unexpectedly loaded config from --chdir target directory: {out:?}"
539 );
540 }
541
542 #[cfg(not(windows))] // windows has no executable "echo", its only supported as part of a batch-file
543 #[test]
544 fn test_split_string_into_args_one_argument_no_quotes() {
545 let scene = TestScenario::new(util_name!());
546
547 let out = scene
548 .ucmd()
549 .arg("-S echo hello world")
550 .succeeds()
551 .stdout_move_str();
552 assert_eq!(out, "hello world\n");
553 }
554
555 #[cfg(not(windows))] // windows has no executable "echo", its only supported as part of a batch-file
556 #[test]
557 fn test_split_string_into_args_one_argument() {
558 let scene = TestScenario::new(util_name!());
559
560 let out = scene
561 .ucmd()
562 .arg("-S echo \"hello world\"")
563 .succeeds()
564 .stdout_move_str();
565 assert_eq!(out, "hello world\n");
566 }
567
568 #[cfg(not(windows))] // windows has no executable "echo", its only supported as part of a batch-file
569 #[test]
570 fn test_split_string_into_args_s_escaping_challenge() {
571 let scene = TestScenario::new(util_name!());
572
573 let out = scene
574 .ucmd()
575 .args(&[r#"-S echo "hello \"great\" world""#])
576 .succeeds()
577 .stdout_move_str();
578 assert_eq!(out, "hello \"great\" world\n");
579 }
580
581 #[test]
582 fn test_split_string_into_args_s_escaped_c_not_allowed() {
583 let scene = TestScenario::new(util_name!());
584
585 let out = scene.ucmd().args(&[r#"-S"\c""#]).fails().stderr_move_str();
586 assert_eq!(
587 out,
588 "env: '\\c' must not appear in double-quoted -S string at position 2\n"
589 );
590 }
591
592 #[cfg(not(windows))] // no printf available
593 #[test]
594 fn test_split_string_into_args_s_whitespace_handling() {
595 let scene = TestScenario::new(util_name!());
596
597 let out = scene
598 .ucmd()
599 .args(&["-Sprintf x%sx\\n A \t B \x0B\x0C\r\n"])
600 .succeeds()
601 .stdout_move_str();
602 assert_eq!(out, "xAx\nxBx\n");
603 }
604
605 #[cfg(not(windows))] // no printf available
606 #[test]
607 fn test_split_string_into_args_long_option_whitespace_handling() {
608 let scene = TestScenario::new(util_name!());
609
610 let out = scene
611 .ucmd()
612 .args(&["--split-string printf x%sx\\n A \t B \x0B\x0C\r\n"])
613 .succeeds()
614 .stdout_move_str();
615 assert_eq!(out, "xAx\nxBx\n");
616 }
617
618 #[cfg(not(windows))] // no printf available
619 #[test]
620 fn test_split_string_option_forms_match_gnu_required_argument_handling() {
621 let scene = TestScenario::new(util_name!());
622
623 scene
624 .ucmd()
625 .args(&["-S", "printf x:%s\\n one two"])
626 .succeeds()
627 .stdout_is("x:one\nx:two\n");
628
629 scene
630 .ucmd()
631 .args(&["--split-string", "printf x:%s\\n one two"])
632 .succeeds()
633 .stdout_is("x:one\nx:two\n");
634
635 scene
636 .ucmd()
637 .arg("--split-string=printf x:%s\\n one two")
638 .succeeds()
639 .stdout_is("x:one\nx:two\n");
640 }
641
642 #[cfg(not(windows))] // no printf available
643 #[test]
644 fn test_split_string_into_args_debug_output_whitespace_handling() {
645 let scene = TestScenario::new(util_name!());
646
647 let out = scene
648 .ucmd()
649 .args(&["-vvS printf x%sx\\n A \t B \x0B\x0C\r\n"])
650 .succeeds();
651 assert_eq!(out.stdout_str(), "xAx\nxBx\n");
652 assert_eq!(
653 out.stderr_str(),
654 "input args:\narg[0]: 'env'\narg[1]: $\
655 '-vvS printf x%sx\\\\n A \\t B \\x0B\\x0C\\r\\n'\nexecuting: printf\
656 \n arg[0]= 'printf'\n arg[1]= $'x%sx\\n'\n arg[2]= 'A'\n arg[3]= 'B'\n"
657 );
658 }
659
660 // FixMe: This test fails on MACOS:
661 // thread 'test_env::test_env_split_quoted_with_backslash_space' panicked at 'assertion failed: `(left == right)`
662 // left: `"X=Y Z=W\n__CF_USER_TEXT_ENCODING=0x1F5:0x0:0x0\n"`,
663 // right: `"X=Y Z=W\n"`', tests/by-util/test_env.rs:369:5
664 #[cfg(not(target_vendor = "apple"))]
665 #[test]
666 fn test_env_split_quoted_with_backslash_space() {
667 let scene = TestScenario::new(util_name!());
668
669 let env_bin = String::from(uutests::util::get_tests_binary()) + " " + util_name!();
670 let input = [
671 String::from("-i"),
672 String::from(r#"-SX="Y\_Z=W" "#) + env_bin.escape_default().to_string().as_str() + "",
673 ];
674
675 let mut output = "X=Y Z=W\n".to_string();
676
677 // Workaround for the test to pass when coverage is being run.
678 // If enabled, the binary called by env_bin will most probably be
679 // instrumented for coverage, and thus will set the
680 // __LLVM_PROFILE_RT_INIT_ONCE
681 if env::var("__LLVM_PROFILE_RT_INIT_ONCE").is_ok() {
682 output.push_str("__LLVM_PROFILE_RT_INIT_ONCE=__LLVM_PROFILE_RT_INIT_ONCE\n");
683 }
684
685 let out = scene.ucmd().args(&input).succeeds();
686 // Windows hands PROCESSOR_ARCHITECTURE to every process it starts, so it
687 // shows up even in the empty environment `-i` asks for (seen on arm64).
688 let stdout: Vec<&str> = out
689 .stdout_str()
690 .lines()
691 .filter(|line| !line.starts_with("PROCESSOR_ARCHITECTURE="))
692 .collect();
693 assert_eq!(stdout, output.lines().collect::<Vec<_>>());
694 }
695
696 #[cfg(not(windows))] // no printf available
697 #[test]
698 fn test_split_string_single_quotes_keep_unknown_backslash_sequences_literal() {
699 let scene = TestScenario::new(util_name!());
700 scene
701 .ucmd()
702 .arg("-Sprintf %s '\\x'")
703 .succeeds()
704 .stdout_is("\\x");
705 scene
706 .ucmd()
707 .arg("-Sprintf %s '\\a'")
708 .succeeds()
709 .stdout_is("\\a");
710 scene
711 .ucmd()
712 .arg("-Sprintf %s '\\`'")
713 .succeeds()
714 .stdout_is("\\`");
715 scene
716 .ucmd()
717 .arg("-Sprintf %s '\\q'")
718 .succeeds()
719 .stdout_is("\\q");
720 scene
721 .ucmd()
722 .arg("-Sprintf %s '\\|'")
723 .succeeds()
724 .stdout_is("\\|");
725 scene
726 .ucmd()
727 .arg("-Sprintf %s '\\9'")
728 .succeeds()
729 .stdout_is("\\9");
730 }
731
732 #[cfg(not(windows))] // no printf available
733 #[test]
734 fn test_split_string_backslash_a_behavior_matches_gnu_quoting_context() {
735 let scene = TestScenario::new(util_name!());
736
737 scene
738 .ucmd()
739 .arg("-Sprintf %s '\\a'")
740 .succeeds()
741 .stdout_is("\\a");
742
743 scene
744 .ucmd()
745 .arg("-Sprintf %s \"\\a\"")
746 .fails_with_code(125)
747 .no_stdout()
748 .stderr_contains("invalid sequence '\\a' in -S");
749
750 scene
751 .ucmd()
752 .arg("-Sprintf %s \\a")
753 .fails_with_code(125)
754 .no_stdout()
755 .stderr_contains("invalid sequence '\\a' in -S");
756 }
757 #[test]
758 #[allow(clippy::cognitive_complexity)] // Ignore clippy lint of too long function sign
759 fn test_env_parsing_errors() {
760 let ts = TestScenario::new(util_name!());
761
762 ts.ucmd()
763 .arg("-S\\|echo hallo") // no quotes, invalid escape sequence |
764 .fails_with_code(125)
765 .no_stdout()
766 .stderr_is("env: invalid sequence '\\|' in -S at position 1\n");
767
768 ts.ucmd()
769 .arg("-S\\a") // no quotes, invalid escape sequence a
770 .fails_with_code(125)
771 .no_stdout()
772 .stderr_is("env: invalid sequence '\\a' in -S at position 1\n");
773
774 ts.ucmd()
775 .arg("-S\"\\a\"") // double quotes, invalid escape sequence a
776 .fails_with_code(125)
777 .no_stdout()
778 .stderr_is("env: invalid sequence '\\a' in -S at position 2\n");
779
780 ts.ucmd()
781 .arg(r#"-S"\a""#) // same as before, just using r#""#
782 .fails_with_code(125)
783 .no_stdout()
784 .stderr_is("env: invalid sequence '\\a' in -S at position 2\n");
785
786 ts.ucmd()
787 .arg(r"-S\|\&\;") // no quotes, invalid escape sequence |
788 .fails_with_code(125)
789 .no_stdout()
790 .stderr_is("env: invalid sequence '\\|' in -S at position 1\n");
791
792 ts.ucmd()
793 .arg(r"-S\<\&\;") // no quotes, invalid escape sequence <
794 .fails_with_code(125)
795 .no_stdout()
796 .stderr_is("env: invalid sequence '\\<' in -S at position 1\n");
797
798 ts.ucmd()
799 .arg(r"-S\>\&\;") // no quotes, invalid escape sequence >
800 .fails_with_code(125)
801 .no_stdout()
802 .stderr_is("env: invalid sequence '\\>' in -S at position 1\n");
803
804 ts.ucmd()
805 .arg(r"-S\`\&\;") // no quotes, invalid escape sequence `
806 .fails_with_code(125)
807 .no_stdout()
808 .stderr_is("env: invalid sequence '\\`' in -S at position 1\n");
809
810 ts.ucmd()
811 .arg(r#"-S"\`\&\;""#) // double quotes, invalid escape sequence `
812 .fails_with_code(125)
813 .no_stdout()
814 .stderr_is("env: invalid sequence '\\`' in -S at position 2\n");
815
816 ts.ucmd()
817 .arg(r"-S\`") // ` escaped without quotes
818 .fails_with_code(125)
819 .no_stdout()
820 .stderr_is("env: invalid sequence '\\`' in -S at position 1\n");
821
822 ts.ucmd()
823 .arg(r#"-S"\`""#) // ` escaped in double quotes
824 .fails_with_code(125)
825 .no_stdout()
826 .stderr_is("env: invalid sequence '\\`' in -S at position 2\n");
827
828 ts.ucmd()
829 .args(&[r"-S\🦉"]) // ` escaped in single quotes
830 .fails_with_code(125)
831 .no_stdout()
832 .stderr_is("env: invalid sequence '\\\u{FFFD}' in -S at position 1\n"); // gnu doesn't show the owl. Instead a invalid unicode ?
833 }
834
835 #[test]
836 fn test_env_with_empty_executable_single_quotes() {
837 let ts = TestScenario::new(util_name!());
838
839 ts.ucmd()
840 .args(&["-S''"]) // empty single quotes, considered as program name
841 .fails_with_code(127)
842 .no_stdout()
843 .stderr_is("env: '': No such file or directory\n"); // gnu version again adds escaping here
844 }
845
846 #[test]
847 fn test_env_with_empty_executable_double_quotes() {
848 let ts = TestScenario::new(util_name!());
849
850 ts.ucmd()
851 .args(&["-S\"\""]) // empty double quotes, considered as program name
852 .fails_with_code(127)
853 .no_stdout()
854 .stderr_is("env: '': No such file or directory\n");
855 }
856
857 // Do not assume that coreutils uses argv0
858 #[test]
859 #[cfg(unix)]
860 fn test_env_overwrite_arg0() {
861 let ts = TestScenario::new(util_name!());
862
863 ts.ucmd()
864 .args(&["--argv0", "hijacked", "sh", "-c", "echo $0"])
865 .succeeds()
866 .stdout_only("hijacked\n");
867 }
868
869 // Do not assume that coreutils uses argv0
870 #[test]
871 #[cfg(unix)]
872 fn test_env_arg_argv0_overwrite() {
873 let ts = TestScenario::new(util_name!());
874
875 // overwrite --argv0 by --argv0
876 ts.ucmd()
877 .args(&["--argv0", "dirname"])
878 .args(&["--argv0", "hijacked", "sh", "-c", "echo $0"])
879 .succeeds()
880 .stdout_only("hijacked\n");
881
882 // overwrite -a by -a
883 ts.ucmd()
884 .args(&["-a", "dirname"])
885 .args(&["-a", "hijacked", "sh", "-c", "echo $0"])
886 .succeeds()
887 .stdout_only("hijacked\n");
888
889 // overwrite --argv0 by -a
890 ts.ucmd()
891 .args(&["--argv0", "dirname"])
892 .args(&["-a", "hijacked", "sh", "-c", "echo $0"])
893 .succeeds()
894 .stdout_only("hijacked\n");
895
896 // overwrite -a by --argv0
897 ts.ucmd()
898 .args(&["-a", "dirname"])
899 .args(&["--argv0", "hijacked", "sh", "-c", "echo $0"])
900 .succeeds()
901 .stdout_only("hijacked\n");
902 }
903
904 // Do not assume that coreutils uses argv0
905 #[test]
906 #[cfg(unix)]
907 fn test_env_arg_argv0_overwrite_mixed_with_string_args() {
908 let ts = TestScenario::new(util_name!());
909
910 // string arg following normal
911 ts.ucmd()
912 .args(&["-S--argv0 dirname"])
913 .args(&["--argv0", "hijacked", "sh", "-c", "echo $0"])
914 .succeeds()
915 .stdout_only("hijacked\n");
916
917 // normal following string arg
918 ts.ucmd()
919 .args(&["-a", "dirname"])
920 .args(&["-S-a hijacked sh -c 'echo $0'"])
921 .succeeds()
922 .stdout_only("hijacked\n");
923
924 // one large string arg
925 ts.ucmd()
926 .args(&["-S--argv0 dirname -a hijacked sh -c 'echo $0'"])
927 .succeeds()
928 .stdout_only("hijacked\n");
929
930 // two string args
931 ts.ucmd()
932 .args(&["-S-a dirname"])
933 .args(&["-S--argv0 hijacked sh -c 'echo $0'"])
934 .succeeds()
935 .stdout_only("hijacked\n");
936
937 // three args: normal, string, normal
938 ts.ucmd()
939 .args(&["-a", "sleep"])
940 .args(&["-S-a dirname"])
941 .args(&["-a", "hijacked", "sh", "-c", "echo $0"])
942 .succeeds()
943 .stdout_only("hijacked\n");
944 }
945
946 #[test]
947 #[cfg(unix)]
948 fn test_env_arg_ignore_signal_invalid_signals() {
949 let ts = TestScenario::new(util_name!());
950 ts.ucmd()
951 .args(&["--ignore-signal=banana"])
952 .fails_with_code(125)
953 .stderr_contains("env: 'banana': invalid signal");
954 ts.ucmd()
955 .args(&["--ignore-signal=SIGbanana"])
956 .fails_with_code(125)
957 .stderr_contains("env: 'SIGbanana': invalid signal");
958 ts.ucmd()
959 .args(&["--ignore-signal=exit"])
960 .fails_with_code(125)
961 .stderr_contains("env: 'exit': invalid signal");
962 ts.ucmd()
963 .args(&["--ignore-signal=SIGexit"])
964 .fails_with_code(125)
965 .stderr_contains("env: 'SIGexit': invalid signal");
966 }
967
968 #[test]
969 #[cfg(unix)]
970 fn test_env_arg_ignore_signal_special_signals() {
971 let ts = TestScenario::new(util_name!());
972 let signal_stop = nix::sys::signal::SIGSTOP;
973 let signal_kill = nix::sys::signal::SIGKILL;
974 ts.ucmd()
975 .args(&["--ignore-signal=stop", "echo", "hello"])
976 .fails_with_code(125)
977 .stderr_contains(format!(
978 "env: failed to set signal action for signal {}: Invalid argument",
979 signal_stop as i32
980 ));
981 ts.ucmd()
982 .args(&["--ignore-signal=kill", "echo", "hello"])
983 .fails_with_code(125)
984 .stderr_contains(format!(
985 "env: failed to set signal action for signal {}: Invalid argument",
986 signal_kill as i32
987 ));
988 ts.ucmd()
989 .args(&["--ignore-signal=SToP", "echo", "hello"])
990 .fails_with_code(125)
991 .stderr_contains(format!(
992 "env: failed to set signal action for signal {}: Invalid argument",
993 signal_stop as i32
994 ));
995 ts.ucmd()
996 .args(&["--ignore-signal=SIGKILL", "echo", "hello"])
997 .fails_with_code(125)
998 .stderr_contains(format!(
999 "env: failed to set signal action for signal {}: Invalid argument",
1000 signal_kill as i32
1001 ));
1002 }
1003
1004 #[test]
1005 #[cfg(unix)]
1006 fn test_env_arg_ignore_signal_valid_signals() {
1007 {
1008 let mut target = Target::new(&["int"]);
1009 target.send_signal(Signal::SIGINT);
1010 assert!(target.is_alive());
1011 }
1012 {
1013 let mut target = Target::new(&["usr2"]);
1014 target.send_signal(Signal::SIGUSR2);
1015 assert!(target.is_alive());
1016 }
1017 {
1018 let mut target = Target::new(&["int", "usr2"]);
1019 target.send_signal(Signal::SIGUSR1);
1020 assert!(!target.is_alive());
1021 }
1022 }
1023
1024 #[test]
1025 #[cfg(unix)]
1026 fn test_env_arg_ignore_signal_empty() {
1027 let ts = TestScenario::new(util_name!());
1028 ts.ucmd()
1029 .args(&["--ignore-signal=", "echo", "hello"])
1030 .succeeds()
1031 .no_stderr()
1032 .stdout_contains("hello");
1033 }
1034
1035 #[test]
1036 #[cfg(unix)]
1037 fn test_env_arg_ignore_signal_all_signals() {
1038 let mut target = Target::new(&[]);
1039 target.send_signal(Signal::SIGINT);
1040 assert!(target.is_alive());
1041 }
1042
1043 #[test]
1044 #[cfg(unix)]
1045 fn test_env_default_signal_pipe() {
1046 let ts = TestScenario::new(util_name!());
1047 run_sigpipe_script(&ts, &["--default-signal=PIPE"]);
1048 }
1049
1050 #[test]
1051 #[cfg(unix)]
1052 fn test_env_default_signal_all_signals() {
1053 let ts = TestScenario::new(util_name!());
1054 run_sigpipe_script(&ts, &["--default-signal"]);
1055 }
1056
1057 #[test]
1058 #[cfg(unix)]
1059 fn test_env_block_signal_flag() {
1060 new_ucmd!()
1061 .env("PATH", PATH)
1062 .args(&["--block-signal", "true"])
1063 .succeeds()
1064 .no_stderr();
1065 }
1066
1067 #[test]
1068 #[cfg(any(target_os = "linux", target_os = "android"))]
1069 fn test_env_block_realtime_signal() {
1070 new_ucmd!()
1071 .env("PATH", PATH)
1072 .args(&["--block-signal=SIGRTMIN+7", "true"])
1073 .succeeds()
1074 .no_stderr();
1075 new_ucmd!()
1076 .env("PATH", PATH)
1077 .args(&["--block-signal=SIGRTMAX-7", "true"])
1078 .succeeds()
1079 .no_stderr();
1080 }
1081
1082 #[test]
1083 #[cfg(unix)]
1084 fn test_env_list_signal_handling_reports_ignore() {
1085 let result = new_ucmd!()
1086 .env("PATH", PATH)
1087 .args(&["--ignore-signal=INT", "--list-signal-handling", "true"])
1088 .succeeds();
1089 let stderr = result.stderr_str();
1090 assert!(
1091 stderr.contains("INT") && stderr.contains("IGNORE"),
1092 "unexpected signal listing: {stderr}"
1093 );
1094 }
1095
1096 #[cfg(unix)]
1097 fn run_sigpipe_script(ts: &TestScenario, extra_args: &[&str]) {
1098 let shell = env::var("SHELL").unwrap_or_else(|_| String::from("sh"));
1099 let _guard = SigpipeGuard::new();
1100 let mut cmd = ts.ucmd();
1101 cmd.env("PATH", PATH);
1102 cmd.args(extra_args);
1103 cmd.arg(shell);
1104 cmd.arg("-c");
1105 cmd.arg("trap - PIPE; seq 999999 2>err | head -n1 > out");
1106 cmd.succeeds();
1107 assert_eq!(ts.fixtures.read("out"), "1\n");
1108 assert_eq!(ts.fixtures.read("err"), "");
1109 }
1110
1111 #[cfg(unix)]
1112 struct SigpipeGuard {
1113 previous: libc::sighandler_t,
1114 }
1115
1116 #[cfg(unix)]
1117 impl SigpipeGuard {
1118 fn new() -> Self {
1119 let previous = unsafe { libc::signal(libc::SIGPIPE, libc::SIG_IGN) };
1120 Self { previous }
1121 }
1122 }
1123
1124 #[cfg(unix)]
1125 impl Drop for SigpipeGuard {
1126 fn drop(&mut self) {
1127 unsafe {
1128 libc::signal(libc::SIGPIPE, self.previous);
1129 }
1130 }
1131 }
1132
1133 #[test]
1134 fn disallow_equals_sign_on_short_unset_option() {
1135 let ts = TestScenario::new(util_name!());
1136
1137 ts.ucmd()
1138 .arg("-u=")
1139 .fails_with_code(125)
1140 .stderr_contains("env: cannot unset '=': Invalid argument");
1141 ts.ucmd()
1142 .arg("-u=A1B2C3")
1143 .fails_with_code(125)
1144 .stderr_contains("env: cannot unset '=A1B2C3': Invalid argument");
1145 ts.ucmd().arg("--split-string=A1B=2C3=").succeeds();
1146 ts.ucmd()
1147 .arg("--unset=")
1148 .fails_with_code(125)
1149 .stderr_contains("env: cannot unset '': Invalid argument");
1150 }
1151
1152 #[cfg(test)]
1153 mod tests_split_iterator {
1154
1155 enum EscapeStyle {
1156 /// No escaping.
1157 None,
1158 /// Wrap in single quotes.
1159 SingleQuoted,
1160 /// Single quotes combined with backslash.
1161 Mixed,
1162 }
1163
1164 /// Determines escaping style to use.
1165 fn escape_style(s: &str) -> EscapeStyle {
1166 if s.is_empty() {
1167 return EscapeStyle::SingleQuoted;
1168 }
1169
1170 let mut special = false;
1171 let mut newline = false;
1172 let mut single_quote = false;
1173
1174 for c in s.chars() {
1175 match c {
1176 '\n' => {
1177 newline = true;
1178 special = true;
1179 }
1180 '\'' => {
1181 single_quote = true;
1182 special = true;
1183 }
1184 '|' | '&' | ';' | '<' | '>' | '(' | ')' | '$' | '`' | '\\' | '"' | ' ' | '\t'
1185 | '*' | '?' | '[' | '#' | '˜' | '=' | '%' => {
1186 special = true;
1187 }
1188 _ => (),
1189 }
1190 }
1191
1192 if !special {
1193 EscapeStyle::None
1194 } else if newline && !single_quote {
1195 EscapeStyle::SingleQuoted
1196 } else {
1197 EscapeStyle::Mixed
1198 }
1199 }
1200
1201 /// Escapes special characters in a string, so that it will retain its literal
1202 /// meaning when used as a part of command in Unix shell.
1203 ///
1204 /// It tries to avoid introducing any unnecessary quotes or escape characters,
1205 /// but specifics regarding quoting style are left unspecified.
1206 pub fn quote(s: &str) -> std::borrow::Cow<'_, str> {
1207 // We are going somewhat out of the way to provide
1208 // minimal amount of quoting in typical cases.
1209 match escape_style(s) {
1210 EscapeStyle::None => s.into(),
1211 EscapeStyle::SingleQuoted => format!("'{s}'").into(),
1212 EscapeStyle::Mixed => {
1213 let mut quoted = String::new();
1214 quoted.push('\'');
1215 for c in s.chars() {
1216 if c == '\'' {
1217 quoted.push_str("'\\''");
1218 } else {
1219 quoted.push(c);
1220 }
1221 }
1222 quoted.push('\'');
1223 quoted.into()
1224 }
1225 }
1226 }
1227
1228 /// Joins arguments into a single command line suitable for execution in Unix
1229 /// shell.
1230 ///
1231 /// Each argument is quoted using [`quote`] to preserve its literal meaning when
1232 /// parsed by Unix shell.
1233 ///
1234 /// Note: This function is essentially an inverse of [`split`].
1235 ///
1236 /// # Examples
1237 ///
1238 /// Logging executed commands in format that can be easily copied and pasted
1239 /// into an actual shell:
1240 ///
1241 /// ```rust,no_run
1242 /// fn execute(args: &[&str]) {
1243 /// use std::process::Command;
1244 /// println!("Executing: {}", shell_words::join(args));
1245 /// Command::new(&args[0])
1246 /// .args(&args[1..])
1247 /// .spawn()
1248 /// .expect("failed to start subprocess")
1249 /// .wait()
1250 /// .expect("failed to wait for subprocess");
1251 /// }
1252 ///
1253 /// execute(&["python", "-c", "print('Hello world!')"]);
1254 /// ```
1255 ///
1256 /// [`quote`]: fn.quote.html
1257 /// [`split`]: fn.split.html
1258 pub fn join<I, S>(words: I) -> String
1259 where
1260 I: IntoIterator<Item = S>,
1261 S: AsRef<str>,
1262 {
1263 let mut line = words.into_iter().fold(String::new(), |mut line, word| {
1264 let quoted = quote(word.as_ref());
1265 line.push_str(quoted.as_ref());
1266 line.push(' ');
1267 line
1268 });
1269 line.pop();
1270 line
1271 }
1272
1273 use std::ffi::OsString;
1274
1275 use env::{
1276 EnvError,
1277 native_int_str::{Convert, NCvt, from_native_int_representation_owned},
1278 };
1279
1280 fn split(input: &str) -> Result<Vec<OsString>, EnvError> {
1281 ::env::split_iterator::split(&NCvt::convert(input)).map(|vec| {
1282 vec.into_iter()
1283 .map(from_native_int_representation_owned)
1284 .collect()
1285 })
1286 }
1287
1288 fn split_ok(cases: &[(&str, &[&str])]) {
1289 for (i, &(input, expected)) in cases.iter().enumerate() {
1290 match split(input) {
1291 Err(actual) => {
1292 panic!(
1293 "[{i}] calling split({input:?}):\nexpected: Ok({expected:?})\n actual: Err({actual:?})\n"
1294 );
1295 }
1296 Ok(actual) => {
1297 assert_eq!(
1298 expected,
1299 actual.as_slice(),
1300 "[{i}] After split({input:?}).unwrap()\nexpected: {expected:?}\n actual: {actual:?}\n"
1301 );
1302 }
1303 }
1304 }
1305 }
1306
1307 #[test]
1308 fn split_empty() {
1309 split_ok(&[("", &[])]);
1310 }
1311
1312 #[test]
1313 fn split_initial_whitespace_is_removed() {
1314 split_ok(&[
1315 (" a", &["a"]),
1316 ("\t\t\t\tbar", &["bar"]),
1317 ("\t \nc", &["c"]),
1318 ]);
1319 }
1320
1321 #[test]
1322 fn split_trailing_whitespace_is_removed() {
1323 split_ok(&[
1324 ("a ", &["a"]),
1325 ("b\t", &["b"]),
1326 ("c\t \n \n \n", &["c"]),
1327 ("d\n\n", &["d"]),
1328 ]);
1329 }
1330
1331 #[test]
1332 fn split_carriage_return() {
1333 split_ok(&[("c\ra\r'\r'\r", &["c", "a", "\r"])]);
1334 }
1335
1336 #[test]
1337 fn split_() {
1338 split_ok(&[("\\'\\'", &["''"])]);
1339 }
1340
1341 #[test]
1342 fn split_single_quotes() {
1343 split_ok(&[
1344 (r"''", &[r""]),
1345 (r"'a'", &[r"a"]),
1346 (r"'\\'", &[r"\"]),
1347 (r"' \\ '", &[r" \ "]),
1348 (r"'#'", &[r"#"]),
1349 ]);
1350 }
1351
1352 #[test]
1353 fn split_double_quotes() {
1354 split_ok(&[
1355 (r#""""#, &[""]),
1356 (r#""""""#, &[""]),
1357 (r#""a b c' d""#, &["a b c' d"]),
1358 (r#""\$""#, &["$"]),
1359 (r#""`""#, &["`"]),
1360 (r#""\"""#, &["\""]),
1361 (r#""\\""#, &["\\"]),
1362 ("\"\n\"", &["\n"]),
1363 ("\"\\\n\"", &[""]),
1364 ]);
1365 }
1366
1367 #[test]
1368 fn split_unquoted() {
1369 split_ok(&[
1370 (r"\\|\\&\\;", &[r"\|\&\;"]),
1371 (r"\\<\\>", &[r"\<\>"]),
1372 (r"\\(\\)", &[r"\(\)"]),
1373 (r"\$", &[r"$"]),
1374 (r#"\""#, &[r#"""#]),
1375 (r"\'", &[r"'"]),
1376 ("\\\n", &[]),
1377 (" \\\n \n", &[]),
1378 ("a\nb\nc", &["a", "b", "c"]),
1379 ("a\\\nb\\\nc", &["abc"]),
1380 ("foo bar baz", &["foo", "bar", "baz"]),
1381 ]);
1382 }
1383
1384 #[test]
1385 fn split_trailing_backslash() {
1386 assert_eq!(
1387 split("\\"),
1388 Err(EnvError::EnvInvalidBackslashAtEndOfStringInMinusS(
1389 1,
1390 "Delimiter".into()
1391 ))
1392 );
1393 assert_eq!(
1394 split(" \\"),
1395 Err(EnvError::EnvInvalidBackslashAtEndOfStringInMinusS(
1396 2,
1397 "Delimiter".into()
1398 ))
1399 );
1400 assert_eq!(
1401 split("a\\"),
1402 Err(EnvError::EnvInvalidBackslashAtEndOfStringInMinusS(
1403 2,
1404 "Unquoted".into()
1405 ))
1406 );
1407 }
1408
1409 #[test]
1410 fn split_errors() {
1411 assert_eq!(
1412 split("'abc"),
1413 Err(EnvError::EnvMissingClosingQuote(4, '\''))
1414 );
1415 assert_eq!(split("\""), Err(EnvError::EnvMissingClosingQuote(1, '"')));
1416 assert_eq!(split("'\\"), Err(EnvError::EnvMissingClosingQuote(2, '\'')));
1417 assert_eq!(split("'\\"), Err(EnvError::EnvMissingClosingQuote(2, '\'')));
1418 assert_eq!(
1419 split(r#""$""#),
1420 Err(EnvError::EnvParsingOfVariableOnlyBracedName(2)),
1421 );
1422 }
1423
1424 #[test]
1425 fn split_error_fail_with_unknown_escape_sequences() {
1426 assert_eq!(
1427 split("\\a"),
1428 Err(EnvError::EnvInvalidSequenceBackslashXInMinusS(1, 'a'))
1429 );
1430 assert_eq!(
1431 split("\"\\a\""),
1432 Err(EnvError::EnvInvalidSequenceBackslashXInMinusS(2, 'a'))
1433 );
1434 assert_eq!(split("'\\a'"), Ok(vec![OsString::from("\\a")]));
1435 assert_eq!(split("'\\`'"), Ok(vec![OsString::from("\\`")]));
1436 assert_eq!(
1437 split(r#""\a""#),
1438 Err(EnvError::EnvInvalidSequenceBackslashXInMinusS(2, 'a'))
1439 );
1440 assert_eq!(
1441 split(r"\🦉"),
1442 Err(EnvError::EnvInvalidSequenceBackslashXInMinusS(
1443 1, '\u{FFFD}'
1444 ))
1445 );
1446 }
1447
1448 #[test]
1449 fn split_comments() {
1450 split_ok(&[
1451 (r" x # comment ", &["x"]),
1452 (r" w1#w2 ", &["w1#w2"]),
1453 (r"'not really a # comment'", &["not really a # comment"]),
1454 (" a # very long comment \n b # another comment", &["a", "b"]),
1455 ]);
1456 }
1457
1458 #[test]
1459 fn test_quote() {
1460 assert_eq!(quote(""), "''");
1461 assert_eq!(quote("'"), "''\\'''");
1462 assert_eq!(quote("abc"), "abc");
1463 assert_eq!(quote("a \n b"), "'a \n b'");
1464 assert_eq!(quote("X'\nY"), "'X'\\''\nY'");
1465 }
1466
1467 #[test]
1468 fn test_join() {
1469 assert_eq!(join(["a", "b", "c"]), "a b c");
1470 assert_eq!(join([" ", "$", "\n"]), "' ' '$' '\n'");
1471 }
1472
1473 #[test]
1474 fn join_followed_by_split_is_identity() {
1475 let cases: Vec<&[&str]> = vec![
1476 &["a"],
1477 &["python", "-c", "print('Hello world!')"],
1478 &["echo", " arg with spaces ", "arg \' with \" quotes"],
1479 &["even newlines are quoted correctly\n", "\n", "\n\n\t "],
1480 &["$", "`test`"],
1481 &["cat", "~user/log*"],
1482 &["test", "'a \"b", "\"X'"],
1483 &["empty", "", "", ""],
1484 ];
1485 for argv in cases {
1486 let args = join(argv);
1487 assert_eq!(split(&args).unwrap(), argv);
1488 }
1489 }
1490 }
1491
1492 mod test_raw_string_parser {
1493 use std::{
1494 borrow::Cow,
1495 ffi::{OsStr, OsString},
1496 };
1497
1498 use env::{
1499 native_int_str::{
1500 NativeStr, from_native_int_representation, from_native_int_representation_owned,
1501 to_native_int_representation,
1502 },
1503 string_expander::StringExpander,
1504 string_parser,
1505 };
1506
1507 const LEN_OWL: usize = if cfg!(windows) { 2 } else { 4 };
1508
1509 #[test]
1510 fn test_ascii_only_take_one_look_at_correct_data_and_end_behavior() {
1511 let input = "hello";
1512 let cow = to_native_int_representation(OsStr::new(input));
1513 let mut uut = StringExpander::new(&cow);
1514 for c in input.chars() {
1515 assert_eq!(c, uut.get_parser().peek().unwrap());
1516 uut.take_one().unwrap();
1517 }
1518 assert_eq!(
1519 uut.get_parser().peek(),
1520 Err(string_parser::Error {
1521 peek_position: 5,
1522 err_type: string_parser::ErrorType::EndOfInput
1523 })
1524 );
1525 uut.take_one().unwrap_err();
1526 uut.take_one().unwrap_err();
1527 assert_eq!(
1528 from_native_int_representation_owned(uut.take_collected_output()),
1529 input
1530 );
1531 uut.take_one().unwrap_err();
1532 assert_eq!(
1533 from_native_int_representation_owned(uut.take_collected_output()),
1534 ""
1535 );
1536 }
1537
1538 #[test]
1539 fn test_multi_byte_codes_take_one_look_at_correct_data_and_end_behavior() {
1540 let input = OsString::from("🦉🦉🦉x🦉🦉x🦉x🦉🦉🦉🦉");
1541 let cow = to_native_int_representation(input.as_os_str());
1542 let mut uut = StringExpander::new(&cow);
1543 for _i in 0..3 {
1544 assert_eq!(uut.get_parser().peek().unwrap(), '\u{FFFD}');
1545 uut.take_one().unwrap();
1546 assert_eq!(uut.get_parser().peek().unwrap(), 'x');
1547 uut.take_one().unwrap();
1548 }
1549 assert_eq!(uut.get_parser().peek().unwrap(), '\u{FFFD}');
1550 uut.take_one().unwrap();
1551 assert_eq!(
1552 uut.get_parser().peek(),
1553 Err(string_parser::Error {
1554 peek_position: 10 * LEN_OWL + 3,
1555 err_type: string_parser::ErrorType::EndOfInput
1556 })
1557 );
1558 uut.take_one().unwrap_err();
1559 uut.take_one().unwrap_err();
1560 assert_eq!(
1561 from_native_int_representation_owned(uut.take_collected_output()),
1562 input
1563 );
1564 uut.take_one().unwrap_err();
1565 assert_eq!(
1566 from_native_int_representation_owned(uut.take_collected_output()),
1567 ""
1568 );
1569 }
1570
1571 #[test]
1572 fn test_multi_byte_codes_put_one_ascii_start_middle_end_try_invalid_ascii() {
1573 let input = OsString::from("🦉🦉🦉x🦉🦉x🦉x🦉🦉🦉🦉");
1574 let cow = to_native_int_representation(input.as_os_str());
1575 let owl: char = '🦉';
1576 let mut uut = StringExpander::new(&cow);
1577 uut.put_one_char('a');
1578 for _i in 0..3 {
1579 assert_eq!(uut.get_parser().peek().unwrap(), '\u{FFFD}');
1580 uut.take_one().unwrap();
1581 uut.put_one_char('a');
1582 assert_eq!(uut.get_parser().peek().unwrap(), 'x');
1583 uut.take_one().unwrap();
1584 uut.put_one_char('a');
1585 }
1586 assert_eq!(uut.get_parser().peek().unwrap(), '\u{FFFD}');
1587 uut.take_one().unwrap();
1588 uut.put_one_char(owl);
1589 uut.put_one_char('a');
1590 assert_eq!(
1591 uut.get_parser().peek(),
1592 Err(string_parser::Error {
1593 peek_position: LEN_OWL * 10 + 3,
1594 err_type: string_parser::ErrorType::EndOfInput
1595 })
1596 );
1597 uut.take_one().unwrap_err();
1598 uut.put_one_char('a');
1599 uut.take_one().unwrap_err();
1600 assert_eq!(
1601 from_native_int_representation_owned(uut.take_collected_output()),
1602 "a🦉🦉🦉axa🦉🦉axa🦉axa🦉🦉🦉🦉🦉aa"
1603 );
1604 uut.take_one().unwrap_err();
1605 assert_eq!(
1606 from_native_int_representation_owned(uut.take_collected_output()),
1607 ""
1608 );
1609 }
1610
1611 #[test]
1612 fn test_multi_byte_codes_skip_one_take_one_skip_until_ascii_char_or_end() {
1613 let input = OsString::from("🦉🦉🦉x🦉🦉x🦉x🦉🦉🦉🦉");
1614 let cow = to_native_int_representation(input.as_os_str());
1615 let mut uut = StringExpander::new(&cow);
1616
1617 uut.skip_one().unwrap(); // skip 🦉🦉🦉
1618 let p = LEN_OWL * 3;
1619 assert_eq!(uut.get_peek_position(), p);
1620
1621 uut.skip_one().unwrap(); // skip x
1622 assert_eq!(uut.get_peek_position(), p + 1);
1623 uut.take_one().unwrap(); // take 🦉🦉
1624 let p = p + 1 + LEN_OWL * 2;
1625 assert_eq!(uut.get_peek_position(), p);
1626
1627 uut.skip_one().unwrap(); // skip x
1628 assert_eq!(uut.get_peek_position(), p + 1);
1629 uut.get_parser_mut().skip_until_char_or_end('x'); // skip 🦉
1630 let p = p + 1 + LEN_OWL;
1631 assert_eq!(uut.get_peek_position(), p);
1632 uut.take_one().unwrap(); // take x
1633 uut.get_parser_mut().skip_until_char_or_end('x'); // skip 🦉🦉🦉🦉 till end
1634 let p = p + 1 + LEN_OWL * 4;
1635 assert_eq!(uut.get_peek_position(), p);
1636
1637 uut.take_one().unwrap_err();
1638 assert_eq!(
1639 from_native_int_representation_owned(uut.take_collected_output()),
1640 "🦉🦉x"
1641 );
1642 }
1643
1644 #[test]
1645 fn test_multi_byte_codes_skip_multiple_ascii_bounded_good_and_bad() {
1646 let input = OsString::from("🦉🦉🦉x🦉🦉x🦉x🦉🦉🦉🦉");
1647 let cow = to_native_int_representation(input.as_os_str());
1648 let mut uut = StringExpander::new(&cow);
1649
1650 uut.get_parser_mut().skip_multiple(0);
1651 assert_eq!(uut.get_peek_position(), 0);
1652 let p = LEN_OWL * 3;
1653 uut.get_parser_mut().skip_multiple(p); // skips 🦉🦉🦉
1654 assert_eq!(uut.get_peek_position(), p);
1655
1656 uut.take_one().unwrap(); // take x
1657 assert_eq!(uut.get_peek_position(), p + 1);
1658 let step = LEN_OWL * 3 + 1;
1659 uut.get_parser_mut().skip_multiple(step); // skips 🦉🦉x🦉
1660 let p = p + 1 + step;
1661 assert_eq!(uut.get_peek_position(), p);
1662 uut.take_one().unwrap(); // take x
1663
1664 assert_eq!(uut.get_peek_position(), p + 1);
1665 let step = 4 * LEN_OWL;
1666 uut.get_parser_mut().skip_multiple(step); // skips 🦉🦉🦉🦉
1667 let p = p + 1 + step;
1668 assert_eq!(uut.get_peek_position(), p);
1669
1670 uut.take_one().unwrap_err();
1671 assert_eq!(
1672 from_native_int_representation_owned(uut.take_collected_output()),
1673 "xx"
1674 );
1675 }
1676
1677 #[test]
1678 fn test_multi_byte_codes_put_string_utf8_start_middle_end() {
1679 let input = OsString::from("🦉🦉🦉x🦉🦉x🦉x🦉🦉🦉🦉");
1680 let cow = to_native_int_representation(input.as_os_str());
1681 let mut uut = StringExpander::new(&cow);
1682
1683 uut.put_string("🦔oo");
1684 uut.take_one().unwrap(); // takes 🦉🦉🦉
1685 uut.put_string("oo🦔");
1686 uut.take_one().unwrap(); // take x
1687 uut.get_parser_mut().skip_until_char_or_end('\n'); // skips till end
1688 uut.put_string("o🦔o");
1689
1690 uut.take_one().unwrap_err();
1691 assert_eq!(
1692 from_native_int_representation_owned(uut.take_collected_output()),
1693 "🦔oo🦉🦉🦉oo🦔xo🦔o"
1694 );
1695 }
1696
1697 #[test]
1698 fn test_multi_byte_codes_look_at_remaining_start_middle_end() {
1699 let input = "🦉🦉🦉x🦉🦉x🦉x🦉🦉🦉🦉";
1700 let cow = to_native_int_representation(OsStr::new(input));
1701 let mut uut = StringExpander::new(&cow);
1702
1703 assert_eq!(uut.get_parser().peek_remaining(), OsStr::new(input));
1704 uut.take_one().unwrap(); // takes 🦉🦉🦉
1705 assert_eq!(uut.get_parser().peek_remaining(), OsStr::new(&input[12..]));
1706 uut.get_parser_mut().skip_until_char_or_end('\n'); // skips till end
1707 assert_eq!(uut.get_parser().peek_remaining(), OsStr::new(""));
1708
1709 uut.take_one().unwrap_err();
1710 assert_eq!(
1711 from_native_int_representation_owned(uut.take_collected_output()),
1712 "🦉🦉🦉"
1713 );
1714 }
1715
1716 #[test]
1717 fn test_deal_with_invalid_encoding() {
1718 let owl_invalid_part;
1719 let (brace_1, brace_2);
1720 #[cfg(windows)]
1721 {
1722 let mut buffer = [0u16; 2];
1723 let owl = '🦉'.encode_utf16(&mut buffer);
1724 owl_invalid_part = owl[0];
1725 brace_1 = '<'.encode_utf16(&mut buffer).to_vec();
1726 brace_2 = '>'.encode_utf16(&mut buffer).to_vec();
1727 }
1728 #[cfg(not(windows))]
1729 {
1730 let mut buffer = [0u8; 4];
1731 let owl = '🦉'.encode_utf8(&mut buffer);
1732 owl_invalid_part = owl.bytes().next().unwrap();
1733 brace_1 = b"<".to_vec();
1734 brace_2 = b">".to_vec();
1735 }
1736 let mut input_ux = brace_1;
1737 input_ux.push(owl_invalid_part);
1738 input_ux.extend(brace_2);
1739 let input_str = from_native_int_representation(Cow::Borrowed(&input_ux));
1740 let mut uut = StringExpander::new(&input_ux);
1741
1742 assert_eq!(uut.get_parser().peek_remaining(), input_str);
1743 assert_eq!(uut.get_parser().peek().unwrap(), '<');
1744 uut.take_one().unwrap(); // takes "<"
1745 assert_eq!(
1746 uut.get_parser().peek_remaining(),
1747 NativeStr::new(&input_str).split_at(1).1
1748 );
1749 assert_eq!(uut.get_parser().peek().unwrap(), '\u{FFFD}');
1750 uut.take_one().unwrap(); // takes owl_b
1751 assert_eq!(
1752 uut.get_parser().peek_remaining(),
1753 NativeStr::new(&input_str).split_at(2).1
1754 );
1755 assert_eq!(uut.get_parser().peek().unwrap(), '>');
1756 uut.get_parser_mut().skip_until_char_or_end('\n');
1757 assert_eq!(uut.get_parser().peek_remaining(), OsStr::new(""));
1758
1759 uut.take_one().unwrap_err();
1760 assert_eq!(
1761 from_native_int_representation_owned(uut.take_collected_output()),
1762 NativeStr::new(&input_str).split_at(2).0
1763 );
1764 }
1765 }
1766
1767 #[cfg(unix)]
1768 #[test]
1769 fn test_simulation_of_terminal_false() {
1770 let scene = TestScenario::new("util");
1771
1772 let out = scene.ccmd("env").arg("sh").arg("is_a_tty.sh").succeeds();
1773 std::assert_eq!(
1774 String::from_utf8_lossy(out.stdout()),
1775 "stdin is not a tty\nstdout is not a tty\nstderr is not a tty\n"
1776 );
1777 std::assert_eq!(
1778 String::from_utf8_lossy(out.stderr()),
1779 "This is an error message.\n"
1780 );
1781 }
1782
1783 #[cfg(unix)]
1784 #[test]
1785 fn test_simulation_of_terminal_true() {
1786 let scene = TestScenario::new("util");
1787
1788 let out = scene
1789 .ccmd("env")
1790 .arg("sh")
1791 .arg("is_a_tty.sh")
1792 .terminal_simulation(true)
1793 .succeeds();
1794 std::assert_eq!(
1795 String::from_utf8_lossy(out.stdout()),
1796 "stdin is a tty\r\nterminal size: 30 80\r\nstdout is a tty\r\nstderr is a tty\r\n"
1797 );
1798 std::assert_eq!(
1799 String::from_utf8_lossy(out.stderr()),
1800 "This is an error message.\r\n"
1801 );
1802 }
1803
1804 #[cfg(unix)]
1805 #[test]
1806 fn test_simulation_of_terminal_for_stdin_only() {
1807 let scene = TestScenario::new("util");
1808
1809 let out = scene
1810 .ccmd("env")
1811 .arg("sh")
1812 .arg("is_a_tty.sh")
1813 .terminal_sim_stdio(TerminalSimulation {
1814 stdin: true,
1815 stdout: false,
1816 stderr: false,
1817 ..Default::default()
1818 })
1819 .succeeds();
1820 std::assert_eq!(
1821 String::from_utf8_lossy(out.stdout()),
1822 "stdin is a tty\nterminal size: 30 80\nstdout is not a tty\nstderr is not a tty\n"
1823 );
1824 std::assert_eq!(
1825 String::from_utf8_lossy(out.stderr()),
1826 "This is an error message.\n"
1827 );
1828 }
1829
1830 #[cfg(unix)]
1831 #[test]
1832 fn test_simulation_of_terminal_for_stdout_only() {
1833 let scene = TestScenario::new("util");
1834
1835 let out = scene
1836 .ccmd("env")
1837 .arg("sh")
1838 .arg("is_a_tty.sh")
1839 .terminal_sim_stdio(TerminalSimulation {
1840 stdin: false,
1841 stdout: true,
1842 stderr: false,
1843 ..Default::default()
1844 })
1845 .succeeds();
1846 std::assert_eq!(
1847 String::from_utf8_lossy(out.stdout()),
1848 "stdin is not a tty\r\nstdout is a tty\r\nstderr is not a tty\r\n"
1849 );
1850 std::assert_eq!(
1851 String::from_utf8_lossy(out.stderr()),
1852 "This is an error message.\n"
1853 );
1854 }
1855
1856 #[cfg(unix)]
1857 #[test]
1858 fn test_simulation_of_terminal_for_stderr_only() {
1859 let scene = TestScenario::new("util");
1860
1861 let out = scene
1862 .ccmd("env")
1863 .arg("sh")
1864 .arg("is_a_tty.sh")
1865 .terminal_sim_stdio(TerminalSimulation {
1866 stdin: false,
1867 stdout: false,
1868 stderr: true,
1869 ..Default::default()
1870 })
1871 .succeeds();
1872 std::assert_eq!(
1873 String::from_utf8_lossy(out.stdout()),
1874 "stdin is not a tty\nstdout is not a tty\nstderr is a tty\n"
1875 );
1876 std::assert_eq!(
1877 String::from_utf8_lossy(out.stderr()),
1878 "This is an error message.\r\n"
1879 );
1880 }
1881
1882 #[cfg(unix)]
1883 #[test]
1884 fn test_simulation_of_terminal_size_information() {
1885 let scene = TestScenario::new("util");
1886
1887 let out = scene
1888 .ccmd("env")
1889 .arg("sh")
1890 .arg("is_a_tty.sh")
1891 .terminal_sim_stdio(TerminalSimulation {
1892 size: Some(libc::winsize {
1893 ws_col: 40,
1894 ws_row: 10,
1895 ws_xpixel: 40 * 8,
1896 ws_ypixel: 10 * 10,
1897 }),
1898 stdout: true,
1899 stdin: true,
1900 stderr: true,
1901 })
1902 .succeeds();
1903 std::assert_eq!(
1904 String::from_utf8_lossy(out.stdout()),
1905 "stdin is a tty\r\nterminal size: 10 40\r\nstdout is a tty\r\nstderr is a tty\r\n"
1906 );
1907 std::assert_eq!(
1908 String::from_utf8_lossy(out.stderr()),
1909 "This is an error message.\r\n"
1910 );
1911 }
1912
1913 #[cfg(unix)]
1914 #[test]
1915 fn test_simulation_of_terminal_pty_sends_eot_automatically() {
1916 let scene = TestScenario::new("util");
1917
1918 let mut cmd = scene.ccmd("env");
1919 cmd.timeout(std::time::Duration::from_secs(10));
1920 cmd.args(&["cat", "-"]);
1921 cmd.terminal_simulation(true);
1922 let child = cmd.run_no_wait();
1923 let out = child.wait().unwrap(); // cat would block if there is no eot
1924
1925 std::assert_eq!(String::from_utf8_lossy(out.stderr()), "");
1926 std::assert_eq!(String::from_utf8_lossy(out.stdout()), "\r\n");
1927 }
1928
1929 #[cfg(unix)]
1930 #[test]
1931 fn test_simulation_of_terminal_pty_pipes_into_data_and_sends_eot_automatically() {
1932 let scene = TestScenario::new("util");
1933
1934 let message = "Hello stdin forwarding!";
1935
1936 let mut cmd = scene.ccmd("env");
1937 cmd.args(&["cat", "-"]);
1938 cmd.terminal_simulation(true);
1939 cmd.pipe_in(message);
1940 let child = cmd.run_no_wait();
1941 let out = child.wait().unwrap();
1942
1943 std::assert_eq!(
1944 String::from_utf8_lossy(out.stdout()),
1945 format!("{message}\r\n")
1946 );
1947 std::assert_eq!(String::from_utf8_lossy(out.stderr()), "");
1948 }
1949
1950 #[test]
1951 #[cfg(not(windows))]
1952 fn test_emoji_env_vars() {
1953 new_ucmd!()
1954 .arg("🎯_VAR=Hello 🌍")
1955 .arg("printenv")
1956 .arg("🎯_VAR")
1957 .succeeds()
1958 .stdout_contains("Hello 🌍");
1959 }
1960
1961 #[cfg(unix)]
1962 #[test]
1963 fn test_simulation_of_terminal_pty_write_in_data_and_sends_eot_automatically() {
1964 let scene = TestScenario::new("util");
1965
1966 let mut cmd = scene.ccmd("env");
1967 cmd.args(&["cat", "-"]);
1968 cmd.terminal_simulation(true);
1969 let mut child = cmd.run_no_wait();
1970 child.write_in("Hello stdin forwarding via write_in!");
1971 let out = child.wait().unwrap();
1972
1973 std::assert_eq!(
1974 String::from_utf8_lossy(out.stdout()),
1975 "Hello stdin forwarding via write_in!\r\n"
1976 );
1977 std::assert_eq!(String::from_utf8_lossy(out.stderr()), "");
1978 }
1979
1980 #[test]
1981 fn test_env_french() {
1982 new_ucmd!()
1983 .arg("--verbo")
1984 .env("LANG", "fr_FR")
1985 .fails()
1986 .stderr_contains("erreur : argument inattendu");
1987 }
1988
1989 #[test]
1990 fn test_shebang_error() {
1991 new_ucmd!()
1992 .arg("\'-v \'")
1993 .fails()
1994 .stderr_contains("use -[v]S to pass options in shebang lines");
1995 }
1996
1997 #[test]
1998 #[cfg(not(windows))]
1999 fn test_reject_shell_style_variable_expansions() {
2000 for split in [
2001 "-Secho $TEST_VAR_12345",
2002 "-Secho ${TEST_VAR_12345:fallback}",
2003 "-Secho ${TEST_VAR_12345:-fallback}",
2004 "-Secho ${TEST_VAR_12345-default}",
2005 ] {
2006 new_ucmd!()
2007 .env("TEST_VAR_12345", "value")
2008 .arg(split)
2009 .fails_with_code(125)
2010 .stderr_contains("only ${VARNAME} expansion is supported");
2011 }
2012 }
2013
2014 #[test]
2015 #[cfg(not(windows))]
2016 fn test_simple_braced_variable() {
2017 new_ucmd!()
2018 .env("TEST_VAR_12345", "value")
2019 .arg("-Secho ${TEST_VAR_12345}")
2020 .succeeds()
2021 .stdout_is("value\n");
2022 }
2023
2024 #[test]
2025 fn test_braced_variable_error_missing_closing_brace() {
2026 new_ucmd!()
2027 .arg("-Secho ${FOO")
2028 .fails_with_code(125)
2029 .stderr_contains("only ${VARNAME} expansion is supported, error at: ${FOO");
2030 }
2031
2032 #[test]
2033 fn test_braced_variable_error_rejects_default_syntax() {
2034 new_ucmd!()
2035 .arg("-Secho ${FOO:-value}")
2036 .fails_with_code(125)
2037 .stderr_contains("only ${VARNAME} expansion is supported");
2038 }
2039
2040 #[test]
2041 fn test_braced_variable_error_starts_with_digit() {
2042 new_ucmd!()
2043 .arg("-Secho ${1FOO}")
2044 .fails_with_code(125)
2045 .stderr_contains("only ${VARNAME} expansion is supported, error at: ${1FOO}");
2046 }
2047
2048 #[test]
2049 fn test_braced_variable_error_unexpected_character() {
2050 new_ucmd!()
2051 .arg("-Secho ${FOO?}")
2052 .fails_with_code(125)
2053 .stderr_contains("only ${VARNAME} expansion is supported");
2054 }
2055
2056 #[test]
2057 #[cfg(unix)]
2058 fn test_non_utf8_env_vars() {
2059 use std::ffi::OsString;
2060 use std::os::unix::ffi::OsStringExt;
2061
2062 let non_utf8_value = OsString::from_vec(b"hello\x80world".to_vec());
2063 new_ucmd!()
2064 .env("NON_UTF8_VAR", &non_utf8_value)
2065 .succeeds()
2066 .stdout_contains_bytes(b"NON_UTF8_VAR=hello\x80world");
2067 }
2068
2069 #[test]
2070 #[cfg(unix)]
2071 fn test_ignore_signal_pipe_broken_pipe_regression() {
2072 // Test that --ignore-signal=PIPE properly ignores SIGPIPE in child processes.
2073 // When SIGPIPE is ignored, processes should handle broken pipes gracefully
2074 // instead of being terminated by the signal.
2075 //
2076 // Regression test for: https://github.com/uutils/coreutils/issues/9617
2077
2078 use std::io::{BufRead, BufReader};
2079 use std::process::{Command, Stdio};
2080
2081 let scene = TestScenario::new(util_name!());
2082
2083 // Helper function to simulate a broken pipe scenario (like "seq 1000000 | head -n1")
2084 let test_sigpipe_behavior = |use_ignore_signal: bool| -> i32 {
2085 let mut cmd = Command::new(&scene.bin_path);
2086 cmd.arg("env");
2087
2088 if use_ignore_signal {
2089 cmd.arg("--ignore-signal=PIPE");
2090 }
2091
2092 // Use seq instead of yes - writes bounded output but enough to trigger SIGPIPE
2093 cmd.arg("seq")
2094 .arg("1")
2095 .arg("1000000")
2096 .stdout(Stdio::piped())
2097 .stderr(Stdio::null());
2098
2099 let mut child = cmd.spawn().expect("Failed to spawn env process");
2100
2101 // Read exactly one line then close the pipe to trigger SIGPIPE
2102 if let Some(stdout) = child.stdout.take() {
2103 let mut reader = BufReader::new(stdout);
2104 let mut line = String::new();
2105 let _ = reader.read_line(&mut line);
2106 // Pipe closes when reader is dropped, sending SIGPIPE to writing process
2107 }
2108
2109 // seq should exit quickly (either from SIGPIPE or after handling EPIPE)
2110 match child.wait() {
2111 Ok(status) => status.code().unwrap_or(141), // 128 + 13
2112 Err(_) => 141,
2113 }
2114 };
2115
2116 // Test without signal ignoring - should be killed by SIGPIPE
2117 let normal_exit_code = test_sigpipe_behavior(false);
2118 println!("Normal 'env seq' exit code: {normal_exit_code}");
2119
2120 // Test with --ignore-signal=PIPE - should handle broken pipe gracefully
2121 let ignore_signal_exit_code = test_sigpipe_behavior(true);
2122 println!("With --ignore-signal=PIPE exit code: {ignore_signal_exit_code}");
2123
2124 // Verify the --ignore-signal=PIPE flag changes the behavior
2125 assert!(
2126 ignore_signal_exit_code != 141,
2127 "--ignore-signal=PIPE had no effect! Process was still killed by SIGPIPE (exit code 141). Normal: {normal_exit_code}, --ignore-signal: {ignore_signal_exit_code}"
2128 );
2129
2130 // Expected behavior:
2131 assert_eq!(
2132 normal_exit_code, 141,
2133 "Without --ignore-signal, process should be killed by SIGPIPE"
2134 );
2135 assert_ne!(
2136 ignore_signal_exit_code, 141,
2137 "With --ignore-signal=PIPE, process should NOT be killed by SIGPIPE"
2138 );
2139
2140 // Process should exit gracefully when SIGPIPE is ignored
2141 assert!(
2142 ignore_signal_exit_code == 0 || ignore_signal_exit_code == 1,
2143 "With --ignore-signal=PIPE, process should exit gracefully (0 or 1), got: {ignore_signal_exit_code}"
2144 );
2145 }
2146
2147 #[test]
2148 #[cfg(unix)]
2149 fn test_env_disallow_double_underscore_all() {
2150 new_ucmd!()
2151 .args(&["--ignore-signal=__ALL__", "true"])
2152 .fails()
2153 .stderr_contains("invalid signal");
2154
2155 new_ucmd!()
2156 .args(&["--default-signal=__ALL__", "true"])
2157 .fails()
2158 .stderr_contains("invalid signal");
2159
2160 new_ucmd!()
2161 .args(&["--block-signal=__ALL__", "true"])
2162 .fails()
2163 .stderr_contains("invalid signal");
2164 }
2165
2166 #[cfg(unix)]
2167 #[cfg(all(feature = "feat_diagnostics", not(wasi_runner)))]
2168 mod diagnostics {
2169 use super::*;
2170
2171 #[test]
2172 fn test_snippet_points_at_the_unterminated_quote() {
2173 let result = new_ucmd!()
2174 .terminal_sim_stderr()
2175 .args(&["-S", "echo 'unterminated"])
2176 .fails_with_code(125);
2177
2178 // The string is echoed back quoted, since it holds spaces; the caret
2179 // still lands inside it, on the run that never closes.
2180 assert_eq!(
2181 result.stderr_as_displayed(),
2182 "\
2183 env: no terminating quote in -S string at position 18 for quote '''
2184 ╭─[ env:1:9 ]
2185 │
2186 1 │ env -S \"echo 'unterminated\"
2187 │ ──────────────────
2188 │
2189 │ Help: -S quotes as the shell does: ' and \" come in pairs, and \\' escapes a quote
2190 ───╯"
2191 );
2192 }
2193
2194 #[test]
2195 fn test_snippet_points_at_the_invalid_escape() {
2196 let result = new_ucmd!()
2197 .terminal_sim_stderr()
2198 .args(&["-S", "echo \\q"])
2199 .fails_with_code(125);
2200 let stderr = result.stderr_as_displayed();
2201
2202 // The caret covers the backslash and the character it was meant to
2203 // escape, not just the one the parser stopped on.
2204 assert!(stderr.contains("invalid sequence '\\q'"), "{stderr}");
2205 assert!(stderr.contains(" 1 │ env -S 'echo \\q'"), "{stderr}");
2206 assert!(stderr.contains("\n │ ──"), "{stderr}");
2207 }
2208
2209 #[test]
2210 fn test_snippet_points_at_the_whole_variable_reference() {
2211 let result = new_ucmd!()
2212 .terminal_sim_stderr()
2213 .args(&["-S", "echo ${1FOO}"])
2214 .fails_with_code(125);
2215 let stderr = result.stderr_as_displayed();
2216
2217 // Raised on the digit, but the caret covers the reference from its
2218 // `$`, which is what the reader has to fix.
2219 assert!(stderr.contains("only ${VARNAME} expansion"), "{stderr}");
2220 assert!(
2221 stderr.contains("a variable name cannot start with a digit"),
2222 "{stderr}"
2223 );
2224 assert!(stderr.contains("\n │ ─┬─"), "{stderr}");
2225 }
2226
2227 #[test]
2228 fn test_snippet_follows_the_string_when_it_is_glued_to_the_option() {
2229 let result = new_ucmd!()
2230 .terminal_sim_stderr()
2231 .args(&["-Secho ${FOO"])
2232 .fails_with_code(125);
2233 let stderr = result.stderr_as_displayed();
2234
2235 // `-Secho …` carries the string in the same argument, so the caret
2236 // shifts by the two columns the option takes.
2237 assert!(stderr.contains("this { is never closed"), "{stderr}");
2238 assert!(stderr.contains(" 1 │ env '-Secho ${FOO'"), "{stderr}");
2239 assert!(stderr.contains("\n │ ──┬──"), "{stderr}");
2240 }
2241
2242 #[test]
2243 fn test_snippet_points_into_the_right_argument() {
2244 // The same text appears as the command env is asked to run; the caret
2245 // belongs to the -S string, which is where the parse failed.
2246 let result = new_ucmd!()
2247 .terminal_sim_stderr()
2248 .args(&["-S", "echo \\q", "echo \\q"])
2249 .fails_with_code(125);
2250 let stderr = result.stderr_as_displayed();
2251
2252 assert!(stderr.contains("env:1:14"), "{stderr}");
2253 }
2254
2255 #[test]
2256 fn test_plain_message_when_stderr_is_a_pipe() {
2257 // The harness pipes stderr, so the report must not appear.
2258 new_ucmd!()
2259 .args(&["-S", "echo 'unterminated"])
2260 .fails_with_code(125)
2261 .stderr_is("env: no terminating quote in -S string at position 18 for quote '''\n");
2262 }
2263 }