Skip to main content

pubhubs/cli/
common.rs

1use crate::servers::Config;
2
3/// Arguments shared between `admin` and `serve` commands.
4#[derive(clap::Args, Debug)]
5pub(crate) struct CommonArgs {
6    /// Look for a configuration file at these locations.  If no configuration file is found at the
7    /// first location, the second one is consulted, and so on.  
8    #[arg(
9        name = "config",
10        short,
11        long,
12        value_name = "PATHS",
13        default_values = ["pubhubs.toml", "pubhubs.default.toml"]
14    )]
15    config_search_paths: Vec<std::path::PathBuf>,
16}
17
18impl CommonArgs {
19    pub fn load_config(&self) -> anyhow::Result<Config> {
20        let config = self.load_config_inner()?;
21
22        match config.log.as_ref() {
23            Some(c) => std::borrow::Cow::Borrowed(c),
24            None => std::borrow::Cow::Owned(Default::default()),
25        }
26        .try_init_env_logger();
27
28        Ok(config)
29    }
30
31    fn load_config_inner(&self) -> anyhow::Result<Config> {
32        for pb in &self.config_search_paths {
33            if let Some(config) = Config::load_from_path(pb)? {
34                return Ok(config);
35            }
36
37            log::info!("no configuration file at {}", pb.display());
38        }
39
40        anyhow::bail!(
41            "no config file found at any of these paths: {}",
42            self.config_search_paths
43                .iter()
44                .map(|pb| pb.to_string_lossy().into_owned())
45                .collect::<Vec<String>>()
46                .join(", ")
47        );
48    }
49}