whitequark / rust-xdg

A library that makes it easy to follow the X Desktop Group specifications
https://wiki.freedesktop.org/www/Specifications/
Apache License 2.0
154 stars 30 forks source link

Wishlist: find a named config file in all config directories #19

Closed takluyver closed 6 years ago

takluyver commented 6 years ago

Apologies if I'm missing an easy way to do this with the existing methods, but I'd like a method to find instances of a config file from all the directories on the search path, so that user config can be merged with system config.

This is what I've written in my application to do this (it's clumsy code, because I'm new to rust, but it might make it clearer what I mean):

fn find_config_files<P>(relpath: P) -> Vec<PathBuf> where P:AsRef<Path> {
    let basedirs = xdg::BaseDirectories::new().unwrap();
    let mut config_dirs = basedirs.get_config_dirs();
    config_dirs.reverse();  // Ordered from least preferred to most preferred
    config_dirs.push(basedirs.get_config_home());
    println!("XDG Config dirs: {:?}", config_dirs);
    let mut files = Vec::new();
    for dir in config_dirs {
        let file = dir.join(&relpath);
        if file.is_file() {
            files.push(file);
        }
    }
    files
}
whitequark commented 6 years ago

Seems like an iterator would be in order here. It can be emulated slightly more elegantly than you did it with:

let basedirs = xdg::BaseDirectories::new().unwrap();
let config_dirs = [basedirs.get_config_home()].iter();
let config_dirs = config_dirs.chain(basedirs.get_config_dirs().rev());
for dir in config_dirs {
  ...
}
takluyver commented 6 years ago

Thanks, that is more elegant. Shall I make a pull request? Do you want it just for config, or for data as well? I think it makes most sense for config, but it might be worth having both for symmetry.

whitequark commented 6 years ago

Let's go with both, I can see uses for either. A PR sounds good. Do you know how to make new iterators?

takluyver commented 6 years ago

I haven't made an iterator before, but do you mean like it's explained here, or is there a better way?

whitequark commented 6 years ago

Oh I forgot how cool the Rust community is. This saves me the hassle of explaining it!

takluyver commented 6 years ago

Great, I'll give it a go :-)