Skip to content

Commit

Permalink
error: Handle a missing key in toml get
Browse files Browse the repository at this point in the history
See #14.

This replaces the panic with a nice clean error message.
Not yet closing the issue, though, because as discussed there
the interface we want is what `git config` does in this situation:
prints no output, but also prints nothing to stderr, and just
exits with a failure status.
  • Loading branch information
gnprice committed Dec 5, 2022
1 parent f05bec7 commit 5368fea
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
14 changes: 10 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ enum CliError {
NotArray(),
#[fail(display = "array index out of bounds")]
ArrayIndexOob(),
#[fail(display = "key not found: {}", key)]
KeyNotFound { key: String },
}

fn main() {
Expand Down Expand Up @@ -93,6 +95,7 @@ fn get(path: &PathBuf, query: &str, opts: &GetOpts) -> Result<(), Error> {
}

let item = walk_tpath(doc.as_item(), &tpath);
let item = item.ok_or(CliError::KeyNotFound { key: query.into() })?;

if opts.raw {
if let Item::Value(Value::String(s)) = item {
Expand Down Expand Up @@ -207,15 +210,18 @@ fn parse_query_cli(query: &str) -> Result<Query, CliError> {
})
}

fn walk_tpath<'a>(mut item: &'a toml_edit::Item, tpath: &[TpathSegment]) -> &'a toml_edit::Item {
fn walk_tpath<'a>(
mut item: &'a toml_edit::Item,
tpath: &[TpathSegment],
) -> Option<&'a toml_edit::Item> {
use TpathSegment::{Name, Num};
for seg in tpath {
match seg {
Name(n) => item = &item[n],
Num(n) => item = &item[n],
Name(n) => item = item.get(n)?,
Num(n) => item = item.get(n)?,
}
}
item
Some(item)
}

// TODO Can we do newtypes more cleanly than this?
Expand Down
3 changes: 2 additions & 1 deletion test/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,8 @@ tomltest_get!(get_string_raw, ["--raw", "key"], "value\n");

// TODO test `get --output-toml`

tomltest_get_err!(get_missing, ["nosuchkey"], "panicked"); // TODO should make error better
tomltest_get_err!(get_missing, ["nosuchkey"], "key not found");
tomltest_get_err!(get_missing_num, ["key[1]"], "key not found");

macro_rules! tomltest_set {
($name:ident, $args:expr, $expected:expr) => {
Expand Down

0 comments on commit 5368fea

Please sign in to comment.