bbox_core/
cli.rs

1use crate::config::{config_error_exit, Loglevel};
2use crate::service::OgcApiService;
3use clap::{ArgMatches, Args, Command, CommandFactory, FromArgMatches, Parser, Subcommand};
4use log::warn;
5use std::env;
6use std::path::{Path, PathBuf};
7
8#[derive(Args, Debug)]
9pub struct GlobalArgs {
10    /// Config file (Default: bbox.toml)
11    #[arg(short, long, value_name = "FILE")]
12    pub config: Option<PathBuf>,
13    /// Log level (Default: info)
14    #[arg(long)]
15    pub loglevel: Option<Loglevel>,
16}
17
18#[derive(Parser, Debug)]
19pub enum CommonCommands {
20    /// Run service
21    Serve(ServeArgs),
22}
23
24#[derive(Args, Debug)]
25pub struct ServeArgs {
26    /// Serve service from file or URL
27    pub file_or_url: Option<String>,
28}
29
30/* t-rex serve:
31OPTIONS:
32    --bind <IPADDRESS>                          Bind web server to this address (0.0.0.0 for all)
33-c, --config <FILE>                             Load from custom config file
34    --loglevel <error|warn|info|debug|trace>    Log level (Default: info)
35    --port <PORT>                               Bind web server to this port
36*/
37
38#[derive(Parser, Debug)]
39pub enum NoCommands {}
40
41#[derive(Args, Debug)]
42pub struct NoArgs;
43
44/// Combined cli commands and args for composed service
45#[derive(Clone)]
46pub struct CliArgs {
47    cli: Command,
48}
49
50impl CliArgs {
51    pub fn register_args<C: Subcommand, A: clap::Args>(&mut self) {
52        let mut cli = C::augment_subcommands(self.cli.clone());
53        if std::any::type_name::<A>() != "bbox_core::cli::NoArgs" {
54            cli = A::augment_args(cli);
55        }
56        self.cli = cli;
57    }
58    /// Register service commands and args
59    pub fn register_service_args<S: OgcApiService>(&mut self) {
60        self.register_args::<S::CliCommands, S::CliArgs>();
61    }
62    pub fn cli_matches(&self) -> ArgMatches {
63        // cli.about("BBOX tile server")
64        self.cli.clone().get_matches()
65    }
66    pub fn apply_global_args(&self) {
67        let Ok(args) = GlobalArgs::from_arg_matches(&self.cli_matches()) else {
68            warn!("GlobalArgs::from_arg_matches error");
69            return;
70        };
71        if let Some(config) = args.config {
72            if Path::new(&config).exists() {
73                env::set_var("BBOX_CONFIG", config);
74            } else {
75                config_error_exit(format!("Config file {config:?} not found."));
76            }
77        }
78    }
79}
80
81impl Default for CliArgs {
82    fn default() -> Self {
83        Self {
84            cli: NoCommands::command(),
85        }
86    }
87}