ocpi-tariffs-cli 0.54.0

CLI application for OCPI tariff calculation
Documentation
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! Lint a tariff and print a report.

#[cfg(test)]
mod test_fixed_path;

use std::{
    fs,
    io::{IsTerminal as _, Write as _},
    path::{Path, PathBuf},
};

use clap::{Args, Parser};
use console::style;
use ocpi_tariffs::{Versioned as _, json, lint, tariff, warning};

use crate::{
    Error, ObjectKind, load_object_file, load_object_from_stdin,
    opts::{FilePath, LintVersion},
    print,
};

/// The name of the tariff source when using `stdin`.
const STDIN_NAME: &str = "<stdin>";

/// The name of the destination a `--fix` run writes to when the tariff came from `stdin`.
const STDOUT_NAME: &str = "<stdout>";

/// The suffix, extension included, of the file a `--fix` run writes.
const FIXED_SUFFIX: &str = "_fixed.json";

/// The arguments and logic for the `lint::Command`.
#[derive(Parser)]
pub struct Command {
    /// Arguments for the `lint::Command`.
    #[command(flatten)]
    args: Arguments,
}

/// Argument for the lint command.
#[derive(Args)]
struct Arguments {
    /// The OCPI version that should be used for the input structures.
    #[arg(short = 'o', long, value_enum)]
    ocpi_version: LintVersion,

    /// Pretty print the tariff JSON for human consumption.
    #[arg(long)]
    pretty: bool,

    /// A path to the tariff structure in JSON format.
    ///
    /// If no path is provided the tariff is read from standard in.
    #[arg(short = 'f', long)]
    file: Option<PathBuf>,

    /// Write a copy of the tariff with the mechanically fixable warnings resolved.
    ///
    /// The tariff is walked again after each round of edits, until a walk finds nothing left to
    /// fix, because resolving one warning can be what raises or enables the next.
    ///
    /// The copy is written beside the input file with `_fixed.json` in place of its extension,
    /// or to `stdout` when the tariff was read from `stdin`. An existing file is never
    /// overwritten. The copy is linted in turn, so the report that follows the fix is of the
    /// warnings that remain.
    #[arg(long)]
    fix: bool,

    /// Let `--fix` make edits that change what the tariff means under OCPI.
    ///
    /// Without this flag, `--fix` makes only the edits that leave the meaning the same. `lint`
    /// then prints how many of the other edits it held back.
    ///
    /// With or without this flag, `lint` lists each fix it refused, such as a rename
    /// whose new name would clash with the name of another field in the same object.
    #[arg(long, requires = "fix")]
    allow_changes: bool,
}

impl Command {
    /// Run the `lint` Command.
    pub fn run(self) -> Result<(), Error> {
        let Self {
            args:
                Arguments {
                    ocpi_version,
                    pretty,
                    file: tariff,
                    fix,
                    allow_changes,
                },
        } = self;

        let tariff_file_path = tariff.as_deref().map(FilePath::from_path).transpose()?;
        let tariff_name = tariff_file_path
            .as_ref()
            .map(FilePath::file_name)
            .unwrap_or_else(|| STDIN_NAME);

        let tariff_json = if let Some(path) = tariff_file_path.as_ref() {
            load_object_file(path, ObjectKind::Tariff)?
        } else if std::io::stdin().is_terminal() {
            return Err(Error::TariffRequired);
        } else {
            load_object_from_stdin(ObjectKind::Tariff)?
        };

        let tariff_doc = json::parse_object(&tariff_json)?;
        let (tariff_doc, ocpi_version, version_source) = resolve_version(tariff_doc, ocpi_version)?;

        eprintln!(
            "{} tariff `{}` as version `{}`",
            style("Linting").green().bold(),
            style(&tariff_name).blue(),
            style(ocpi_version).blue()
        );

        let (tariff, warnings) = tariff::from_json(tariff_doc, ocpi_version).into_parts();

        if pretty {
            eprintln!("{}", style("# Source Tariff:").green());
            eprintln!("{}\n", json::write::Pretty::from_doc(tariff.as_doc()));
        }

        let report = tariff::lint(&tariff);

        eprintln!("Completed {} tariff\n", style("linting").green().bold());

        let lint::tariff::Report {
            warnings: lint_warnings,
        } = report;

        let source_name = tariff_file_path
            .as_ref()
            .map(FilePath::dir_and_name)
            .unwrap_or_else(|| STDIN_NAME.into());

        print::warning_set("schema validation", &warnings);
        print_report(&source_name, &tariff, &lint_warnings);

        if fix {
            let options =
                lint::fix::Options::default().unexpected_fields(version_source.unexpected_fields());
            let options = if allow_changes {
                options.allow_changes()
            } else {
                options
            };

            fix_tariff(&tariff, ocpi_version, options, tariff_file_path.as_ref())?;
        }

        Ok(())
    }
}

