1
Fork 0
advent-of-code/source/utilities.rs

49 lines
1.4 KiB
Rust

//! Miscellaneous utility functions.
use std::{
fs::{create_dir_all, read_to_string, write},
path::PathBuf,
};
use {color_eyre::Result, dialoguer::Password, rand::seq::IteratorRandom};
use crate::{solution::Solution, year_2020, year_2021};
/// Shorthand to get the solutions for all years.
pub fn get_solutions() -> Vec<Vec<Solution>> {
vec![year_2020::get_solutions(), year_2021::get_solutions()]
}
/// Return a random emoji from the [`emojis::Group::AnimalsAndNature`] set.
pub fn random_emoji() -> String {
emojis::iter()
.filter(|emoji| emoji.group() == emojis::Group::AnimalsAndNature)
.choose(&mut rand::thread_rng())
.unwrap()
.to_string()
}
/// Get the Advent of Code session cookie from an existing file or start an
/// interactive prompt to ask the user for it.
pub fn session_cookie() -> Result<String> {
let session_cookie_path = PathBuf::from("aoc/session.txt");
if session_cookie_path.exists() {
read_to_string(session_cookie_path).map_err(Into::into)
} else {
let session_cookie = Password::new()
.with_prompt("Advent of Code Session Cookie")
.interact()?;
write_file(session_cookie_path, session_cookie)
}
}
/// Write the given contents to a path, ensuring the parent directory for the
/// location exists.
pub fn write_file(path: PathBuf, contents: String) -> Result<String> {
create_dir_all(path.parent().unwrap())?;
write(path, &contents)?;
Ok(contents)
}