diff --git a/src/main.rs b/src/main.rs index 4f5f60b..e934136 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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 + } +} \ No newline at end of file