#![allow(clippy::print_stdout, clippy::print_stderr)]
use std::path::PathBuf;
use std::process::ExitCode;
use anyhow::{Context as _, Result};
use clap::{Parser, Subcommand};
use s2_kit::codec::{DecodeOptions, decode_with};
use s2_kit::session::Analyzer;
use s2_kit::testing::{read_s2log, replay_with};
use s2_kit::types::WireProfile;
use s2_kit::validate::{Context, Severity, Validate, rules};
#[derive(Parser)]
#[command(
name = "s2-kit",
version,
about = "Validate S2 messages and transcripts"
)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
Validate {
path: PathBuf,
#[arg(long)]
lenient: bool,
#[arg(long)]
strict_warnings: bool,
#[arg(long)]
beta: bool,
},
Replay {
path: PathBuf,
#[command(flatten)]
options: ReplayOptions,
},
Rules,
}
#[derive(Debug, Clone, Copy, clap::Args)]
struct ReplayOptions {
#[arg(long)]
strict: bool,
#[arg(long)]
strict_warnings: bool,
#[arg(long)]
beta: bool,
#[arg(long)]
s2_connect: bool,
}
fn main() -> ExitCode {
match run() {
Ok(true) => ExitCode::SUCCESS,
Ok(false) => ExitCode::FAILURE,
Err(e) => {
eprintln!("s2-kit: {e:#}");
ExitCode::FAILURE
}
}
}
fn read(path: &PathBuf) -> Result<String> {
if path.as_os_str() == "-" {
Ok(std::io::read_to_string(std::io::stdin())?)
} else {
std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))
}
}
fn run() -> Result<bool> {
let cli = Cli::parse();
match cli.command {
Command::Rules => {
print!("{}", s2_kit::validate::rules_markdown());
Ok(true)
}
Command::Validate {
path,
lenient,
strict_warnings,
beta,
} => Ok(validate_text(
&read(&path)?,
lenient,
strict_warnings,
profile(beta),
)),
Command::Replay { path, options } => Ok(replay_text(&read(&path)?, options)),
}
}
fn validate_text(text: &str, lenient: bool, strict_warnings: bool, profile: WireProfile) -> bool {
let mut options = DecodeOptions::default().profile(profile);
if lenient {
options = options.lenient();
}
let ctx = Context {
profile,
..Context::empty()
};
let mut ok = true;
let mut checked = 0usize;
for (line_number, chunk) in messages_in(text).into_iter().enumerate() {
checked += 1;
let label = format!("message {}", line_number + 1);
match decode_with(&chunk, &options) {
Err(error) => {
println!("{label}: {error}");
ok = false;
}
Ok(decoded) => {
for path in &decoded.pruned {
println!("{label}: pruned {path}");
}
let report = decoded.message.validate(&ctx);
for violation in report.violations() {
println!("{label}: {violation}");
if violation.severity == Severity::Error || strict_warnings {
ok = false;
}
}
}
}
}
println!(
"{checked} message(s) checked against {} rules: {}",
rules::RULES.len(),
if ok { "ok" } else { "FAILED" }
);
ok
}
fn replay_text(text: &str, options: ReplayOptions) -> bool {
let entries = read_s2log(text);
if entries.is_empty() {
eprintln!("s2-kit: no transcript lines found; expected JSON Lines of {{t, dir, msg}}");
return false;
}
let mut analyzer = Analyzer::new().profile(profile(options.beta));
if options.strict {
analyzer = analyzer.strict();
}
if options.s2_connect {
analyzer = analyzer.over_s2_connect();
}
let report = replay_with(&entries, analyzer);
for finding in &report.findings {
println!("{finding}");
}
let failed = report
.findings
.iter()
.any(|finding| finding.is_error() || options.strict_warnings);
println!(
"{} line(s), {} answered, checked against {} rules: {}",
report.lines,
report.answered,
rules::RULES.len(),
if failed { "FAILED" } else { "ok" }
);
!failed
}
const fn profile(beta: bool) -> WireProfile {
if beta {
WireProfile::V0_0_2Beta
} else {
WireProfile::V1_0_0
}
}
fn messages_in(text: &str) -> Vec<String> {
let trimmed = text.trim();
if let Ok(serde_json::Value::Array(items)) = serde_json::from_str(trimmed) {
return items.iter().map(ToString::to_string).collect();
}
if trimmed.lines().count() > 1 {
let lines: Vec<String> = trimmed
.lines()
.filter(|l| !l.trim().is_empty())
.filter_map(|line| {
let value: serde_json::Value = serde_json::from_str(line).ok()?;
Some(
value
.get("msg")
.map_or_else(|| line.to_string(), ToString::to_string),
)
})
.collect();
if lines.len() == trimmed.lines().filter(|l| !l.trim().is_empty()).count() {
return lines;
}
}
vec![trimmed.to_string()]
}