aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorMatthew Hall <hallmatthew314@gmail.com>2024-03-28 22:24:04 +1300
committerMatthew Hall <hallmatthew314@gmail.com>2024-03-28 22:24:04 +1300
commit19d78ca2f8c5d37ba0c8bac76e30714a65c9f7b2 (patch)
tree476e51332d42f6cf6116365c0f64cffd4c9939e9 /src
parentcda07006720dc53367d0a552aa2c77796825f82d (diff)
Basic implementation of CLI arguments
Diffstat (limited to 'src')
-rw-r--r--src/args.rs51
-rw-r--r--src/main.rs16
2 files changed, 62 insertions, 5 deletions
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<Args> {
+ let arg_vec: Vec<String> = 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<String> = 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::<u32>().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<T> = Result<T, Error>;
#[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)
}
}