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 an example with clapv3 (beta) with optional stdin/stdout #37

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 115 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ path = "src/tutorial/cli-args-struct.rs"
name = "cli-args-structopt"
path = "src/tutorial/cli-args-structopt.rs"

[[bin]]
name = "cli-args-clap3-stdin-stdout"
path = "src/tutorial/cli-args-clap3-stdin-stdout.rs"

[[bin]]
name = "impl-draft-shortcut"
path = "src/tutorial/impl-draft-shortcut.rs"
Expand Down Expand Up @@ -62,6 +66,8 @@ members = [
]

[dependencies]
clap = "3.0.0-beta.2"
csv = "1.1.6"
structopt = "0.3.21"
failure = "0.1.3"
exitfailure = "0.5.1"
Expand Down
58 changes: 58 additions & 0 deletions src/tutorial/cli-args-clap3-stdin-stdout.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
use clap::{AppSettings, Clap};
use std::error::Error;
use std::fs::File;
use std::io;
use std::io::{Read, Write};
use std::process;

/// A sample-program
///
/// The program is a show-case how to read data either from file or stdin and write data either to
/// file or stdout
#[derive(Clap)]
#[clap(version = "0.1")]
#[clap(setting = AppSettings::ColoredHelp)]
struct Opts {
/// Optional output file; default stdout
#[clap(short, long)]
output: Option<String>,
/// Optional input file; default stdin
input: Option<String>,
}

fn main() {
let opts: Opts = Opts::parse();
let exit = match (opts.input, opts.output) {
(None, None) => run(io::stdin(), io::stdout()),
(None, Some(f)) => run(io::stdin(), open_output(f)),
(Some(f), None) => run(open_input(f), io::stdout()),
(Some(fin), Some(fout)) => run(open_input(fin), open_output(fout)),
};

if let Err(err) = exit {
println!("{}", err);
process::exit(1);
}
}

fn open_input(f: String) -> File {
File::open(f).expect("Could not open input file")
}
fn open_output(f: String) -> File {
File::create(f).expect("Could not open output file")
}

fn run(input: impl Read, output: impl Write) -> Result<(), Box<dyn Error>> {
let mut rdr = csv::Reader::from_reader(input);
let mut wtr = csv::Writer::from_writer(output);

wtr.write_record(rdr.headers()?)?;

for result in rdr.records() {
let record = result?;
wtr.write_record(&record)?;
}

wtr.flush()?;
Ok(())
}
56 changes: 56 additions & 0 deletions src/tutorial/cli-args.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,3 +208,59 @@ That just means there is no error and our program ended.
Make this program output its arguments!

</aside>


## Parsing CLI arguments with 'Clap v3 beta' and dealing with stdin and stdout
Similar to StructOpt, it is also possible with Clap v3 (currently in beta) to
define the command-line options as a `struct` and derive the rest.

The following code also illustrates how to read input either from file, if
provided as a command-line argument, or from `stdin` otherwise. Same applies
to output: If the output-file not given as command-line argument, the output is
written per default to `stdout`.

```rust,ignore
{{#include cli-args-clap3-stdin-stdout.rs}}
```

Now the program could be used in four different ways


```console
cargo run --bin cli-args-clap3-stdin-stdout -- < input.csv > output.csv
cargo run --bin cli-args-clap3-stdin-stdout -- input.csv > output.csv
cargo run --bin cli-args-clap3-stdin-stdout -- --output output.csv < input.csv
cargo run --bin cli-args-clap3-stdin-stdout -- --output output.csv input.csv
```

The help message looks like below:

```console
cargo run --bin cli-args-clap3-stdin-stdout -- --help
CLAiR 0.1
A sample-program

The program is a show-case how to read data either from file or stdin and write data either to file
or stdout

USAGE:
cli-args-clap3-stdin-stdout [OPTIONS] [input]

ARGS:
<input>
Optional input file; default stdin

FLAGS:
-h, --help
Prints help information

-V, --version
Prints version information


OPTIONS:
-o, --output <output>
Optional output file; default stdout


```