#[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,
};
const STDIN_NAME: &str = "<stdin>";
const STDOUT_NAME: &str = "<stdout>";
const FIXED_SUFFIX: &str = "_fixed.json";
#[derive(Parser)]
pub struct Command {
#[command(flatten)]
args: Arguments,
}
#[derive(Args)]
struct Arguments {
#[arg(short = 'o', long, value_enum)]
ocpi_version: LintVersion,
#[arg(long)]
pretty: bool,
#[arg(short = 'f', long)]
file: Option<PathBuf>,
#[arg(long)]
fix: bool,
#[arg(long, requires = "fix")]
allow_changes: bool,
}
impl 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(())
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum VersionSource {
Inferred,
Given,
}
impl VersionSource {
fn unexpected_fields(self) -> lint::fix::UnexpectedFields {
match self {
Self::Inferred => lint::fix::UnexpectedFields::Remove,
Self::Given => lint::fix::UnexpectedFields::Keep,
}
}
}
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))
}
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)
}
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(())
}
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())
}
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))
}
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<_>>();
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!();
}
}