Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add JSON support #117

Merged
merged 11 commits into from
Dec 13, 2023
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),

## [Unreleased]

- feat: new option --json to format output as JSON array
- fix: field formatting is now applied to field 1 even if it's the only
one present and with no delimiters around

Expand Down
11 changes: 9 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,15 @@ FLAGS:
-h, --help Print this help and exit
-m, --complement Invert fields (e.g. '2' becomes '1,3:')
-j, --(no-)join Print selected parts with delimiter inbetween
--json Print fields as a JSON array of strings

OPTIONS:
-f, --fields <bounds> Fields to keep, 1-indexed, comma separated.
Use colon to include everything in a range.
Fields can be negative (-1 is the last field).
[default 1:]

e.g. cutting on '-' the string 'a-b-c-d'
e.g. cutting the string 'a-b-c-d' on '-'
-f 1 => a
-f 1: => a-b-c-d
-f 1:3 => a-b-c
Expand All @@ -65,7 +66,7 @@ OPTIONS:

You can also format the output using {} syntax
e.g.
-f '["{1}", "{2}"]' => ["a", "b"]
-f '({1}, {2})' => (a, b)

You can escape { and } using {{ and }}.

Expand Down Expand Up @@ -131,6 +132,12 @@ cba
ac
```

```sh
# Emit JSON output
❯ echo "foo bar baz" | tuc -d ' ' --json
["foo","bar","baz"]
```

```sh
# Delimiters can be any number of characters long
❯ echo "a<sep>b<sep>c" | tuc -d '<sep>' -f 1,3
Expand Down
20 changes: 11 additions & 9 deletions doc/tuc.1
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ Invert fields (e.g.\ \[aq]2\[aq] becomes \[aq]1,3:\[aq])
.TP
.B \-j, --(no-)join
Print selected parts with delimiter in between
.TP
.B --json
Print fields as a JSON array of strings
.SH OPTIONS
.PP
\f[B]-f\f[R], \f[B]--fields\f[R] [bounds]
Expand All @@ -72,31 +75,31 @@ Print selected parts with delimiter in between
.PP
\ \ \ \ \ \ \ [default 1:]
.PP
\ \ \ \ \ \ \ e.g.\ cutting on \[aq]-\[aq] the string \[aq]a-b-c-d\[aq]
\ \ \ \ \ \ \ e.g.\ cutting the string \[aq]a-b-c-d\[aq] on \[aq]-\[aq]
.PD 0
.P
.PD
\ \ \ \ \ \ \ \ \-f 1 => a
\ \ \ \ \ \ \ \ \ \f[V]-f 1 => a\f[R]
.PD 0
.P
.PD
\ \ \ \ \ \ \ \ \-f 1: => a-b-c-d
\ \ \ \ \ \ \ \ \ \f[V]-f 1: => a-b-c-d\f[R]
.PD 0
.P
.PD
\ \ \ \ \ \ \ \ \-f 1:3 => a-b-c
\ \ \ \ \ \ \ \ \ \f[V]-f 1:3 => a-b-c\f[R]
.PD 0
.P
.PD
\ \ \ \ \ \ \ \ \-f 3,2 => cb
\ \ \ \ \ \ \ \ \ \f[V]-f 3,2 => cb\f[R]
.PD 0
.P
.PD
\ \ \ \ \ \ \ \ \-f 3,1:2 => ca-b
\ \ \ \ \ \ \ \ \ \f[V]-f 3,1:2 => ca-b\f[R]
.PD 0
.P
.PD
\ \ \ \ \ \ \ \ \-f -3:-2 => b-c
\ \ \ \ \ \ \ \ \ \f[V]-f -3:-2 => b-c\f[R]
.PP
\ \ \ \ \ \ \ To re-apply the delimiter add -j, to replace
.PD 0
Expand All @@ -112,8 +115,7 @@ Print selected parts with delimiter in between
.PD 0
.P
.PD
\ \ \ \ \ \ \ \ \ -f \[aq][\[dq]{1}\[dq], \[dq]{2}\[dq]]\[aq] =>
[\[dq]a\[dq], \[dq]b\[dq]]
\ \ \ \ \ \ \ \ \ \f[V]-f \[aq]({1}, {2})\[aq] => (a, b)\f[R]
.PP
\ \ \ \ \ \ \ You can escape { and } using {{ and }}.
.PP
Expand Down
6 changes: 4 additions & 2 deletions doc/tuc.1.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ FLAGS
-j, \--(no-)join
: Print selected parts with delimiter in between

\--json
: Print fields as a JSON array of strings

OPTIONS
=======
Expand All @@ -57,7 +59,7 @@ OPTIONS

| [default 1:]

| e.g. cutting on \'-\' the string \'a-b-c-d\'
| e.g. cutting the string \'a-b-c-d\' on \'-\'
| `-f 1 => a`
| `-f 1: => a-b-c-d`
| `-f 1:3 => a-b-c`
Expand All @@ -70,7 +72,7 @@ OPTIONS

| You can also format the output using {} syntax
| e.g.
| -f \'[\"{1}\", \"{2}\"]\' => [\"a\", \"b\"]
| `-f '({1}, {2})' => (a, b)`

| You can escape { and } using {{ and }}.

Expand Down
94 changes: 71 additions & 23 deletions src/bin/tuc.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use anyhow::Result;
use std::io::Write;
use std::str::FromStr;
use tuc::bounds::{BoundsType, UserBoundsList};
use tuc::bounds::{BoundOrFiller, BoundsType, UserBoundsList};
use tuc::cut_bytes::read_and_cut_bytes;
use tuc::cut_lines::read_and_cut_lines;
use tuc::cut_str::read_and_cut_str;
Expand Down Expand Up @@ -33,27 +33,28 @@ FLAGS:
-h, --help Print this help and exit
-m, --complement Invert fields (e.g. '2' becomes '1,3:')
-j, --(no-)join Print selected parts with delimiter in between
--json Print fields as a JSON array of strings

