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

1.2: Feature Request: Sample-Program which reads and writes to stdin resp. stdout #36

Open
michelk opened this issue Jun 11, 2021 · 1 comment

Comments

@michelk
Copy link

michelk commented Jun 11, 2021

It would be great to have an example cli-program with usage:

sample-program --output
if --output is missing, output will be written to stdout; if input-file is missing, input is read from stdin.

Thanks.

@michelk
Copy link
Author

michelk commented Jun 11, 2021

I came up with the following. But the pattern-match seems to be a bit tedious; isn't there something easier?

Do you want me, to make a PR?

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(())
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant