Skip to main content

gt_tool/
config.rs

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        // FIXME: Print a nice output, don't just reuse the Debug impl
26        write!(fmt, "{self:?}")
27    }
28}
29
30impl std::error::Error for Error {}
31
32/// Creates an iterator of default (Linux) search paths. The iterator output
33/// is a list of files named "gt-tool.toml" found in decreasingly specific
34/// configuration folders.
35///
36/// - any dirs listed in env var `$XDG_CONFIG_DIRS`
37/// - and the `/etc` dir
38///
39/// This is so that user-specific configs are used first, then machine-wide
40/// ones.
41pub fn default_paths() -> impl Iterator<Item = PathBuf> {
42    // Read env var `XDG_CONFIG_DIRS` and split on ":" to get highest-priority list
43    // TODO: Emit warning when paths aren't unicode
44    std::env::var("XDG_CONFIG_DIRS")
45        .unwrap_or(String::from(""))
46        .split(":")
47        // Set up the "/etc" list
48        //      Which is pretty silly, in this case.
49        //      Maybe a future version will scan nested folders and this will make
50        //      more sense.
51        // glue on the "/etc" path
52        .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
62/// Searches through the files, `search_files`, for configuration related to a
63/// project, `project`.
64///
65/// The project string is used as a map key and should match the real path of a
66/// project on disk. These are the table names for each config section.
67///
68/// The search files iterator must produce *files* not *folders.* For now,
69/// there is no mechanism to ensure correct usage. Files that can't be opened
70/// will quietly be skipped, so there will be no warning when one gives a
71/// folder.
72///
73/// Use `fn default_paths()` to get a reasonable (Linux) default.
74///
75/// TODO: Check for, and warn or error when given a dir.
76pub fn get_config(
77    project: &str,
78    search_files: impl Iterator<Item = PathBuf>,
79) -> Result<PartialConfig> {
80    /*
81    1. Get conf search (from fn input)
82    2. Iterate config dirs
83    3. Try load toml::Value from file
84    4. Try-get proj-specific table
85    5. Try-get "[all]" table
86    6. (merge) Update `Option::None`s in proj-spec with `Some(_)`s from "[all]"
87    7. (merge, again) Fold the PartialConfigs into a finished one
88    */
89
90    let file_iter = search_files;
91
92    let toml_iter = file_iter
93        .map(std::fs::read_to_string) // read text from file
94        .filter_map(|res| res.ok()) // remove any error messages
95        // TODO: Log warnings when files couldn't be read.
96        .map(|toml_text| toml_text.parse::<Value>()) // try convert to `toml::Value`
97        .filter_map(|res| res.ok()); // remove any failed parses
98    let config_iter = toml_iter
99        .map(|val| -> Result<PartialConfig> {
100            // Like `fn read_conf_str(...)`, but doesn't produce a `WholeFile`
101
102            // 1. Get the top-level table that is the config file
103            let cfg_table = val.as_table().ok_or(Error::BadFormat)?;
104
105            // 2. Get table
106
107            get_table(cfg_table, project)
108                // 3a. convert to PartialConfig
109                .and_then(PartialConfig::try_from)
110                // 3b. or default, if the table couldn't be found.
111                .or(Ok(PartialConfig::default()))
112                // 4. assemble a 2-tuple of PartialConfigs by...
113                .map(|proj| {
114                    (
115                        // 4-1. Passing in the project-specific PartialConfig
116                        proj.project_path(project),
117                        // 4-2. Getting and converting to PartialConfig, or returning any Err() if one appears.
118                        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    // One lonely builder-pattern function to set the project path.
142    // This is so I can do continuation style calls instead of a bunch of
143    // successive `let conf = ...` temporaries.
144    fn project_path(self, path: impl ToString) -> Self {
145        PartialConfig {
146            project_path: Some(path.to_string()),
147            ..self
148        }
149    }
150
151    // Merges two `PartialConfig`'s together, producing a new one.
152    // Non-None values on the right-hand side are used to replace values
153    // in the left-hand side, even if they are Some(_).
154    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    /// Scans properties out of a `toml::Table` to get a PartialConfig.
169    ///
170    /// `Error::NoSuchProperty` is quietly ignored (mapped to `None`) since it
171    /// isn't an error in this context.
172    ///
173    /// All other errors are propagated and should be treated as real failures.
174    fn try_from(value: &Table) -> Result<Self> {
175        Ok(Self {
176            // can't get table name because that key is gone by this point.
177            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
186/// The outer value must be a Table so we can get the sub-table from it.
187fn 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
195/// Similar to `get_property()` but maps the "Error::NoSuchProperty" result to
196/// Option::None. Some properties aren't specified, and that's okay... sometimes.
197fn 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
211/// The config properties are individual strings. This gets the named property,
212/// or an error explaining why it couldn't be fetched.
213fn 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    // The property is given the value of empty-string `""`
243    #[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    // Ensure the config comes back with something even when there is no
290    // matching project-specific table.
291    #[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    // Ensure the config comes back with something even when there is no
309    // "[all]" table
310    #[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    // Ensure that trying to load files that don't exist simply get skipped over
326    // instead of causing a short-circuit exit or other bogus output.
327    #[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}