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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
use std::path::{Path, PathBuf};
use directories::{BaseDirs, ProjectDirs};
use once_cell::sync::Lazy;
use serde::Deserialize;
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
#[serde(transparent)]
pub struct CfgPath(PathInner);
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
#[serde(untagged)]
enum PathInner {
Shell(String),
Literal(PathBuf),
}
#[derive(thiserror::Error, Debug, Clone)]
#[non_exhaustive]
pub enum CfgPathError {
#[error("unrecognized variable {0}")]
UnknownVar(String),
#[error("can't construct project directories")]
NoProjectDirs,
#[error("can't construct base directories")]
NoBaseDirs,
#[error("can't convert value of {0} to UTF-8")]
BadUtf8(String),
#[error("invalid path string: {0:?}")]
InvalidString(String),
}
impl CfgPath {
pub fn new(s: String) -> Self {
CfgPath(PathInner::Shell(s))
}
pub fn path(&self) -> Result<PathBuf, CfgPathError> {
match &self.0 {
PathInner::Shell(s) => expand(s),
PathInner::Literal(p) => Ok(p.clone()),
}
}
pub fn from_path<P: AsRef<Path>>(path: P) -> Self {
CfgPath(PathInner::Literal(path.as_ref().to_owned()))
}
}
#[cfg(feature = "expand-paths")]
fn expand(s: &str) -> Result<PathBuf, CfgPathError> {
Ok(shellexpand::full_with_context(s, get_home, get_env)
.map_err(|e| e.cause)?
.into_owned()
.into())
}
#[cfg(not(feature = "expand-paths"))]
fn expand(s: &str) -> Result<PathBuf, CfgPathError> {
s.try_into()
.map_err(|_| CfgPathError::InvalidString(s.to_owned()))
}
#[cfg(feature = "expand-paths")]
fn get_home() -> Option<&'static Path> {
base_dirs().ok().map(BaseDirs::home_dir)
}
#[cfg(feature = "expand-paths")]
fn get_env(var: &str) -> Result<Option<&'static str>, CfgPathError> {
let path = match var {
"ARTI_CACHE" => project_dirs()?.cache_dir(),
"ARTI_CONFIG" => project_dirs()?.config_dir(),
"ARTI_SHARED_DATA" => project_dirs()?.data_dir(),
"ARTI_LOCAL_DATA" => project_dirs()?.data_local_dir(),
"USER_HOME" => base_dirs()?.home_dir(),
_ => return Err(CfgPathError::UnknownVar(var.to_owned())),
};
match path.to_str() {
Some(s) => Ok(Some(s)),
None => Err(CfgPathError::BadUtf8(var.to_owned())),
}
}
impl std::fmt::Display for CfgPath {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.0 {
PathInner::Literal(p) => write!(fmt, "{:?} [exactly]", p),
PathInner::Shell(s) => s.fmt(fmt),
}
}
}
#[cfg(feature = "expand-paths")]
fn project_dirs() -> Result<&'static ProjectDirs, CfgPathError> {
static PROJECT_DIRS: Lazy<Option<ProjectDirs>> =
Lazy::new(|| ProjectDirs::from("org", "torproject", "Arti"));
PROJECT_DIRS.as_ref().ok_or(CfgPathError::NoProjectDirs)
}
#[cfg(feature = "expand-paths")]
fn base_dirs() -> Result<&'static BaseDirs, CfgPathError> {
static BASE_DIRS: Lazy<Option<BaseDirs>> = Lazy::new(BaseDirs::new);
BASE_DIRS.as_ref().ok_or(CfgPathError::NoBaseDirs)
}
#[cfg(all(test, feature = "expand-paths"))]
mod test {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn expand_no_op() {
let p = CfgPath::new("Hello/world".to_string());
assert_eq!(p.to_string(), "Hello/world".to_string());
assert_eq!(p.path().unwrap().to_str(), Some("Hello/world"));
let p = CfgPath::new("/usr/local/foo".to_string());
assert_eq!(p.to_string(), "/usr/local/foo".to_string());
assert_eq!(p.path().unwrap().to_str(), Some("/usr/local/foo"));
}
#[test]
fn expand_home() {
let p = CfgPath::new("~/.arti/config".to_string());
assert_eq!(p.to_string(), "~/.arti/config".to_string());
let expected = dirs::home_dir().unwrap().join(".arti/config");
assert_eq!(p.path().unwrap().to_str(), expected.to_str());
let p = CfgPath::new("${USER_HOME}/.arti/config".to_string());
assert_eq!(p.to_string(), "${USER_HOME}/.arti/config".to_string());
assert_eq!(p.path().unwrap().to_str(), expected.to_str());
}
#[test]
fn expand_cache() {
let p = CfgPath::new("${ARTI_CACHE}/example".to_string());
assert_eq!(p.to_string(), "${ARTI_CACHE}/example".to_string());
let expected = project_dirs().unwrap().cache_dir().join("example");
assert_eq!(p.path().unwrap().to_str(), expected.to_str());
}
#[test]
fn expand_bogus() {
let p = CfgPath::new("${ARTI_WOMBAT}/example".to_string());
assert_eq!(p.to_string(), "${ARTI_WOMBAT}/example".to_string());
assert!(matches!(p.path(), Err(CfgPathError::UnknownVar(_))));
assert_eq!(
&p.path().unwrap_err().to_string(),
"unrecognized variable ARTI_WOMBAT"
);
}
#[test]
fn literal() {
let p = CfgPath::from_path(PathBuf::from("${ARTI_CACHE}/literally"));
assert_eq!(
p.path().unwrap().to_str().unwrap(),
"${ARTI_CACHE}/literally"
);
assert_eq!(p.to_string(), "\"${ARTI_CACHE}/literally\" [exactly]");
}
}