1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
use crate::gopher;
use std::{
fs::{File, OpenOptions},
io::{prelude::*, BufReader, Result, Write},
};
pub const DIR: &str = "~/.config/phetch/";
pub fn exists(filename: &str) -> bool {
if let Ok(path) = path() {
path.join(filename).exists()
} else {
false
}
}
pub fn load(filename: &str) -> Result<BufReader<File>> {
path().and_then(|dotdir| {
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))
}
})
}
pub fn append(filename: &str, label: &str, url: &str) -> Result<()> {
path().and_then(|dotdir| {
let path = dotdir.join(filename);
if let Ok(mut file) = OpenOptions::new().append(true).create(true).open(path) {
let u = gopher::parse_url(url);
write!(
file,
"{}{}\t{}\t{}\t{}\r\n",
u.typ.to_char(),
label,
u.sel,
u.host,
u.port
)?;
Ok(())
} else {
Err(error!("Can't open file for writing: {:?}", filename))
}
})
}
pub fn prepend(filename: &str, label: &str, url: &str) -> Result<()> {
path().and_then(|dotdir| {
let path = dotdir.join(filename);
if let Ok(mut file) = OpenOptions::new()
.write(true)
.read(true)
.create(true)
.open(path)
{
let url = gopher::parse_url(url);
let mut buf = vec![];
file.read_to_end(&mut buf)?;
file.seek(std::io::SeekFrom::Start(0))?;
write!(
file,
"{}{}\t{}\t{}\t{}\r\n",
url.typ.to_char(),
label,
url.sel,
url.host,
url.port
)?;
file.write_all(&buf)?;
Ok(())
} else {
Err(error!("Can't open file for writing: {:?}", filename))
}
})
}
pub fn path() -> Result<std::path::PathBuf> {
let homevar = std::env::var("HOME");
if homevar.is_err() {
return Err(error!("$HOME not set, can't decode `~`"));
}
let dotdir = DIR.replace('~', &homevar.unwrap());
let dotdir = std::path::Path::new(&dotdir);
if dotdir.exists() {
Ok(std::path::PathBuf::from(dotdir))
} else {
Err(error!("Config dir not found: {}", DIR))
}
}