From c6ac35a6af7b9c00ba9341ecfff496da86bfab76 Mon Sep 17 00:00:00 2001 From: Teddy Wing Date: Sun, 2 Aug 2020 09:48:07 +0200 Subject: Add `-h` argument Print usage on `-h` and `--help`. Store the usage brief on `Config` in order to be able to print it from multiple places. --- src/bin/git-sugpatch.rs | 10 +++++----- src/config.rs | 20 +++++++++++++++----- src/suggestion.rs | 2 +- 3 files changed, 21 insertions(+), 11 deletions(-) diff --git a/src/bin/git-sugpatch.rs b/src/bin/git-sugpatch.rs index c8fc0a8..10499e9 100644 --- a/src/bin/git-sugpatch.rs +++ b/src/bin/git-sugpatch.rs @@ -10,7 +10,10 @@ use github_suggestion_cli::config::Config; fn main() { let args: Vec<_> = env::args().collect(); - let config = match Config::get(&args) { + let config = match Config::get( + &args, + "usage: git sugpatch [options] ...", + ) { Ok(c) => c, Err(e) => { gseprintln!(e); @@ -20,10 +23,7 @@ fn main() { }; if config.suggestions.is_empty() { - print!( - "{}", - config.usage("usage: git sugpatch [options] ..."), - ); + config.print_usage(); process::exit(exitcode::USAGE); } diff --git a/src/config.rs b/src/config.rs index 4402014..476b597 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,4 +1,5 @@ use std::env; +use std::process; use getopts::{self, Options}; use git2::{self, Repository}; @@ -27,23 +28,31 @@ pub enum Error { Git(#[from] git2::Error), } -pub struct Config { +pub struct Config<'a> { pub github_token: String, pub o_r: Result, pub suggestions: Vec, opts: Options, + usage_brief: &'a str, } -impl Config { - pub fn get(args: &[String]) -> Result { +impl<'a> Config<'a> { + pub fn get(args: &[String], usage_brief: &'a str) -> Result { let mut opts = Options::new(); opts.optopt("", "github-token", "", "TOKEN"); opts.optopt("", "remote", "", "REMOTE"); + opts.optflag("h", "help", "print this help menu"); let opt_matches = opts.parse(&args[1..])?; + if opt_matches.opt_present("h") { + print!("{}", opts.usage(&usage_brief)); + + process::exit(exitcode::USAGE); + } + let git_config = Repository::open(".")?.config()?; let o_r = OwnerRepo::from_remote( @@ -56,11 +65,12 @@ impl Config { suggestions: opt_matches.free, opts: opts, + usage_brief, }) } - pub fn usage(&self, brief: &str) -> String { - self.opts.usage(&brief) + pub fn print_usage(&self) { + print!("{}", self.opts.usage(&self.usage_brief)) } fn github_token( diff --git a/src/suggestion.rs b/src/suggestion.rs index fc22a7c..f1684e0 100644 --- a/src/suggestion.rs +++ b/src/suggestion.rs @@ -9,7 +9,7 @@ use crate::arg::is_suggestion_id; use crate::config::Config; -pub fn for_suggestion(config: &Config, f: F) +pub fn for_suggestion(config: &Config<'_>, f: F) where F: Fn(&Suggestion) { for suggestion_arg in &config.suggestions { -- cgit v1.2.3