2
0
mirror of https://github.com/xvxx/phetch synced 2024-11-05 00:00:58 +00:00
phetch/src/config.rs

63 lines
1.8 KiB
Rust
Raw Normal View History

2019-12-23 08:09:18 +00:00
use gopher;
2019-12-23 08:22:08 +00:00
use std::fs::{File, OpenOptions};
use std::io::{BufReader, Result, Write};
2019-12-23 08:09:18 +00:00
pub const DIR: &str = "~/.config/phetch/";
// Loads a file in the config directory for reading.
pub fn load(filename: &str) -> Result<BufReader<File>> {
2019-12-23 19:06:52 +00:00
path().and_then(|dotdir| {
2019-12-23 08:09:18 +00:00
let path = dotdir.join(filename);
if let Ok(file) = OpenOptions::new().read(true).open(&path) {
Ok(BufReader::new(file))
} else {
Err(error!("Couldn't open {:?}", path))
}
2019-12-23 19:06:52 +00:00
})
2019-12-23 08:09:18 +00:00
}
// Append a menu item as a line to a file in the config dir.
2019-12-23 19:06:52 +00:00
pub fn append(filename: &str, label: &str, url: &str) -> Result<()> {
path().and_then(|dotdir| {
let path = dotdir.join(filename);
2019-12-23 08:09:18 +00:00
if let Ok(mut file) = std::fs::OpenOptions::new()
.append(true)
.create(true)
2019-12-23 19:06:52 +00:00
.open(path)
2019-12-23 08:22:08 +00:00
{
let (t, host, port, sel) = gopher::parse_url(&url);
file.write_all(
format!(
"{}{}\t{}\t{}\t{}\r\n",
gopher::char_for_type(t).unwrap_or('i'),
label,
sel,
host,
port
)
.as_ref(),
);
2019-12-23 19:06:52 +00:00
Ok(())
} else {
Err(error!("Can't open file for writing: {:?}", filename))
2019-12-23 08:22:08 +00:00
}
2019-12-23 19:06:52 +00:00
})
2019-12-23 08:09:18 +00:00
}
// PathBuf to config dir if it exists.
// None if the config dir doesn't exist.
2019-12-23 19:06:52 +00:00
pub fn path() -> Result<std::path::PathBuf> {
2019-12-23 08:09:18 +00:00
let homevar = std::env::var("HOME");
if homevar.is_err() {
2019-12-23 19:06:52 +00:00
return Err(error!("$HOME not set, can't decode `~`"));
2019-12-23 08:09:18 +00:00
}
let dotdir = DIR.replace('~', &homevar.unwrap());
let dotdir = std::path::Path::new(&dotdir);
if dotdir.exists() {
2019-12-23 19:06:52 +00:00
Ok(std::path::PathBuf::from(dotdir))
2019-12-23 08:09:18 +00:00
} else {
2019-12-23 19:06:52 +00:00
Err(error!("Config dir not found: {}", DIR))
2019-12-23 08:09:18 +00:00
}
}