/// Where the OCPI version being linted against came from.
///
/// Removing an unexpected field leaves what the tariff means under OCPI the same. It can still
/// change which version `tariff::infer_version` picks for the fixed copy.
///
/// `infer_version` reads a tariff as 2.2.1 when it has a field that only 2.2.1 defines, such as
/// `party_id`. Without one, `infer_version` reads it as 2.1.1. A tariff linted with
/// `--ocpi-version v211` may hold a 2.2.1-only field, and the 2.1.1 schema reports it as
/// unexpected. Removing that field could turn a tariff that infers as 2.2.1 into one that infers
/// as 2.1.1. That is why `lint` keeps the unexpected fields when the version was given.
///
/// When `lint` inferred the version itself, none of the unexpected fields is a 2.2.1-only field.
/// Removing them leaves the inference where it was.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum VersionSource {
    /// The version was inferred from the fields present in the tariff.
    Inferred,

    /// The version was given with `--ocpi-version`.
    Given,
}

impl VersionSource {
    /// Whether a fix may remove unexpected fields.
    fn unexpected_fields(self) -> lint::fix::UnexpectedFields {
        match self {
            Self::Inferred => lint::fix::UnexpectedFields::Remove,
            Self::Given => lint::fix::UnexpectedFields::Keep,
        }
    }
}

/// The version to lint `doc` against, and the document itself, which inferring takes ownership of.
fn resolve_version(
    doc: json::Document<'_>,
    requested: LintVersion,
) -> Result<(json::Document<'_>, ocpi_tariffs::Version, VersionSource), Error> {
    if let Some(version) = requested.version() {
        return Ok((doc, version, VersionSource::Given));
    }

    let Some(versioned) = tariff::infer_version(doc).certain_or_none() else {
        return Err(Error::TariffVersionUncertain);
    };

    let version = versioned.version();

    Ok((versioned.into_doc(), version, VersionSource::Inferred))
}

/// Resolve the fixable warnings of `tariff`, write the result and report what it still raises.
fn fix_tariff(
    tariff: &tariff::Versioned<'_>,
    ocpi_version: ocpi_tariffs::Version,
    options: lint::fix::Options,
    file_path: Option<&FilePath>,
) -> Result<(), Error> {
    let fixed = tariff::fix(tariff, options).map_err(Error::Fix)?;

    if fixed.edits == 0 && fixed.changes_held_back == 0 && fixed.refused.is_empty() {
        eprintln!("Nothing to {}\n", style("fix").green().bold());
        return Ok(());
    }

    if fixed.changes_held_back > 0 {
        eprintln!(
            "{} `{}` fix(es) that change what the tariff means. Pass `--allow-changes` to make \
             them.\n",
            style("Held back").yellow().bold(),
            style(fixed.changes_held_back).blue()
        );
    }

    if !fixed.refused.is_empty() {
        eprintln!(
            "{} `{}` fix(es). Make these by hand:",
            style("Refused").yellow().bold(),
            style(fixed.refused.len()).blue()
        );

        for refused in &fixed.refused {
            eprintln!(
                "  - path: {}: `{}`, {}",
                print::DisplayPath(&refused.path),
                refused.warning,
                style(refused.reason).yellow()
            );
        }

        eprintln!();
    }

    if fixed.edits == 0 {
        return Ok(());
    }

    let destination = write_fixed(file_path, &fixed.source)?;

    eprintln!(
        "{} `{}` warning(s) in `{}` pass(es), wrote `{}`\n",
        style("Fixed").green().bold(),
        style(fixed.edits).blue(),
        style(fixed.passes).blue(),
        style(&destination).blue()
    );

    if fixed.outcome == lint::fix::Outcome::FixLimit {
        eprintln!(
            "{}: stopped after `{}` pass(es) with fixes still to make, so the report below is \
             not of a fully fixed tariff. This is a bug in this tool.\n",
            style("WARN").yellow(),
            style(fixed.passes).blue()
        );
    }

    relint(&fixed.source, ocpi_version, &destination)
}

