use clap::crate_name;
use dirs_next::{config_dir, home_dir};
use rev_lines::RevLines;
use std::{
env,
ffi::{OsStr, OsString},
fs::OpenOptions,
io::{self, BufReader, Write},
path::PathBuf,
};
pub fn get_history_filepath() -> PathBuf {
let mut cfg_path = match config_dir() {
Some(dir) => dir,
None => {
if let Some(mut dir) = home_dir() {
dir.push(".config");
dir
} else {
PathBuf::new()
}
}
};
cfg_path.push(crate_name!());
cfg_path.push(".path_history");
cfg_path
}
pub fn get_nth_last_revision(n: u128) -> io::Result<OsString> {
let history_filepath = get_history_filepath();
if !history_filepath.exists() {
return Err(io::Error::new(
io::ErrorKind::NotFound,
"History file not found. Nothing to revert to.",
));
}
let history_file = OpenOptions::new().read(true).open(history_filepath)?;
let rev_lines = RevLines::new(BufReader::new(history_file)).unwrap();
let revision_path = match rev_lines.into_iter().nth((n - 1) as usize) {
Some(s) => OsString::from(s),
None => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!(
"History does not contain {} revision(s). Please specify a smaller revision number.",
&n
),
))
}
};
Ok(revision_path)
}
pub fn write_to_history(p: &OsStr) -> io::Result<()> {
let p_str = p.to_str().unwrap();
let history_filepath = get_history_filepath();
let mut history_file = OpenOptions::new()
.create(true)
.append(true)
.open(history_filepath)?;
writeln!(history_file, "{}", p_str)
}