Skip to content

Commit ebaae2e

Browse files
authored
Merge pull request #9726 from ChrisDryden/env-non-utf8
env: preserve non-UTF-8 environment variables and remove unwrap
2 parents 4401eb1 + 5d4abd8 commit ebaae2e

File tree

2 files changed

+22
-5
lines changed

2 files changed

+22
-5
lines changed

src/uu/env/src/env.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ use std::os::unix::ffi::OsStrExt;
3030
#[cfg(unix)]
3131
use std::os::unix::process::CommandExt;
3232

33-
use uucore::display::Quotable;
33+
use uucore::display::{OsWrite, Quotable};
3434
use uucore::error::{ExitCode, UError, UResult, USimpleError, UUsageError};
3535
use uucore::line_ending::LineEnding;
3636
#[cfg(unix)]
@@ -100,12 +100,16 @@ struct Options<'a> {
100100
}
101101

102102
/// print `name=value` env pairs on screen
103-
fn print_env(line_ending: LineEnding) {
103+
fn print_env(line_ending: LineEnding) -> io::Result<()> {
104104
let stdout_raw = io::stdout();
105105
let mut stdout = stdout_raw.lock();
106-
for (n, v) in env::vars() {
107-
write!(stdout, "{n}={v}{line_ending}").unwrap();
106+
for (n, v) in env::vars_os() {
107+
stdout.write_all_os(&n)?;
108+
stdout.write_all(b"=")?;
109+
stdout.write_all_os(&v)?;
110+
write!(stdout, "{line_ending}")?;
108111
}
112+
Ok(())
109113
}
110114

111115
fn parse_name_value_opt<'a>(opts: &mut Options<'a>, opt: &'a OsStr) -> UResult<bool> {
@@ -548,7 +552,7 @@ impl EnvAppData {
548552

549553
if opts.program.is_empty() {
550554
// no program provided, so just dump all env vars to stdout
551-
print_env(opts.line_ending);
555+
print_env(opts.line_ending)?;
552556
} else {
553557
return self.run_program(&opts, self.do_debug_printing);
554558
}

tests/by-util/test_env.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1862,3 +1862,16 @@ fn test_braced_variable_error_unexpected_character() {
18621862
.fails_with_code(125)
18631863
.stderr_contains("Unexpected character: '?'");
18641864
}
1865+
1866+
#[test]
1867+
#[cfg(unix)]
1868+
fn test_non_utf8_env_vars() {
1869+
use std::ffi::OsString;
1870+
use std::os::unix::ffi::OsStringExt;
1871+
1872+
let non_utf8_value = OsString::from_vec(b"hello\x80world".to_vec());
1873+
new_ucmd!()
1874+
.env("NON_UTF8_VAR", &non_utf8_value)
1875+
.succeeds()
1876+
.stdout_contains_bytes(b"NON_UTF8_VAR=hello\x80world");
1877+
}

0 commit comments

Comments
 (0)