You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
phetch/src/history.rs

86 lines
2.3 KiB
Rust

5 years ago
use gopher;
use std::fs::File;
use std::io::{BufRead, BufReader, Result, Write};
5 years ago
const CONFIG_DIR: &str = "~/.config/phetch/";
const HISTORY_FILE: &str = "history.gph";
/// History file is saved in ~/.config/phetch/history.gph if the phetch
/// config directory exists.
pub fn load_as_raw_menu() -> String {
5 years ago
let mut out = vec![];
match load() {
Ok(reader) => {
let mut lines = reader.lines();
while let Some(Ok(line)) = lines.next() {
out.insert(0, line); // reverse order
}
5 years ago
}
Err(e) => out.push(format!("3{}", e)),
5 years ago
}
out.insert(0, format!("i{}{}:\r\ni", CONFIG_DIR, HISTORY_FILE));
out.join("\r\n")
5 years ago
}
pub fn load() -> Result<BufReader<File>> {
5 years ago
let dotdir = config_dir_path();
if dotdir.is_none() {
return Err(error!("{} directory doesn't exist", CONFIG_DIR));
5 years ago
}
let history = dotdir.unwrap().join(HISTORY_FILE);
if let Ok(file) = std::fs::OpenOptions::new().read(true).open(&history) {
return Ok(BufReader::new(file));
5 years ago
}
Err(error!("Couldn't open {:?}", history))
5 years ago
}
// save a single history entry
pub fn save(url: &str, label: &str) {
5 years ago
let dotdir = config_dir_path();
if dotdir.is_none() {
return;
}
let dotdir = dotdir.unwrap();
let history = dotdir.join(HISTORY_FILE);
5 years ago
if let Ok(mut file) = std::fs::OpenOptions::new()
.append(true)
.create(true)
.open(history)
{
let (t, host, port, sel) = gopher::parse_url(&url);
// ignore internal URLs
if host == "help" {
return;
}
file.write_all(
format!(
"{}{}\t{}\t{}\t{}\r\n",
gopher::char_for_type(t).unwrap_or('i'),
label,
sel,
host,
port
)
.as_ref(),
);
5 years ago
}
}
// Returns None if the config dir doesn't exist.
5 years ago
pub fn config_dir_path() -> Option<std::path::PathBuf> {
let homevar = std::env::var("HOME");
if homevar.is_err() {
return None;
}
let dotdir = CONFIG_DIR.replace('~', &homevar.unwrap());
5 years ago
let dotdir = std::path::Path::new(&dotdir);
if dotdir.exists() {
Some(std::path::PathBuf::from(dotdir))
} else {
None
}
}