Skip to content

Commit

Permalink
Merge pull request #3 from CleanCut/clap-derive
Browse files Browse the repository at this point in the history
Clap derive
  • Loading branch information
CleanCut authored Sep 15, 2022
2 parents 125b4a3 + 2784535 commit 05495d0
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 46 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ license = "MIT OR Apache-2.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
clap = "3.2.21"
clap = { version = "3.2.21", features = ["derive"] }
66 changes: 21 additions & 45 deletions src/opts.rs
Original file line number Diff line number Diff line change
@@ -1,57 +1,33 @@
use clap::{App, Arg};
use clap::Parser;

#[derive(Debug)]
#[derive(Debug, clap::Parser)]
pub struct Opts {
#[clap(help = "Read from a file instead of stdin")]
pub filename: Option<String>,
#[clap(
help = "Number of first lines of a file to display",
short = 'H',
long = "head",
default_value_t = 10
)]
pub head: usize,
#[clap(
help = "Number of last lines of a file to display",
short = 'T',
long = "tail",
default_value_t = 10
)]
pub tail: usize,
#[clap(
help = "Wait for additional data to be appended to a file. Ignored if standard input is a pipe.",
short = 'f',
long = "follow"
)]
pub follow: bool,
}

impl Opts {
pub fn parse_args() -> Self {
let matches = App::new("headtail")
.arg(Arg::with_name("filename").help("Read from a file instead of stdin"))
.arg(
Arg::with_name("head")
.short('H')
.long("head")
.takes_value(true)
.default_value("10")
.help("Number of first lines of a file to display"),
)
.arg(
Arg::with_name("tail")
.short('T')
.long("tail")
.takes_value(true)
.default_value("10")
.help("Number of last lines of a file to display"),
)
.arg(
Arg::with_name("follow")
.short('f')
.long("follow")
.help("Wait for additional data to be appended to a file. Ignored if standard input is a pipe."),
)
.get_matches();
let filename = matches.value_of("filename").map(|f| f.to_string());
let head = matches
.value_of("head")
.unwrap()
.parse::<usize>()
.expect("could not parse number for head"); // TODO: more graceful error handling
let tail = matches
.value_of("tail")
.unwrap()
.parse::<usize>()
.expect("could not parse number for tail"); // TODO: more graceful error handling
let follow = matches.is_present("follow");
Self {
filename,
head,
tail,
follow,
}
Self::parse()
}
}

0 comments on commit 05495d0

Please sign in to comment.