Skip to main content

pubhubs/cli/
common.rs

1use crate::servers::Config;
2
3/// A PubHubs deployment a client command (`enter`, `stress`, ...) can contact.
4#[derive(clap::ValueEnum, Debug, Clone, Copy)]
5pub(crate) enum Environment {
6    Stable,
7    Main,
8    Local,
9}
10
11/// The PHC url to contact: the explicit `--url` override if given, otherwise `environment`'s default.
12pub(crate) fn phc_url(
13    environment: Environment,
14    url_override: &Option<url::Url>,
15) -> std::borrow::Cow<'_, url::Url> {
16    if let Some(url) = url_override {
17        return std::borrow::Cow::Borrowed(url);
18    }
19
20    std::borrow::Cow::Owned(
21        match environment {
22            Environment::Local => "http://localhost:5050",
23            Environment::Stable => "https://phc.pubhubs.net",
24            Environment::Main => "https://phc-main.pubhubs.net",
25        }
26        .parse()
27        .expect("hard-coded environment url should parse"),
28    )
29}
30
31/// Arguments shared between `admin` and `serve` commands.
32#[derive(clap::Args, Debug)]
33pub(crate) struct CommonArgs {
34    /// Look for a configuration file at these locations.  If no configuration file is found at the
35    /// first location, the second one is consulted, and so on.  
36    #[arg(
37        name = "config",
38        short,
39        long,
40        value_name = "PATHS",
41        default_values = ["pubhubs.toml", "pubhubs.default.toml"]
42    )]
43    config_search_paths: Vec<std::path::PathBuf>,
44}
45
46impl CommonArgs {
47    pub fn load_config(&self) -> anyhow::Result<Config> {
48        let config = self.load_config_inner()?;
49
50        match config.log.as_ref() {
51            Some(c) => std::borrow::Cow::Borrowed(c),
52            None => std::borrow::Cow::Owned(Default::default()),
53        }
54        .try_init_env_logger();
55
56        Ok(config)
57    }
58
59    fn load_config_inner(&self) -> anyhow::Result<Config> {
60        for pb in &self.config_search_paths {
61            if let Some(config) = Config::load_from_path(pb)? {
62                return Ok(config);
63            }
64
65            log::info!("no configuration file at {}", pb.display());
66        }
67
68        anyhow::bail!(
69            "no config file found at any of these paths: {}",
70            self.config_search_paths
71                .iter()
72                .map(|pb| pb.to_string_lossy().into_owned())
73                .collect::<Vec<String>>()
74                .join(", ")
75        );
76    }
77}