/// Lint the fixed tariff and report the warnings that remain.
///
/// The fixed tariff is validated against the version the original was linted against, rather than
/// against a fresh inference, so the report says what the requested lint made of the output.
fn relint(json: &str, ocpi_version: ocpi_tariffs::Version, name: &str) -> Result<(), Error> {
    let doc = json::parse_object(json)?;
    let (tariff, warnings) = tariff::from_json(doc, ocpi_version).into_parts();

    let lint::tariff::Report {
        warnings: lint_warnings,
    } = tariff::lint(&tariff);

    eprintln!(
        "Completed {} `{}`\n",
        style("re-linting").green().bold(),
        style(name).blue()
    );

    print::warning_set("schema validation", &warnings);
    print_report(name, &tariff, &lint_warnings);

    Ok(())
}

/// Write `json` beside the tariff it was fixed from, and return the name of what was written.
///
/// A tariff read from `stdin` has nowhere beside it to write, so its fix goes to `stdout`. The
/// reports go to `stderr`, so the JSON is the whole of `stdout`.
///
/// Neither destination adds a trailing newline, so redirecting `stdout` to a file gives the same
/// bytes as fixing that file in place would have.
fn write_fixed(file_path: Option<&FilePath>, json: &str) -> Result<String, Error> {
    let Some(file_path) = file_path else {
        print!("{json}");
        return Ok(STDOUT_NAME.to_owned());
    };

    let destination = fixed_path(file_path)?;
    let opened = fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&destination);

    let mut file = match opened {
        Ok(file) => file,
        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
            return Err(Error::FixedFileExists { path: destination });
        }
        Err(error) => {
            return Err(Error::FileIO {
                path: destination,
                error,
            });
        }
    };

    file.write_all(json.as_bytes())
        .map_err(Error::then_file_io(&destination))?;

    Ok(destination.display().to_string())
}

/// The path a `--fix` run writes for the tariff at `source`: its name with [`FIXED_SUFFIX`] in
/// place of the extension, in the same directory.
fn fixed_path(source: &Path) -> Result<PathBuf, Error> {
    let Some(stem) = source.file_stem() else {
        return Err(Error::PathNotFile {
            path: source.to_path_buf(),
        });
    };

    let Some(dir) = source.parent() else {
        return Err(Error::PathNoParentDir {
            path: source.to_path_buf(),
        });
    };

    let mut name = stem.to_os_string();
    name.push(FIXED_SUFFIX);

    Ok(dir.join(name))
}

/// Print the lint report cross referencing the warning with the source JSON so the report can
/// display the source JSON for each [`json::Element`] that has warnings.
fn print_report(
    tariff_name: &str,
    tariff: &tariff::Versioned<'_>,
    warnings: &warning::Set<lint::tariff::Warning>,
) {
    const INDENT: &str = "  ";

    if !warnings.is_empty() {
        eprintln!("{}\n", style("# Warnings").yellow());
    }

    let source = tariff.as_doc().source();
    let list_item = style("*").yellow();
    let block = style("|").yellow();

    for group in warnings {
        let (element, warnings) = group.to_parts();
        eprintln!(
            "{} Warnings for `{}`\n",
            style("##").yellow(),
            style(&element.path).yellow()
        );

        eprintln!(
            "{INDENT} {} {}:{}\n{INDENT} {}",
            style("|").green(),
            style(&tariff_name).green(),
            style(element.location).green(),
            style("|").green(),
        );

        let val_lines = source.lines().collect::<Vec<_>>();

        // Calculate the largest amount of whitespace we can trim from a multiline value.
        // `trim_ws` will be `None` if the value is not multiline.
        let trim_ws = val_lines.get(1..).and_then(|lines| {
            lines
                .iter()
                .map(|s| {
                    let trimmed = s.trim_start();
                    s.len().saturating_sub(trimmed.len())
                })
                .min()
        });

        if let Some(trim_ws) = trim_ws {
            let mut val_lines = val_lines.into_iter();

            if let Some(first_line) = val_lines.next() {
                eprint!("{INDENT} {block} {}", style(first_line).yellow());

                for line in val_lines {
                    let (_, line) = line.split_at(trim_ws);
                    eprint!("\n{INDENT} {block} {}", style(line).yellow());
                }

                eprintln!();
            }
        } else {
            eprintln!("{INDENT} {block} {}", style(source).yellow());
        }

        eprintln!();

        for warning in warnings {
            eprintln!("{INDENT} {list_item} {warning}");
        }

        eprintln!();
    }
}