foil/src/main.rs

86 lines
2.2 KiB
Rust
Raw Normal View History

2019-05-25 22:04:54 -04:00
use docopt::Docopt;
2019-05-25 23:14:00 -04:00
use log::debug;
use rand::rngs::OsRng;
use rand::seq::IteratorRandom;
use rand::seq::SliceRandom;
2019-05-25 22:04:54 -04:00
use serde::Deserialize;
2019-05-25 23:14:00 -04:00
use std::iter::FromIterator;
2019-05-25 22:04:54 -04:00
static USAGE: &'static str = "
foil
Usage:
foil set [--db=<db>]
foil get [--db=<db>]
foil list [--db=<db>]
foil generate <spec>
foil (-h | --help)
Options:
--db=<db> The path to the sqlite database [default: db.sqlite3].
-h --help Show this screen.
--version Show version.
";
#[derive(Debug, Deserialize)]
struct Args {
cmd_set: bool,
cmd_get: bool,
cmd_list: bool,
cmd_generate: bool,
flag_db: Option<String>,
arg_spec: Option<String>,
}
2019-05-25 23:14:00 -04:00
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);
}
2019-05-25 21:45:00 -04:00
fn main() {
2019-05-25 22:17:57 -04:00
pretty_env_logger::init();
2019-05-25 22:04:54 -04:00
let args: Args = Docopt::new(USAGE)
.and_then(|dopt| dopt.deserialize())
.unwrap_or_else(|e| e.exit());
2019-05-25 22:17:57 -04:00
debug!("{:?}", args);
2019-05-25 22:04:54 -04:00
2019-05-25 23:14:00 -04:00
if args.cmd_generate {
generate(&args.arg_spec.unwrap());
return;
}
2019-05-25 21:45:00 -04:00
}