From 5248d1de4656d4b747cf3cf5adce62b0f59b0874 Mon Sep 17 00:00:00 2001 From: notohh Date: Sat, 1 Jun 2024 14:26:46 -0400 Subject: [PATCH] add modules & file writing --- src/args.rs | 11 +++++++++++ src/main.rs | 43 ++++++++++++++++++++----------------------- src/randomstring.rs | 19 +++++++++++++++++++ 3 files changed, 50 insertions(+), 23 deletions(-) create mode 100644 src/args.rs create mode 100644 src/randomstring.rs diff --git a/src/args.rs b/src/args.rs new file mode 100644 index 0000000..beab0bd --- /dev/null +++ b/src/args.rs @@ -0,0 +1,11 @@ +use clap::Parser; + +#[derive(Parser, Debug)] +pub struct Args { + #[arg(short)] + pub(crate) length: usize, + #[arg(short)] + pub write_to_file: bool, + #[arg(short, default_value_t = String::from("generated_pwd.txt"))] + pub file: String, +} diff --git a/src/main.rs b/src/main.rs index 96e94cc..b1fdfd5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,30 +1,27 @@ +use args::Args; use clap::Parser; -use rand::{distributions::Alphanumeric, Rng}; +use core::panic; +use randomstring::RandomString; +use std::fs::File; +use std::io::{Error, Write}; -#[derive(Parser, Debug)] -struct Args { - #[arg(short)] - length: usize, -} +mod args; +mod randomstring; -#[derive(Debug)] -struct RandomString; - -impl RandomString { - fn generate_string(&self) -> String { - let args = Args::parse(); - let s: String = rand::thread_rng() - .sample_iter(&Alphanumeric) - .take(args.length) - .map(char::from) - .collect(); - s - } -} - -fn main() { +fn main() -> Result<(), Error> { + let args = Args::parse(); let random_string = RandomString; let string_output = random_string.generate_string(); - println!("{}", string_output); + if args.write_to_file { + let f = &mut File::create(args.file); + let file = match f { + Ok(file) => file.write_all(string_output.as_bytes()), + Err(e) => panic!("cannot create file: {:?}", e), + }; + } else { + println!("{}", string_output); + }; + + Ok(()) } diff --git a/src/randomstring.rs b/src/randomstring.rs new file mode 100644 index 0000000..97bc829 --- /dev/null +++ b/src/randomstring.rs @@ -0,0 +1,19 @@ +use clap::Parser; +use rand::{distributions::Alphanumeric, Rng}; + +use crate::Args; + +#[derive(Debug)] +pub struct RandomString; + +impl RandomString { + pub fn generate_string(&self) -> String { + let args = Args::parse(); + let s: String = rand::thread_rng() + .sample_iter(&Alphanumeric) + .take(args.length) + .map(char::from) + .collect(); + s + } +}