Skip to main content

ocpi_tariffs_cli/
guess_version.rs

1//! Guess the version of a CDR or tariff.
2
3use std::{fmt, path::PathBuf};
4
5use console::style;
6use ocpi_tariffs::{Versioned as _, cdr, guess, json, schema, tariff, warning};
7
8use crate::{Error, ObjectKind, load_object_file, load_object_from_stdin, print};
9
10/// The arguments for the `guess` command.
11#[derive(clap::Parser)]
12pub struct Command {
13    /// The arguments for the `guess` command.
14    #[command(flatten)]
15    args: Arguments,
16}
17
18/// The arguments for the `guess` command.
19#[derive(clap::Args)]
20struct Arguments {
21    /// The type of OCPI object contained in the given JSON.
22    #[arg(short = 't', long = "type")]
23    kind: ObjectKind,
24
25    /// A path to JSON file for the specified object.
26    #[arg(short = 'f', long)]
27    file: Option<PathBuf>,
28
29    /// Check if all fields are allowed to be there according to the OCPI spec.
30    #[arg(long)]
31    validate: bool,
32}
33
34impl fmt::Display for ObjectKind {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        match self {
37            ObjectKind::Cdr => f.write_str("CDR"),
38            ObjectKind::Tariff => f.write_str("tariff"),
39        }
40    }
41}
42
43/// The outcome of running the guess command.
44struct Outcome {
45    /// The kind of object given.
46    object_kind: ObjectKind,
47
48    /// The guessed version of the object given.
49    version: guess::Version<ocpi_tariffs::Version, ()>,
50
51    /// The schema validation warnings for the object.
52    ///
53    /// This is `None` when `--validate` was not requested, or when the guessed
54    /// `Version` is `Uncertain` (there is no schema to validate against).
55    warnings: Option<warning::Set<schema::Warning>>,
56}
57
58impl Command {
59    /// Run the `guess` Command.
60    pub fn run(self) -> Result<(), Error> {
61        let Self {
62            args:
63                Arguments {
64                    kind: object_kind,
65                    file: path,
66                    validate,
67                },
68        } = self;
69
70        let json = if let Some(path) = path.as_deref() {
71            load_object_file(path, object_kind)?
72        } else {
73            load_object_from_stdin(object_kind)?
74        };
75
76        let outcome = match object_kind {
77            ObjectKind::Cdr => {
78                let cdr = json::parse_object(&json)?;
79                let guess = cdr::infer_version(cdr);
80                let version = guess.as_version();
81
82                // Validate against the schema only when the version is certain.
83                let warnings = match (validate, guess) {
84                    (true, guess::Version::Certain(cdr)) => {
85                        let cdr_version = cdr.version();
86                        let (_cdr, warnings) =
87                            cdr::from_json(cdr.into_doc(), cdr_version).into_parts();
88                        Some(warnings)
89                    }
90                    _ => None,
91                };
92
93                Outcome {
94                    object_kind,
95                    version,
96                    warnings,
97                }
98            }
99            ObjectKind::Tariff => {
100                let tariff = json::parse_object(&json)?;
101                let guess = tariff::infer_version(tariff);
102                let version = guess.as_version();
103
104                // Validate against the schema only when the version is certain.
105                let warnings = match (validate, guess) {
106                    (true, guess::Version::Certain(tariff)) => {
107                        let tariff_version = tariff.version();
108                        let (_tariff, warnings) =
109                            tariff::from_json(tariff.into_doc(), tariff_version).into_parts();
110                        Some(warnings)
111                    }
112                    _ => None,
113                };
114
115                Outcome {
116                    object_kind,
117                    version,
118                    warnings,
119                }
120            }
121        };
122
123        let Outcome {
124            object_kind,
125            warnings,
126            version,
127        } = outcome;
128
129        if let Some(warnings) = warnings {
130            print::warning_set("version guessing", &warnings);
131        }
132
133        print_version(object_kind, &version);
134
135        Ok(())
136    }
137}
138
139/// Print the version to the CLI.
140fn print_version(object_kind: ObjectKind, version: &guess::Version<ocpi_tariffs::Version, ()>) {
141    match version {
142        guess::Version::Uncertain(()) => {
143            eprintln!(
144                "Unable to guess the version of the given {} JSON",
145                style(object_kind).green()
146            );
147        }
148        guess::Version::Certain(version) => {
149            println!("{version}");
150        }
151    }
152}