Strip trailing newline

This commit is contained in:
D. Scott Boggs 2024-05-12 08:23:54 -04:00
parent 171124050c
commit 873ea52183

View file

@ -11,26 +11,7 @@ use std::{
};
fn main() {
let mut child_env = vec![];
for (key, value) in env::vars_os() {
let key_bytes: Vec<_> = key.as_bytes().into();
if key_bytes.ends_with(b"_FILE") && !value.is_empty() {
match fs::read(&value) {
Ok(content) => {
let key = OsString::from_vec(key_bytes[0..key_bytes.len() - 5].to_owned());
child_env.push((key, OsString::from_vec(content)));
}
Err(error) => {
panic!(
"failed to read contents of {value:?} (specified by ${}): {error:?}",
key.to_string_lossy()
)
}
}
} else {
child_env.push((key, value))
}
}
let child_env = build_env();
let mut args = env::args().skip(1);
if let Some(cmd) = args.next() {
let collected: Vec<_> = args.collect();
@ -45,3 +26,40 @@ fn main() {
panic!("no command given");
}
}
fn build_env() -> Vec<(OsString, OsString)> {
let mut child_env = vec![];
for (key, value) in env::vars_os() {
let key_bytes: Vec<_> = key.as_bytes().into();
if key_bytes.ends_with(b"_FILE") && !value.is_empty() {
match fs::read(&value) {
Ok(content) => {
let key = OsString::from_vec(key_bytes[0..key_bytes.len() - 5].to_owned());
child_env.push((key, OsString::from_vec(strip_trailing_newline(&content).to_owned())));
}
Err(error) => {
panic!(
"failed to read contents of {value:?} (specified by ${}): {error:?}",
key.to_string_lossy()
)
}
}
} else {
child_env.push((key, value))
}
}
child_env
}
fn strip_trailing_newline(content: &[u8]) -> &[u8] {
let len = content.len();
if content[len - 1] == b'\n' {
if content[len - 2] == b'\r' {
&content[0..len - 2]
} else {
&content[0..len - 1]
}
} else {
content
}
}