Compare commits

...

2 commits
v0.0.1 ... main

Author SHA1 Message Date
D. Scott Boggs 3366828bbe update Cargo.toml 2024-05-12 08:26:08 -04:00
D. Scott Boggs 873ea52183 Strip trailing newline 2024-05-12 08:23:54 -04:00
3 changed files with 42 additions and 22 deletions

2
Cargo.lock generated
View file

@ -4,4 +4,4 @@ version = 3
[[package]]
name = "env_or_file"
version = "0.1.0"
version = "0.0.2"

View file

@ -1,7 +1,9 @@
[package]
name = "env_or_file"
version = "0.1.0"
version = "0.0.2"
edition = "2021"
license = "MPL-2.0"
author = "D. Scott Boggs"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

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
}
}