use std::path::PathBuf;
use std::sync::OnceLock;
static FOUND: OnceLock<Option<PathBuf>> = OnceLock::new();
fn env_home() -> Option<PathBuf> {
std::env::var_os("HOME")
.or_else(|| std::env::var_os("USERPROFILE"))
.map(PathBuf::from)
}
fn candidates() -> Vec<PathBuf> {
let mut v = Vec::new();
if let Some(p) = std::env::var_os("HASHGLASS_WORDLIST") {
v.push(PathBuf::from(p));
}
v.push(PathBuf::from("/usr/share/wordlists/rockyou.txt"));
if let Some(home) = env_home() {
v.push(home.join("wordlists").join("rockyou.txt"));
}
v
}
pub fn find() -> Option<PathBuf> {
FOUND
.get_or_init(|| candidates().into_iter().find(|p| p.is_file()))
.clone()
}
pub fn substitute() -> String {
match find() {
Some(p) => {
let s = p.to_string_lossy().into_owned();
if s.contains(' ') {
format!("\"{s}\"")
} else {
s
}
}
None => "<wordlist>".to_string(),
}
}
pub fn hint() -> &'static str {
if find().is_some() {
""
} else {
"hint: no rockyou.txt found — set $HASHGLASS_WORDLIST or drop one at /usr/share/wordlists/rockyou.txt"
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
fn reset_cache() {
}
#[test]
fn candidates_include_env_override_first() {
unsafe { std::env::set_var("HASHGLASS_WORDLIST", "/tmp/hg_test_wl.txt") };
let c = candidates();
assert_eq!(c[0], PathBuf::from("/tmp/hg_test_wl.txt"));
unsafe { std::env::remove_var("HASHGLASS_WORDLIST") };
reset_cache();
}
#[test]
fn candidates_include_home_wordlists_dir() {
let c = candidates();
assert!(
c.iter()
.any(|p| p.ends_with("wordlists/rockyou.txt")
|| p.ends_with("wordlists\\rockyou.txt"))
);
}
#[test]
fn substitute_returns_placeholder_when_nothing_found() {
let path = std::env::temp_dir().join(format!("nope_{}.txt", std::process::id()));
assert!(!path.is_file(), "test fixture must not exist");
let resolved = candidates().into_iter().find(|p| p.is_file());
if resolved.is_none() {
assert_eq!(substitute(), "<wordlist>");
assert!(!hint().is_empty());
}
}
#[test]
fn substitute_quotes_paths_with_spaces() {
let with_space = std::env::temp_dir()
.join("path with space")
.join("rockyou.txt");
fs::create_dir_all(with_space.parent().unwrap()).ok();
fs::write(&with_space, "test\n").ok();
let s = with_space.to_string_lossy().into_owned();
if s.contains(' ') {
let quoted = format!("\"{s}\"");
assert!(quoted.starts_with('"') && quoted.ends_with('"'));
}
let _ = fs::remove_file(&with_space);
}
}