ocpi_tariffs_cli/
guess_version.rs1use 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#[derive(clap::Parser)]
12pub struct Command {
13 #[command(flatten)]
15 args: Arguments,
16}
17
18#[derive(clap::Args)]
20struct Arguments {
21 #[arg(short = 't', long = "type")]
23 kind: ObjectKind,
24
25 #[arg(short = 'f', long)]
27 file: Option<PathBuf>,
28
29 #[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
43struct Outcome {
45 object_kind: ObjectKind,
47
48 version: guess::Version<ocpi_tariffs::Version, ()>,
50
51 warnings: Option<warning::Set<schema::Warning>>,
56}
57
58impl Command {
59 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 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 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
139fn 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}