openrr_apps_config/
config.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use std::{fs, path::PathBuf};

use anyhow::Result;
use clap::{Parser, ValueEnum};
use openrr_apps::utils::init_tracing;
use schemars::schema_for;
use serde::Deserialize;
use tracing::debug;

#[derive(Debug, Parser)]
#[clap(name = env!("CARGO_BIN_NAME"))]
struct Args {
    #[clap(subcommand)]
    subcommand: Subcommand,
}

#[derive(Debug, Parser)]
enum Subcommand {
    /// Generate JSON schema for the specified config file.
    Schema {
        /// Kind of config file.
        #[clap(value_enum, ignore_case = true)]
        kind: ConfigKind,
    },
    Merge {
        /// Path to the setting file.
        #[clap(long, value_parser)]
        config_path: PathBuf,
        /// Config to overwrite
        #[clap(long)]
        config: String,
    },
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum ConfigKind {
    RobotConfig,
    RobotTeleopConfig,
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum Config {
    RobotConfig(#[allow(dead_code)] Box<openrr_apps::RobotConfig>),
    RobotTeleopConfig(#[allow(dead_code)] Box<openrr_apps::RobotTeleopConfig>),
}

fn main() -> Result<()> {
    init_tracing();
    let args = Args::parse();
    debug!(?args);

    match args.subcommand {
        Subcommand::Schema { kind } => {
            let schema = match kind {
                ConfigKind::RobotConfig => schema_for!(openrr_apps::RobotConfig),
                ConfigKind::RobotTeleopConfig => schema_for!(openrr_apps::RobotTeleopConfig),
            };
            println!("{}", serde_json::to_string_pretty(&schema).unwrap());
        }
        Subcommand::Merge {
            config_path,
            config: overwrite,
        } => {
            let s = &fs::read_to_string(config_path)?;
            let s = &openrr_config::overwrite_str(s, &overwrite)?;
            // check if the edited document is valid config.
            let _base: Config = toml::from_str(s)?;
            println!("{s}");
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use clap::CommandFactory;

    use super::*;

    #[test]
    fn assert_app() {
        Args::command().debug_assert();
    }
}