ocpi-tariffs-cli 0.53.0

CLI application for OCPI tariff calculation
Documentation
//! 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::{json, lint, tariff, warning, Versioned as _};

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

/// 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,
}

impl Command {
    /// Run the `lint` Command.
    pub fn run(self) -> Result<(), Error> {
        let Self {
            args:
                Arguments {
                    ocpi_version,
                    pretty,
                    file: tariff,
                    fix,
                },
        } = 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 {
            fix_tariff(
                &tariff,
                ocpi_version,
                version_source,
                tariff_file_path.as_ref(),
            )?;
        }

        Ok(())
    }
}

/// Where the OCPI version being linted against came from.
///
/// Removing an unexpected field is only meaning-preserving when the version was inferred. A
/// tariff's version is inferred from which fields are present, so under a version given on the
/// command line the unexpected fields are exactly the ones that would have selected the other
/// version, and removing them changes what a later inference concludes.
#[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,
    version_source: VersionSource,
    file_path: Option<&FilePath>,
) -> Result<(), Error> {
    let fixed = tariff::fix(tariff, version_source.unexpected_fields()).map_err(Error::Fix)?;

    if fixed.edits == 0 {
        eprintln!("Nothing to {}\n", style("fix").green().bold());
        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!();
    }
}