From 19d78ca2f8c5d37ba0c8bac76e30714a65c9f7b2 Mon Sep 17 00:00:00 2001 From: Matthew Hall Date: Thu, 28 Mar 2024 22:24:04 +1300 Subject: Basic implementation of CLI arguments --- src/args.rs | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 16 +++++++++++----- 2 files changed, 62 insertions(+), 5 deletions(-) create mode 100644 src/args.rs (limited to 'src') diff --git a/src/args.rs b/src/args.rs new file mode 100644 index 0000000..6753664 --- /dev/null +++ b/src/args.rs @@ -0,0 +1,51 @@ +use std::env; + +pub struct Args { + pub directory: String, + pub n_sentences: u32, + pub unique: bool, +} + +impl Args { + pub fn parse() -> Option { + let arg_vec: Vec = env::args().collect(); + let mut i = 1; //skip first arg (execution path) + + let mut n_sentences = 1; + let mut unique = false; + let mut opt_directory: Option = None; + + while i < arg_vec.len() { + match arg_vec[i].as_str() { + "-n" | "--sentences" => { + if i + 1 < arg_vec.len() { + n_sentences = arg_vec[i+1].parse::().ok()?; + } else { + return None; + } + i += 2; + }, + "--unique" => { + unique = true; + i += 1; + }, + other => { + opt_directory = match opt_directory { + Some(_) => { return None; }, + None => Some(other.to_string()), + }; + i += 1; + }, + } + } + + let directory = opt_directory?; + + Some(Args { + directory, + n_sentences, + unique, + }) + } +} + diff --git a/src/main.rs b/src/main.rs index 4f299d4..82e568e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,11 +6,16 @@ use std::io; use std::path::PathBuf; use std::process; +pub mod args; + + use rand::{thread_rng, seq::{SliceRandom, IteratorRandom}}; use clap::Parser; +use crate::args::Args; #[derive(Debug)] enum Error { + BadArguments, NoSentences, MultipleSentences, BadTemplate(String), @@ -27,6 +32,8 @@ enum Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { + Error::BadArguments => + write!(f, "error while parsing arguments"), Error::NoSentences => write!(f, "no sentences.txt file found"), Error::MultipleSentences => @@ -64,7 +71,7 @@ type ProgResult = Result; #[derive(Parser, Debug)] #[command(name = "spout")] #[command(about = "Generates nonsense", long_about = None)] -struct Args { +struct OldArgs { /// Path to data directory directory: String, @@ -326,7 +333,8 @@ fn crash(e: Error) -> ! { process::exit(1); } -fn sub_main(args: Args) -> ProgResult<()> { +fn sub_main() -> ProgResult<()> { + let args = Args::parse().ok_or(Error::BadArguments)?; let (mut sentences, mut categories) = read_files(&args.directory, args.unique)?; for _i in 0..args.n_sentences { @@ -339,9 +347,7 @@ fn sub_main(args: Args) -> ProgResult<()> { } fn main() { - let args = Args::parse(); - - if let Err(e) = sub_main(args) { + if let Err(e) = sub_main() { crash(e) } } -- cgit v1.2.1