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 mut content = fs::read_to_string(path).map_err(Error::then_file_io(path))?;
65    json_strip_comments::strip(&mut content).map_err(Error::then_file_io(path))?;
66    debug!(bytes_read = content.len(), "{object_kind} read from file");
67    Ok(content)
68}
69
70/// Load a CDR or tariff from `stdin`.
71pub fn load_object_from_stdin(object_kind: ObjectKind) -> Result<String, Error> {
72    debug!("Loading {object_kind} from stdin");
73    let mut stdin = io::stdin().lock();
74    let mut content = String::with_capacity(DEFAULT_STDIO_BUF_SIZE);
75    let bytes_read = stdin.read_to_string(&mut content).map_err(Error::stdin)?;
76    debug!(bytes_read, "{object_kind} read from stdin");
77    json_strip_comments::strip(&mut content).map_err(Error::stdin)?;
78    Ok(content)
79}
80
81#[doc(hidden)]
82#[derive(Debug)]
83pub enum Error {
84    Handled,
85
86    /// When the process is a `tty` `--cdr` is required.
87    CdrRequired,
88
89    /// An `Error` occurred while parsing a CDR or tariff.
90    Json(json::ParseError),
91
92    /// The tariff could not be parsed well enough to explain it.
93    Explain(warning::Error<tariff::Warning>),
94
95    /// The fixes for a tariff could not be determined or applied.
96    Fix(fix::Error),
97
98    /// The file a `--fix` run would write is already there.
99    FixedFileExists {
100        path: PathBuf,
101    },
102
103    /// An `io::Error` occurred when opening or reading a file.
104    FileIO {
105        path: PathBuf,
106        error: io::Error,
107    },
108
109    /// An internal error that is a bug.
110    Internal(Box<dyn std::error::Error + Send + Sync + 'static>),
111
112    /// A timezone was provided by the user and it failed to parse.
113    InvalidTimezone(chrono_tz::ParseError),
114
115    /// The `CDR` or tariff path supplied is not a file.
116    PathNotFile {
117        path: PathBuf,
118    },
119
120    /// The `CDR` or tariff path supplied doesn't have a parent directory.
121    PathNoParentDir {
122        path: PathBuf,
123    },
124
125    /// An Error happened when calling the `cdr::price` fn.
126    Price(warning::Error<ocpi_tariffs::price::Warning>),
127
128    /// An Error happened when performing I/O.
129    StdIn(io::Error),
130
131    /// When the process is a `tty` `--tariff` is required.
132    TariffRequired,
133
134    /// `--ocpi-version infer` was given for a tariff whose version can not be inferred.
135    TariffVersionUncertain,
136}
137
138impl std::error::Error for Error {}
139
140impl fmt::Display for Error {
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        match self {
143            Self::Handled => Ok(()),
144            Self::CdrRequired => f.write_str("`--cdr` is required when the process is a TTY"),
145            Self::Json(err) => write!(f, "{err}"),
146            Self::Explain(err) => write!(f, "{err}"),
147            Self::Fix(err) => write!(f, "{err}"),
148            Self::FixedFileExists { path } => write!(
149                f,
150                "Refusing to overwrite the existing file `{}`; move it aside and run again",
151                path.display()
152            ),
153            Self::FileIO { path, error } => {
154                write!(f, "File error `{}`: {}", path.display(), error)
155            }
156            Self::Internal(err) => {
157                write!(f, "{err}")
158            }
159            Self::InvalidTimezone(err) => write!(f, "the timezone given is invalid; {err}"),
160            Self::PathNotFile { path } => {
161                write!(f, "The path given is not a file: `{}`", path.display())
162            }
163            Self::PathNoParentDir { path } => {
164                write!(
165                    f,
166                    "The path given doesn't have a parent dir: `{}`",
167                    path.display()
168                )
169            }
170            Self::Price(err) => write!(f, "{err}"),
171            Self::StdIn(err) => {
172                write!(f, "Stdin error {err}")
173            }
174            Self::TariffRequired => f.write_str("`--tariff` is required when the process is a TTY"),
175            Self::TariffVersionUncertain => f.write_str(
176                "The OCPI version of the tariff can not be inferred; give it with `--ocpi-version v211` or `--ocpi-version v221`",
177            ),
178        }
179    }
180}
181
182impl From<warning::Error<ocpi_tariffs::price::Warning>> for Error {
183    fn from(value: warning::Error<ocpi_tariffs::price::Warning>) -> Self {
184        Self::Price(value)
185    }
186}
187
188impl From<json::ParseError> for Error {
189    fn from(err: json::ParseError) -> Self {
190        Self::Json(err)
191    }
192}
193
194impl Error {
195    /// Return a fn that can be used in `Result::map_err` to create a `FileIO`.
196    pub fn then_file_io(path: &Path) -> impl FnOnce(io::Error) -> Error + use<'_> {
197        |error| Self::FileIO {
198            path: path.to_path_buf(),
199            error,
200        }
201    }
202
203    pub fn stdin(err: io::Error) -> Self {
204        Self::StdIn(err)
205    }
206}
207
208#[doc(hidden)]
209pub fn setup_logging() -> Result<(), &'static str> {
210    let stderr = io::stderr();
211    let builder = tracing_subscriber::fmt()
212        .without_time()
213        .with_writer(io::stderr)
214        .with_ansi(stderr.is_terminal());
215
216    let level = match env::var("RUST_LOG") {
217        Ok(s) => s.parse().unwrap_or(tracing::Level::INFO),
218        Err(err) => match err {
219            env::VarError::NotPresent => tracing::Level::INFO,
220            env::VarError::NotUnicode(_) => {
221                return Err("RUST_LOG is not unicode");
222            }
223        },
224    };
225
226    builder.with_max_level(level).init();
227
228    Ok(())
229}