Skip to main content

ocpi_tariffs_cli/
lib.rs

1// Set here rather than in `[workspace.lints.rust]`; see the note in `ocpi-tariffs/src/lib.rs`.
2#![warn(
3    unused_crate_dependencies,
4    reason = "a dependency nothing imports is still compiled, audited and imposed on consumers"
5)]
6#![allow(clippy::print_stderr, reason = "The CLI is allowed to use stderr")]
7#![allow(clippy::print_stdout, reason = "The CLI is allowed to use stdout")]
8#![cfg_attr(doc, doc = include_str!("../README.md"))]
9
10mod explain;
11mod guess_version;
12mod lint;
13mod opts;
14mod price;
15mod print;
16
17use std::{
18    env, fmt, fs,
19    io::{self, IsTerminal as _, Read as _},
20    path::{Path, PathBuf},
21};
22
23use clap::Parser;
24use ocpi_tariffs::{fix, json, tariff, warning};
25use tracing::{debug, instrument};
26
27/// When reading a CDR or tariff from `stdin` create a String with this default
28/// capacity to avoid needless allocations.
29pub const DEFAULT_STDIO_BUF_SIZE: usize = 1024;
30
31#[doc(hidden)]
32#[derive(Parser)]
33#[command(version)]
34pub struct Opts {
35    #[clap(subcommand)]
36    command: opts::Command,
37}
38
39impl Opts {
40    pub fn run(self) -> Result<(), Error> {
41        self.command.run()
42    }
43}
44
45#[derive(Copy, Clone, clap::ValueEnum)]
46pub enum ObjectKind {
47    Cdr,
48    Tariff,
49}
50
51impl fmt::Debug for ObjectKind {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        match self {
54            Self::Cdr => write!(f, "CDR"),
55            Self::Tariff => write!(f, "Tariff"),
56        }
57    }
58}
59
60/// Load a CDR or tariff from file.
61#[instrument]
62pub fn load_object_file(path: &Path, object_kind: ObjectKind) -> Result<String, Error> {
63    debug!("Loading {object_kind} from file");
64    let content = fs::read_to_string(path).map_err(Error::then_file_io(path))?;
65    debug!(bytes_read = content.len(), "{object_kind} read from file");
66    Ok(content)
67}
68
69/// Load a CDR or tariff from `stdin`.
70pub fn load_object_from_stdin(object_kind: ObjectKind) -> Result<String, Error> {
71    debug!("Loading {object_kind} from stdin");
72    let mut stdin = io::stdin().lock();
73    let mut content = String::with_capacity(DEFAULT_STDIO_BUF_SIZE);
74    let bytes_read = stdin.read_to_string(&mut content).map_err(Error::stdin)?;
75    debug!(bytes_read, "{object_kind} read from stdin");
76    Ok(content)
77}
78
79#[doc(hidden)]
80#[derive(Debug)]
81pub enum Error {
82    Handled,
83
84    /// When the process is a `tty` `--cdr` is required.
85    CdrRequired,
86
87    /// An `Error` occurred while parsing a CDR or tariff.
88    Json(json::ParseError),
89
90    /// The tariff could not be parsed well enough to explain it.
91    Explain(warning::Error<tariff::Warning>),
92
93    /// The fixes for a tariff could not be determined or applied.
94    Fix(fix::Error),
95
96    /// The file a `--fix` run would write is already there.
97    FixedFileExists {
98        path: PathBuf,
99    },
100
101    /// An `io::Error` occurred when opening or reading a file.
102    FileIO {
103        path: PathBuf,
104        error: io::Error,
105    },
106
107    /// An internal error that is a bug.
108    Internal(Box<dyn std::error::Error + Send + Sync + 'static>),
109
110    /// A timezone was provided by the user and it failed to parse.
111    InvalidTimezone(chrono_tz::ParseError),
112
113    /// The `CDR` or tariff path supplied is not a file.
114    PathNotFile {
115        path: PathBuf,
116    },
117
118    /// The `CDR` or tariff path supplied doesn't have a parent directory.
119    PathNoParentDir {
120        path: PathBuf,
121    },
122
123    /// An Error happened when calling the `cdr::price` fn.
124    Price(warning::Error<ocpi_tariffs::price::Warning>),
125
126    /// An Error happened when performing I/O.
127    StdIn(io::Error),
128
129    /// When the process is a `tty` `--tariff` is required.
130    TariffRequired,
131
132    /// `--ocpi-version infer` was given for a tariff whose version can not be inferred.
133    TariffVersionUncertain,
134}
135
136impl std::error::Error for Error {}
137
138impl fmt::Display for Error {
139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140        match self {
141            Self::Handled => Ok(()),
142            Self::CdrRequired => f.write_str("`--cdr` is required when the process is a TTY"),
143            Self::Json(err) => write!(f, "{err}"),
144            Self::Explain(err) => write!(f, "{err}"),
145            Self::Fix(err) => write!(f, "{err}"),
146            Self::FixedFileExists { path } => write!(
147                f,
148                "Refusing to overwrite the existing file `{}`; move it aside and run again",
149                path.display()
150            ),
151            Self::FileIO { path, error } => {
152                write!(f, "File error `{}`: {}", path.display(), error)
153            }
154            Self::Internal(err) => {
155                write!(f, "{err}")
156            }
157            Self::InvalidTimezone(err) => write!(f, "the timezone given is invalid; {err}"),
158            Self::PathNotFile { path } => {
159                write!(f, "The path given is not a file: `{}`", path.display())
160            }
161            Self::PathNoParentDir { path } => {
162                write!(
163                    f,
164                    "The path given doesn't have a parent dir: `{}`",
165                    path.display()
166                )
167            }
168            Self::Price(err) => write!(f, "{err}"),
169            Self::StdIn(err) => {
170                write!(f, "Stdin error {err}")
171            }
172            Self::TariffRequired => f.write_str("`--tariff` is required when the process is a TTY"),
173            Self::TariffVersionUncertain => f.write_str(
174                "The OCPI version of the tariff can not be inferred; give it with `--ocpi-version v211` or `--ocpi-version v221`",
175            ),
176        }
177    }
178}
179
180impl From<warning::Error<ocpi_tariffs::price::Warning>> for Error {
181    fn from(value: warning::Error<ocpi_tariffs::price::Warning>) -> Self {
182        Self::Price(value)
183    }
184}
185
186impl From<json::ParseError> for Error {
187    fn from(err: json::ParseError) -> Self {
188        Self::Json(err)
189    }
190}
191
192impl Error {
193    /// Return a fn that can be used in `Result::map_err` to create a `FileIO`.
194    pub fn then_file_io(path: &Path) -> impl FnOnce(io::Error) -> Error + use<'_> {
195        |error| Self::FileIO {
196            path: path.to_path_buf(),
197            error,
198        }
199    }
200
201    pub fn stdin(err: io::Error) -> Self {
202        Self::StdIn(err)
203    }
204}
205
206#[doc(hidden)]
207pub fn setup_logging() -> Result<(), &'static str> {
208    let stderr = io::stderr();
209    let builder = tracing_subscriber::fmt()
210        .without_time()
211        .with_writer(io::stderr)
212        .with_ansi(stderr.is_terminal());
213
214    let level = match env::var("RUST_LOG") {
215        Ok(s) => s.parse().unwrap_or(tracing::Level::INFO),
216        Err(err) => match err {
217            env::VarError::NotPresent => tracing::Level::INFO,
218            env::VarError::NotUnicode(_) => {
219                return Err("RUST_LOG is not unicode");
220            }
221        },
222    };
223
224    builder.with_max_level(level).init();
225
226    Ok(())
227}