1use std::path::PathBuf;
2
3use toml::{Value, value::Table};
4
5pub type Result<T> = core::result::Result<T, Error>;
6
7#[derive(Debug)]
8#[cfg_attr(test, derive(PartialEq))]
9pub enum Error {
10 BadFormat,
11 NoSuchProperty,
12 NoSuchTable,
13 CouldntReadFile,
14 TomlWrap(toml::de::Error),
15}
16
17impl From<toml::de::Error> for Error {
18 fn from(value: toml::de::Error) -> Self {
19 Error::TomlWrap(value)
20 }
21}
22
23impl core::fmt::Display for Error {
24 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25 write!(fmt, "{self:?}")
27 }
28}
29
30impl std::error::Error for Error {}
31
32pub fn default_paths() -> impl Iterator<Item = PathBuf> {
42 std::env::var("XDG_CONFIG_DIRS")
45 .unwrap_or(String::from(""))
46 .split(":")
47 .chain(["/etc"])
53 .map(|path_str| {
54 let mut path = PathBuf::from(path_str);
55 path.push("gt-tool.toml");
56 path
57 })
58 .collect::<Vec<_>>()
59 .into_iter()
60}
61
62pub fn get_config(
77 project: &str,
78 search_files: impl Iterator<Item = PathBuf>,
79) -> Result<PartialConfig> {
80 let file_iter = search_files;
91
92 let toml_iter = file_iter
93 .map(std::fs::read_to_string) .filter_map(|res| res.ok()) .map(|toml_text| toml_text.parse::<Value>()) .filter_map(|res| res.ok()); let config_iter = toml_iter
99 .map(|val| -> Result<PartialConfig> {
100 let cfg_table = val.as_table().ok_or(Error::BadFormat)?;
104
105 get_table(cfg_table, project)
108 .and_then(PartialConfig::try_from)
110 .or(Ok(PartialConfig::default()))
112 .map(|proj| {
114 (
115 proj.project_path(project),
117 get_table(cfg_table, "all")
119 .and_then(PartialConfig::try_from)
120 .unwrap_or(PartialConfig::default()),
121 )
122 })
123 .map(|pair| pair.0.merge(pair.1))
124 })
125 .filter_map(|res| res.ok())
126 .fold(PartialConfig::default(), |acc, inc| acc.merge(inc));
127 Ok(config_iter)
128}
129
130#[derive(Debug, Default)]
131#[cfg_attr(test, derive(PartialEq))]
132pub struct PartialConfig {
133 project_path: Option<String>,
134 pub gitea_url: Option<String>,
135 pub owner: Option<String>,
136 pub repo: Option<String>,
137 pub token: Option<String>,
138}
139
140impl PartialConfig {
141 fn project_path(self, path: impl ToString) -> Self {
145 PartialConfig {
146 project_path: Some(path.to_string()),
147 ..self
148 }
149 }
150
151 fn merge(self, other: Self) -> Self {
155 Self {
156 project_path: other.project_path.or(self.project_path),
157 gitea_url: other.gitea_url.or(self.gitea_url),
158 owner: other.owner.or(self.owner),
159 repo: other.repo.or(self.repo),
160 token: other.token.or(self.token),
161 }
162 }
163}
164
165impl TryFrom<&Table> for PartialConfig {
166 type Error = crate::config::Error;
167
168 fn try_from(value: &Table) -> Result<Self> {
175 Ok(Self {
176 project_path: None,
178 gitea_url: get_maybe_property(value, "gitea_url")?.cloned(),
179 owner: get_maybe_property(value, "owner")?.cloned(),
180 repo: get_maybe_property(value, "repo")?.cloned(),
181 token: get_maybe_property(value, "token")?.cloned(),
182 })
183 }
184}
185
186fn get_table(outer: &Table, table_name: impl ToString) -> Result<&Table> {
188 outer
189 .get(&table_name.to_string())
190 .ok_or(Error::NoSuchTable)?
191 .as_table()
192 .ok_or(Error::BadFormat)
193}
194
195fn get_maybe_property(outer: &Table, property: impl ToString) -> Result<Option<&String>> {
198 let maybe_prop = get_property(outer, property);
199 match maybe_prop {
200 Ok(value) => Ok(Some(value)),
201 Err(e) => {
202 if let Error::NoSuchProperty = e {
203 Ok(None)
204 } else {
205 Err(e)
206 }
207 }
208 }
209}
210
211fn get_property(outer: &Table, property: impl ToString) -> Result<&String> {
214 let maybe_prop = outer
215 .get(&property.to_string())
216 .ok_or(Error::NoSuchProperty)?;
217 if let Value::String(text) = maybe_prop {
218 Ok(text)
219 } else {
220 Err(Error::BadFormat)
221 }
222}
223
224#[cfg(test)]
225mod tests {
226 use toml::map::Map;
227
228 use super::*;
229
230 #[test]
231 fn read_single_prop() -> Result<()> {
232 let fx_input_str = "owner = \"dingus\"";
233 let fx_value = fx_input_str.parse::<Value>()?;
234 let fx_value = fx_value.as_table().ok_or(Error::NoSuchTable)?;
235 let expected = "dingus";
236
237 let res = get_property(&fx_value, String::from("owner"))?;
238 assert_eq!(res, expected);
239 Ok(())
240 }
241
242 #[test]
244 fn read_single_prop_empty_quotes() -> Result<()> {
245 let fx_input_str = "owner = \"\"";
246 let fx_value = fx_input_str.parse::<Value>()?;
247 let fx_value = fx_value.as_table().ok_or(Error::NoSuchTable)?;
248 let expected = "";
249
250 let res = get_property(&fx_value, String::from("owner"))?;
251 assert_eq!(res, expected);
252 Ok(())
253 }
254
255 #[test]
256 fn read_table() -> Result<()> {
257 let fx_input_str = "[tab]\nwith_a_garbage = \"value\"";
258 let fx_value = fx_input_str.parse::<Value>()?;
259 let fx_value = fx_value.as_table().ok_or(Error::BadFormat)?;
260 let mut expected: Map<String, Value> = Map::new();
261 expected.insert(
262 String::from("with_a_garbage"),
263 Value::String(String::from("value")),
264 );
265
266 let res = get_table(&fx_value, String::from("tab"))?;
267 assert_eq!(res, &expected);
268 Ok(())
269 }
270
271 #[test]
272 fn test_get_config_with_specific_match() -> Result<()> {
273 let search_paths = ["./test_data/sample_config.toml"]
274 .into_iter()
275 .map(PathBuf::from);
276 let load_result = get_config("/home/robert/projects/gt-tool", search_paths)?;
277 let expected = PartialConfig {
278 project_path: Some(String::from("/home/robert/projects/gt-tool")),
279 owner: Some(String::from("robert")),
280 repo: Some(String::from("gt-tool")),
281 gitea_url: Some(String::from("http://localhost:3000")),
282 token: Some(String::from("fake-token")),
283 };
284
285 assert_eq!(load_result, expected);
286 Ok(())
287 }
288
289 #[test]
292 fn test_get_config_no_specific_match() -> Result<()> {
293 let search_paths = ["./test_data/sample_config.toml"]
294 .into_iter()
295 .map(PathBuf::from);
296 let load_result = get_config("/no/such/project", search_paths)?;
297 let expected = PartialConfig {
298 project_path: Some(String::from("/no/such/project")),
299 owner: None,
300 repo: None,
301 gitea_url: Some(String::from("http://localhost:3000")),
302 token: Some(String::from("fake-token")),
303 };
304 assert_eq!(load_result, expected);
305 Ok(())
306 }
307
308 #[test]
311 fn test_get_config_without_all() -> Result<()> {
312 let search_paths = ["./test_data/missing_all_table.toml"]
313 .into_iter()
314 .map(PathBuf::from);
315 let load_result = get_config("/some/other/path", search_paths)?;
316 let expected = PartialConfig {
317 project_path: Some(String::from("/some/other/path")),
318 gitea_url: Some(String::from("fake-url")),
319 ..PartialConfig::default()
320 };
321 assert_eq!(load_result, expected);
322 Ok(())
323 }
324
325 #[test]
328 fn test_get_config_many_missing_files() -> Result<()> {
329 let search_paths = [
330 "./test_data/not_real_1.toml",
331 "./test_data/not_real_2.toml",
332 "./test_data/not_real_3.toml",
333 "./test_data/not_real_4.toml",
334 "./test_data/not_real_5.toml",
335 "./test_data/sample_config.toml",
336 "./test_data/not_real_6.toml",
337 ]
338 .into_iter()
339 .map(PathBuf::from);
340 let load_result = get_config("/home/robert/projects/gt-tool", search_paths)?;
341 let expected = PartialConfig {
342 project_path: Some(String::from("/home/robert/projects/gt-tool")),
343 owner: Some(String::from("robert")),
344 repo: Some(String::from("gt-tool")),
345 gitea_url: Some(String::from("http://localhost:3000")),
346 token: Some(String::from("fake-token")),
347 };
348
349 assert_eq!(load_result, expected);
350 Ok(())
351 }
352}