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

49 lines
1.4 KiB
Rust
Raw Permalink Normal View History

2024-01-14 21:04:10 +00:00
//! Miscellaneous utility functions.
use std::{
fs::{create_dir_all, read_to_string, write},
path::PathBuf,
};
use {color_eyre::Result, dialoguer::Password, rand::seq::IteratorRandom};
2022-10-03 16:02:40 +00:00
use crate::{solution::Solution, year_2020, year_2021};
2024-01-14 21:04:10 +00:00
/// Shorthand to get the solutions for all years.
pub fn get_solutions() -> Vec<Vec<Solution>> {
2022-10-03 16:02:40 +00:00
vec![year_2020::get_solutions(), year_2021::get_solutions()]
}
2024-01-14 21:04:10 +00:00
/// 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()
}
2024-01-14 21:04:10 +00:00
/// 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)
}
}
2024-01-14 21:04:10 +00:00
/// 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)
}