Skip to content

Commit

Permalink
fix: Do not allow invalid keys to be set (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
schpet authored Sep 24, 2024
1 parent 50f6369 commit dfa260b
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 14 deletions.
28 changes: 17 additions & 11 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,17 +127,23 @@ pub fn parse_stdin_with_reader<R: Read>(reader: &mut R) -> HashMap<String, Strin
parse_env_content(&buffer)
}

pub fn parse_args(vars: &[String]) -> HashMap<String, String> {
vars.iter()
.filter_map(|arg| {
let parts: Vec<&str> = arg.splitn(2, '=').collect();
if parts.len() == 2 {
Some((parts[0].to_string(), parts[1].to_string()))
} else {
None
}
})
.collect()
pub fn parse_args(vars: &[String]) -> Result<HashMap<String, String>, String> {
vars.iter().try_fold(HashMap::new(), |mut acc, arg| {
let parts: Vec<&str> = arg.splitn(2, '=').collect();
if parts.len() == 2 {
let key = parser::key_parser()
.parse(parts[0])
.map_err(|_| format!("Invalid key format in argument: {}", arg.bold().red()))?;
acc.insert(key, parts[1].to_string());
Ok(acc)
} else {
Err(format!(
"Invalid argument format {}. Expected format is {}",
arg.bold().red(),
"KEY=value".bold()
))
}
})
}

pub fn parse_env_content(content: &str) -> HashMap<String, String> {
Expand Down
8 changes: 7 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,13 @@ fn main() {
if !atty::is(Stream::Stdin) {
parse_stdin()
} else {
parse_args(&cli.vars)
match parse_args(&cli.vars) {
Ok(vars) => vars,
Err(e) => {
eprintln!("Error parsing arguments: {}", e);
process::exit(1);
}
}
}
} else {
HashMap::new()
Expand Down
9 changes: 7 additions & 2 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,20 @@ pub enum Line {
},
}

// Parser for keys
pub fn key_parser() -> impl Parser<char, String, Error = Simple<char>> + Clone {
text::ident().padded()
}

pub fn parser() -> impl Parser<char, Vec<Line>, Error = Simple<char>> + Clone {
// Parser for comments
let comment = just('#')
.ignore_then(take_until(text::newline().or(end())))
.map(|(chars, _)| chars.into_iter().collect::<String>())
.map(Line::Comment);

// Parser for keys
let key = text::ident().padded();

let key = key_parser();

// Parser for single-quoted values
let single_quoted_value = just('\'')
Expand Down

0 comments on commit dfa260b

Please sign in to comment.