move password generation off to its own file

This commit is contained in:
Tom Alexander 2019-05-27 19:24:36 -04:00
parent 523a3f6ec4
commit 7022351ee7
2 changed files with 45 additions and 44 deletions

43
src/generate.rs Normal file
View File

@ -0,0 +1,43 @@
use rand::rngs::OsRng;
use rand::seq::IteratorRandom;
use rand::seq::SliceRandom;
use std::iter::FromIterator;
pub fn generate(spec: &str) {
let (len, rest) = {
let mut separated = spec.splitn(2, ",");
let len = separated.next().unwrap();
let rest = separated.next().unwrap();
(len, rest)
};
let mut rnd = OsRng::new().unwrap();
let mut password_vec: Vec<char> = rest
.chars()
.cycle()
.map(|c| match c {
'a' => "abcdefghijklmnopqrstuvwxyz"
.chars()
.choose(&mut rnd)
.expect("Could not get random element"),
'A' => "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
.chars()
.choose(&mut rnd)
.expect("Could not get random element"),
'1' => "1234567890"
.chars()
.choose(&mut rnd)
.expect("Could not get random element"),
'.' => ".,/?-=#%^"
.chars()
.choose(&mut rnd)
.expect("Could not get random element"),
_ => panic!("Unknown character spec: {}", c),
})
.take(len.parse().unwrap())
.collect();
password_vec.shuffle(&mut rnd);
let shuffled: String = String::from_iter(password_vec.into_iter());
println!("{}", shuffled);
}

View File

@ -1,13 +1,10 @@
use docopt::Docopt;
use log::debug;
use rand::rngs::OsRng;
use rand::seq::IteratorRandom;
use rand::seq::SliceRandom;
use serde::Deserialize;
use std::error::Error;
use std::iter::FromIterator;
pub mod db;
pub mod generate;
static USAGE: &'static str = "
foil
@ -35,45 +32,6 @@ struct Args {
arg_spec: Option<String>,
}
fn generate(spec: &str) {
let (len, rest) = {
let mut separated = spec.splitn(2, ",");
let len = separated.next().unwrap();
let rest = separated.next().unwrap();
(len, rest)
};
let mut rnd = OsRng::new().unwrap();
let mut password_vec: Vec<char> = rest
.chars()
.cycle()
.map(|c| match c {
'a' => "abcdefghijklmnopqrstuvwxyz"
.chars()
.choose(&mut rnd)
.expect("Could not get random element"),
'A' => "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
.chars()
.choose(&mut rnd)
.expect("Could not get random element"),
'1' => "1234567890"
.chars()
.choose(&mut rnd)
.expect("Could not get random element"),
'.' => ".,/?-=#%^"
.chars()
.choose(&mut rnd)
.expect("Could not get random element"),
_ => panic!("Unknown character spec: {}", c),
})
.take(len.parse().unwrap())
.collect();
password_vec.shuffle(&mut rnd);
let shuffled: String = String::from_iter(password_vec.into_iter());
println!("{}", shuffled);
}
fn main() -> Result<(), Box<dyn Error>> {
pretty_env_logger::init();
let args: Args = Docopt::new(USAGE)
@ -82,7 +40,7 @@ fn main() -> Result<(), Box<dyn Error>> {
debug!("{:?}", args);
if args.cmd_generate {
generate(&args.arg_spec.unwrap());
generate::generate(&args.arg_spec.unwrap());
return Ok(());
}