Skip to content

Commit

Permalink
get: Add --raw / -r option
Browse files Browse the repository at this point in the history
Fixes: #19
  • Loading branch information
gnprice committed Dec 4, 2022
1 parent c205f5e commit 3f91f13
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 6 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Unreleased

* New option `toml get -r` / `--raw`.


## 0.2.1

Expand Down
14 changes: 9 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,21 @@ segments*, each of which is either:
* `.KEY`, to index into a table or inline-table, or
* `[INDEX]`, to index into an array-of-tables or array.

```
$ toml get Cargo.toml dependencies.serde
"1.0"
```

Data is emitted by default as JSON:

```
$ toml get Cargo.toml bin[0]
{"name":"toml","path":"src/main.rs"}
```

When the data is a string, the `--raw`/`-r` option prints it directly,
for convenience in contexts like a shell script:

```
$ toml get Cargo.toml dependencies.serde --raw
1.0
```

If you need a more complex query, consider a tool like `jq`, with
`toml` simply transforming the file to JSON:

Expand Down Expand Up @@ -118,6 +121,7 @@ USAGE:
FLAGS:
-h, --help Prints help information
--output-toml Print as a TOML fragment (default: print as JSON)
-r, --raw Print strings raw, not as JSON
-V, --version Prints version information
ARGS:
Expand Down
14 changes: 13 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ struct GetOpts {
/// Print as a TOML fragment (default: print as JSON)
#[structopt(long)]
output_toml: bool,

/// Print strings raw, not as JSON
// (No effect when the item isn't a string, just like `jq -r`.)
#[structopt(long, short)]
raw: bool,
}

#[derive(Debug, Fail)]
Expand Down Expand Up @@ -85,7 +90,14 @@ fn get(path: PathBuf, query: &str, opts: GetOpts) -> Result<(), Error> {
}

let item = walk_tpath(doc.as_item(), &tpath);
// TODO: support shell-friendly output like `jq -r`

if opts.raw {
if let Item::Value(Value::String(s)) = item {
println!("{}", s.value());
return Ok(());
}
}

println!("{}", serde_json::to_string(&JsonItem(item))?);
Ok(())
}
Expand Down

0 comments on commit 3f91f13

Please sign in to comment.