OPTIONS:
-f, --fields <bounds> Fields to keep, 1-indexed, comma separated.
Use colon to include everything in a range.
Fields can be negative (-1 is the last field).
[default 1:]

e.g. cutting on '-' the string 'a-b-c-d'
-f 1 => a
-f 1: => a-b-c-d
-f 1:3 => a-b-c
-f 3,2 => cb
-f 3,1:2 => ca-b
-f -3:-2 => b-c
e.g. cutting the string 'a-b-c-d' on '-'
-f 1 => a
-f 1: => a-b-c-d
-f 1:3 => a-b-c
-f 3,2 => cb
-f 3,1:2 => ca-b
-f -3:-2 => b-c

To re-apply the delimiter add -j, to replace
it add -r (followed by the new delimiter).

You can also format the output using {} syntax
e.g.
-f '["{1}", "{2}"]' => ["a", "b"]
-f '({1}, {2})' => (a, b)

You can escape { and } using {{ and }}.

Expand All @@ -64,7 +65,8 @@ OPTIONS:
-d, --delimiter <delimiter> Delimiter used by --fields to cut the text
[default: \t]
-e, --regex <some regex> Use a regular expression as delimiter
-r, --replace-delimiter <new> Replace the delimiter with the provided text
-r, --replace-delimiter <new> Replace the delimiter with the provided text.
Implies --join
-t, --trim <type> Trim the delimiter (greedy). Valid values are
(l|L)eft, (r|R)ight, (b|B)oth

Expand Down Expand Up @@ -112,7 +114,7 @@ fn parse_args() -> Result<Opt, pico_args::Error> {
if bounds_type == BoundsType::Fields
&& (maybe_fields.is_none() || maybe_fields.as_ref().unwrap().0.is_empty())
{
eprintln!("tuc: invariant error. At least 1 field bound is expected with --fields");
eprintln!("tuc: invariant error. At this point we expected to find at least 1 field bound");
std::process::exit(1);
}

Expand All @@ -125,24 +127,57 @@ fn parse_args() -> Result<Opt, pico_args::Error> {
};

let greedy_delimiter = pargs.contains(["-g", "--greedy-delimiter"]);
let replace_delimiter = pargs.opt_value_from_str(["-r", "--replace-delimiter"])?;
let mut replace_delimiter = pargs.opt_value_from_str(["-r", "--replace-delimiter"])?;

let has_json = pargs.contains("--json");
let has_join = pargs.contains(["-j", "--join"]);
let has_no_join = pargs.contains("--no-join");

if has_join && has_no_join {
eprintln!("tuc: runtime error. You can't pass both --join and --no-join");
eprintln!(
"tuc: runtime error. It's not possible to use --join and --no-join simultaneously"
);
std::process::exit(1);
}

if replace_delimiter.is_some() && has_no_join {
eprintln!("tuc: runtime error. Since --replace implies --join, you can't pass --no-join");
if has_json && has_no_join {
eprintln!("tuc: runtime error. Using both --json and --no-join is not permitted");
std::process::exit(1);
}

if replace_delimiter.is_some() {
if has_no_join {
eprintln!("tuc: runtime error. You can't pass --no-join when using --replace, which implies --join");
std::process::exit(1);
} else if has_json {
eprintln!("tuc: runtime error. The use of --replace with --json is not supported");
std::process::exit(1);
}
}

if bounds_type == BoundsType::Characters && has_no_join {
eprintln!(
"tuc: runtime error. Since --characters implies --join, you can't pass --no-join"
);
std::process::exit(1);
}

if has_json {
replace_delimiter = Some(",".to_owned());
}

let join = has_join
|| has_json
|| replace_delimiter.is_some()
|| (bounds_type == BoundsType::Lines && !has_no_join);
|| (bounds_type == BoundsType::Lines && !has_no_join)
|| (bounds_type == BoundsType::Characters);

if has_json && bounds_type != BoundsType::Characters && bounds_type != BoundsType::Fields {
eprintln!(
"tuc: runtime error. --json support is available only for --fields and --characters"
);
std::process::exit(1);
}

#[cfg(not(feature = "regex"))]
let regex_bag = None;
Expand All @@ -161,8 +196,24 @@ fn parse_args() -> Result<Opt, pico_args::Error> {
}),
});

if regex_bag.is_some() && !cfg!(feature = "regex") {
eprintln!("tuc: runtime error. This version of tuc was compiled without regex support");
if regex_bag.is_some() && cfg!(not(feature = "regex")) {
eprintln!("tuc: invariant error. There should not be any regex when compiled without regex support");
std::process::exit(1);
}

let bounds = maybe_fields
.or(maybe_characters)
.or(maybe_bytes)
.or(maybe_lines)
.unwrap();

if has_json
&& bounds
.0
.iter()
.any(|s| matches!(s, BoundOrFiller::Filler(_)))
{
eprintln!("tuc: runtime error. Cannot format fields when using --json");
std::process::exit(1);
}

Expand All @@ -178,13 +229,10 @@ fn parse_args() -> Result<Opt, pico_args::Error> {
EOL::Newline
},
join,
json: has_json,
delimiter,
bounds_type,
bounds: maybe_fields
.or(maybe_characters)
.or(maybe_bytes)
.or(maybe_lines)
.unwrap(),
bounds,
replace_delimiter,
trim: pargs.opt_value_from_str(["-t", "--trim"])?,
regex_bag,
Expand Down
Loading
Loading