sts10 / phraze

Generate random passphrases

Home Page:https://sts10.github.io/2023/10/24/phraze-passphrase-generator.html

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Clean up main function

sts10 opened this issue · comments

As noted in #14, I don't like how the main function looks right now. Specifically, how I need to have one variable for the built-in list and another for the user-submitted "custom" list.

phraze/src/main.rs

Lines 104 to 161 in d530eba

// We need two different variables here, one for a user-inputted list and another for
// the built-in list (whether chosen or the default). This is because we use different
// variable types for each case.
let (custom_list, built_in_list) = match opt.custom_list_file_path {
Some(custom_list_file_path) => (Some(read_in_custom_list(&custom_list_file_path)?), None),
None => (None, Some(fetch_list(opt.list_choice))),
};
// If a "custom_list" was given by the user, we're going to use that list.
// Otherwise we use the built-in list (a default list if the user didn't choose one).
// To get the length of the list we're going to use, we need to check if a
// custom_list was given.
let list_length = match custom_list {
Some(ref custom_list) => custom_list.len(),
None => built_in_list.unwrap().len(), // pretty sure we're safe to unwrap here...
};
// Since user can define a minimum entropy, we might have to do a little math to
// figure out how many words we need to include in this passphrase.
let number_of_words_to_put_in_passphrase = calculate_number_words_needed(
opt.number_of_words,
opt.minimum_entropy,
opt.strength_count,
list_length,
);
// If user enabled verbose option
if opt.verbose {
// print entropy information, but use eprint to only print it
// to the terminal
print_entropy(
number_of_words_to_put_in_passphrase,
list_length,
opt.n_passphrases,
);
}
// Now we can (finally) generate and print some number of passphrases
for _ in 0..opt.n_passphrases {
// Again, we have more code than we should because of this pesky list type situation...
let passphrase = match (&custom_list, built_in_list) {
(Some(ref custom_list), _) => generate_passphrase(
number_of_words_to_put_in_passphrase,
&opt.separator,
opt.title_case,
custom_list,
),
(None, Some(built_in_list)) => generate_passphrase(
number_of_words_to_put_in_passphrase,
&opt.separator,
opt.title_case,
built_in_list,
),
(None, None) => return Err("List selection error!".to_string()),
};
println!("{}", passphrase);
}

Any ideas on how to refactor this would be appreciated!

For example, is there a way to make a single Type or Struct that can take both a &' static[& 'static str] and a Vec<String>?