Compare commits

..

No commits in common. "main" and "v0.0.1" have entirely different histories.
main ... v0.0.1

3 changed files with 22 additions and 42 deletions

2
Cargo.lock generated
View file

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

View file

@ -1,9 +1,7 @@
[package]
name = "env_or_file"
version = "0.0.2"
version = "0.1.0"
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,7 +11,26 @@ use std::{
};
fn main() {
let child_env = build_env();
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 mut args = env::args().skip(1);
if let Some(cmd) = args.next() {
let collected: Vec<_> = args.collect();
@ -26,40 +45,3 @@ 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
}
}