use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use serde_json::{Value, json};
use crate::cli::discover::{self, DiscoverOptions};
use crate::cli::verbs::{self, Output, Overrides, TestsOptions};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CiFormat {
Markdown,
Junit,
Sarif,
Json,
}
#[derive(Clone, Debug, Default)]
pub struct CiOptions {
pub timeout_ms: Option<u64>,
pub format: Option<CiFormat>,
}
#[derive(Clone, Debug)]
enum TomlVal {
Str(String),
Int(i64),
Bool(bool),
StrList(Vec<String>),
}
#[derive(Clone, Debug)]
struct ManifestDefaults {
timeout_ms: Option<u64>,
scope: Option<usize>,
steps: Option<usize>,
budget: Option<u64>,
}
#[derive(Clone, Debug)]
struct ManifestEntry {
kind: String,
line: usize,
fields: BTreeMap<String, TomlVal>,
}
#[derive(Clone, Debug)]
struct Manifest {
defaults: ManifestDefaults,
entries: Vec<ManifestEntry>,
}
fn strip_toml_comment(line: &str) -> &str {
let mut in_dquote = false;
let mut in_squote = false;
let mut esc = false;
for (i, ch) in line.char_indices() {
if esc {
esc = false;
continue;
}
if in_dquote {
if ch == '\\' {
esc = true;
} else if ch == '"' {
in_dquote = false;
}
continue;
}
if in_squote {
if ch == '\'' {
in_squote = false;
}
continue;
}
match ch {
'"' => in_dquote = true,
'\'' => in_squote = true,
'#' => return &line[..i],
_ => {}
}
}
line
}
fn parse_toml_string(raw: &str, line_no: usize) -> Result<String, String> {
let t = raw.trim();
if t.starts_with('"') && t.ends_with('"') && t.len() >= 2 {
let inner = &t[1..t.len() - 1];
let mut out = String::new();
let mut chars = inner.chars();
while let Some(c) = chars.next() {
if c == '\\' {
match chars.next() {
Some('n') => out.push('\n'),
Some('t') => out.push('\t'),
Some('r') => out.push('\r'),
Some('"') => out.push('"'),
Some('\\') => out.push('\\'),
Some(other) => {
return Err(format!("line {line_no}: unknown escape `\\{other}`"));
}
None => return Err(format!("line {line_no}: trailing backslash in string")),
}
} else {
out.push(c);
}
}
Ok(out)
} else if t.starts_with('\'') && t.ends_with('\'') && t.len() >= 2 {
Ok(t[1..t.len() - 1].to_string())
} else {
Err(format!("line {line_no}: expected quoted string, got `{t}`"))
}
}
fn parse_toml_val(raw: &str, line_no: usize) -> Result<TomlVal, String> {
let t = raw.trim();
if t.starts_with('"') || t.starts_with('\'') {
return Ok(TomlVal::Str(parse_toml_string(t, line_no)?));
}
if t.starts_with('[') && t.ends_with(']') {
let inner = t[1..t.len() - 1].trim();
if inner.is_empty() {
return Ok(TomlVal::StrList(Vec::new()));
}
let mut items = Vec::new();
let mut cur = String::new();
let mut in_dq = false;
let mut in_sq = false;
let mut esc = false;
for ch in inner.chars() {
if esc {
cur.push(ch);
esc = false;
continue;
}
if in_dq {
cur.push(ch);
if ch == '\\' {
esc = true;
} else if ch == '"' {
in_dq = false;
}
continue;
}
if in_sq {
cur.push(ch);
if ch == '\'' {
in_sq = false;
}
continue;
}
match ch {
'"' => {
in_dq = true;
cur.push(ch);
}
'\'' => {
in_sq = true;
cur.push(ch);
}
',' => {
let s = cur.trim();
if !s.is_empty() {
items.push(parse_toml_string(s, line_no)?);
}
cur.clear();
}
_ => cur.push(ch),
}
}
let tail = cur.trim();
if !tail.is_empty() {
items.push(parse_toml_string(tail, line_no)?);
}
return Ok(TomlVal::StrList(items));
}
if t == "true" {
return Ok(TomlVal::Bool(true));
}
if t == "false" {
return Ok(TomlVal::Bool(false));
}
if let Ok(n) = t.replace('_', "").parse::<i64>() {
return Ok(TomlVal::Int(n));
}
Err(format!("line {line_no}: unsupported manifest value `{t}`"))
}
fn parse_manifest(text: &str) -> Result<Manifest, String> {
let mut defaults = ManifestDefaults {
timeout_ms: None,
scope: None,
steps: None,
budget: None,
};
let mut entries: Vec<ManifestEntry> = Vec::new();
let mut current: Option<ManifestEntry> = None;
for (idx, raw_line) in text.lines().enumerate() {
let line_no = idx + 1;
let line = strip_toml_comment(raw_line).trim();
if line.is_empty() {
continue;
}
if line.starts_with("[[") && line.ends_with("]]") {
if let Some(prev) = current.take() {
entries.push(prev);
}
let kind = line[2..line.len() - 2].trim().to_ascii_lowercase();
if !matches!(
kind.as_str(),
"check" | "run" | "accepts" | "diff" | "discover" | "tests"
) {
return Err(format!(
"line {line_no}: unknown section `[[{kind}]]` (expected check, run, accepts, diff, discover, or tests)"
));
}
current = Some(ManifestEntry {
kind,
line: line_no,
fields: BTreeMap::new(),
});
continue;
}
let Some((k_raw, v_raw)) = line.split_once('=') else {
return Err(format!(
"line {line_no}: expected `key = value` or `[[section]]`, got `{line}`"
));
};
let key = k_raw.trim().to_ascii_lowercase();
let val = parse_toml_val(v_raw, line_no)?;
if let Some(entry) = current.as_mut() {
validate_entry_key(&entry.kind, &key, line_no)?;
entry.fields.insert(key, val);
} else {
match (key.as_str(), val) {
("timeout", TomlVal::Str(s)) => {
defaults.timeout_ms = Some(
verbs::parse_duration_ms(&s).map_err(|e| format!("line {line_no}: {e}"))?,
);
}
("scope", TomlVal::Int(n)) if n >= 1 => defaults.scope = Some(n as usize),
("steps", TomlVal::Int(n)) if n >= 1 => defaults.steps = Some(n as usize),
("budget", TomlVal::Int(n)) if n >= 1 => defaults.budget = Some(n as u64),
_ => {
return Err(format!(
"line {line_no}: unknown or invalid top-level key `{key}` (expected timeout, scope, steps, or budget)"
));
}
}
}
}
if let Some(last) = current {
entries.push(last);
}
if entries.is_empty() {
return Err("manifest contains no `[[check]]`, `[[run]]`, `[[accepts]]`, `[[diff]]`, `[[discover]]`, or `[[tests]]` entries".to_string());
}
Ok(Manifest { defaults, entries })
}
fn validate_entry_key(kind: &str, key: &str, line_no: usize) -> Result<(), String> {
let allowed: &[&str] = match kind {
"check" => &[
"name",
"file",
"command",
"with",
"tables",
"with_referencing",
"expect",
"induction",
"scope",
"steps",
"budget",
"explain",
],
"run" => &[
"name",
"file",
"command",
"with",
"tables",
"with_referencing",
"expect",
"scope",
"steps",
"budget",
],
"accepts" => &[
"name",
"file",
"trace",
"with",
"tables",
"with_referencing",
"expect",
],
"diff" => &[
"name",
"old",
"new",
"migration",
"of",
"with",
"tables",
"with_referencing",
"ignore_unread",
"expect",
"scope",
"steps",
"budget",
],
"discover" => &[
"name",
"file",
"with",
"tables",
"with_referencing",
"scope",
"budget",
"expect",
],
"tests" => &[
"name",
"file",
"with",
"tables",
"with_referencing",
"allow_dead",
"scope",
"steps",
"budget",
"expect",
],
_ => &[],
};
if !allowed.contains(&key) {
return Err(format!(
"line {line_no}: unknown key `{key}` in `[[{kind}]]`"
));
}
Ok(())
}
fn field_str<'a>(e: &'a ManifestEntry, key: &str) -> Result<Option<&'a str>, String> {
match e.fields.get(key) {
None => Ok(None),
Some(TomlVal::Str(s)) => Ok(Some(s.as_str())),
Some(_) => Err(format!("line {}: `{key}` must be a string", e.line)),
}
}
fn field_usize(e: &ManifestEntry, key: &str) -> Result<Option<usize>, String> {
match e.fields.get(key) {
None => Ok(None),
Some(TomlVal::Int(n)) if *n >= 1 => Ok(Some(*n as usize)),
Some(_) => Err(format!(
"line {}: `{key}` must be a positive integer",
e.line
)),
}
}
fn field_u64(e: &ManifestEntry, key: &str) -> Result<Option<u64>, String> {
match e.fields.get(key) {
None => Ok(None),
Some(TomlVal::Int(n)) if *n >= 1 => Ok(Some(*n as u64)),
Some(_) => Err(format!(
"line {}: `{key}` must be a positive integer",
e.line
)),
}
}
fn field_bool(e: &ManifestEntry, key: &str) -> Result<bool, String> {
match e.fields.get(key) {
None => Ok(false),
Some(TomlVal::Bool(b)) => Ok(*b),
Some(_) => Err(format!("line {}: `{key}` must be true or false", e.line)),
}
}
fn field_str_list(e: &ManifestEntry, key: &str) -> Result<Vec<String>, String> {
match e.fields.get(key) {
None => Ok(Vec::new()),
Some(TomlVal::StrList(v)) => Ok(v.clone()),
Some(TomlVal::Str(s)) => Ok(vec![s.clone()]),
Some(_) => Err(format!(
"line {}: `{key}` must be a string or list of strings",
e.line
)),
}
}
fn resolve_rel(base_dir: Option<&Path>, raw: &str) -> PathBuf {
let p = Path::new(raw);
if p.is_absolute() {
p.to_path_buf()
} else if let Some(dir) = base_dir {
dir.join(p)
} else {
p.to_path_buf()
}
}
fn read_file_or_sql_dir(path: &Path) -> Result<(String, bool, String), String> {
let disp = path.to_string_lossy().into_owned();
if path.is_dir() {
let out = crate::cli::migrations::read(path)?;
let sql_disp = format!("{}.sql", disp.trim_end_matches('/'));
Ok((out, true, sql_disp))
} else {
let body =
std::fs::read_to_string(path).map_err(|e| format!("cannot read `{disp}`: {e}"))?;
let is_sql = disp.ends_with(".sql");
Ok((body, is_sql, disp))
}
}
fn load_sidecars_rel(
base_dir: Option<&Path>,
with_paths: &[String],
) -> Result<(String, Option<String>), String> {
let mut extra_sql = String::new();
let mut extra_als = String::new();
for raw in with_paths {
let p = resolve_rel(base_dir, raw);
let (body, is_sql, _) = read_file_or_sql_dir(&p)?;
if is_sql {
extra_sql.push('\n');
extra_sql.push_str(&body);
extra_sql.push('\n');
} else {
extra_als.push('\n');
extra_als.push_str(&body);
extra_als.push('\n');
}
}
let als = if extra_als.trim().is_empty() {
None
} else {
Some(extra_als)
};
Ok((extra_sql, als))
}
#[derive(Clone, Debug)]
struct EntryResult {
name: String,
kind: String,
file: String,
expected: String,
actual: String,
outcome: &'static str, elapsed_ms: u64,
message: Option<String>,
}
fn check_verdict_matches(expected: &str, actual: &str) -> bool {
if expected == actual {
return true;
}
expected == "holds" && actual == "proved"
}
fn xml_escape(s: &str) -> String {
s.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
.replace('\'', "'")
}
fn render_markdown(
manifest_name: &str,
verdict: &str,
passed: usize,
failed: usize,
unknown: usize,
elapsed_ms: u64,
entries: &[EntryResult],
) -> String {
let mut out = String::new();
let _ = writeln!(out, "# Elinvar CI summary (`{manifest_name}`)\n");
let _ = writeln!(out, "| Entry | Kind | Expected | Actual | Result | Time |");
let _ = writeln!(out, "|---|---|---|---|---|---:|");
for e in entries {
let _ = writeln!(
out,
"| {} | {} | {} | {} | {} | {} ms |",
e.name.replace('|', "\\|"),
e.kind,
e.expected,
e.actual,
e.outcome,
e.elapsed_ms
);
}
let _ = writeln!(
out,
"\nverdict: {verdict} ({passed} passed, {failed} failed, {unknown} unknown, {elapsed_ms} ms)"
);
for e in entries {
if e.outcome != "passed"
&& let Some(msg) = &e.message
{
let first = msg.lines().next().unwrap_or(msg);
let _ = writeln!(out, "- {} ({}): {first}", e.name, e.outcome);
}
}
out
}
fn render_junit(
manifest_name: &str,
failed: usize,
unknown: usize,
elapsed_ms: u64,
entries: &[EntryResult],
) -> String {
let mut out = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
let total_secs = elapsed_ms as f64 / 1000.0;
let _ = writeln!(
out,
"<testsuites tests=\"{}\" failures=\"{failed}\" errors=\"{unknown}\" time=\"{total_secs:.3}\">",
entries.len()
);
let _ = writeln!(
out,
" <testsuite name=\"{}\" tests=\"{}\" failures=\"{failed}\" errors=\"{unknown}\" time=\"{total_secs:.3}\">",
xml_escape(manifest_name),
entries.len()
);
for e in entries {
let secs = e.elapsed_ms as f64 / 1000.0;
if e.outcome == "passed" {
let _ = writeln!(
out,
" <testcase classname=\"elinvar.{}\" name=\"{}\" time=\"{secs:.3}\"/>",
xml_escape(&e.kind),
xml_escape(&e.name)
);
} else {
let tag = if e.outcome == "unknown" {
"error"
} else {
"failure"
};
let msg = e.message.as_deref().unwrap_or("expectation not met");
let _ = writeln!(
out,
" <testcase classname=\"elinvar.{}\" name=\"{}\" time=\"{secs:.3}\">",
xml_escape(&e.kind),
xml_escape(&e.name)
);
let _ = writeln!(
out,
" <{tag} message=\"expected {}, got {}\">{}</{tag}>",
xml_escape(&e.expected),
xml_escape(&e.actual),
xml_escape(msg)
);
out.push_str(" </testcase>\n");
}
}
out.push_str(" </testsuite>\n</testsuites>\n");
out
}
fn render_sarif(entries: &[EntryResult]) -> String {
let mut results = Vec::new();
for e in entries {
if e.outcome == "passed" {
continue;
}
let level = if e.outcome == "unknown" {
"warning"
} else {
"error"
};
let rule_id = format!("elinvar.{}.{}", e.kind, e.outcome);
let detail = e.message.as_deref().unwrap_or("");
let msg = if detail.is_empty() {
format!("{}: expected `{}`, got `{}`", e.name, e.expected, e.actual)
} else {
format!(
"{}: expected `{}`, got `{}`: {}",
e.name,
e.expected,
e.actual,
detail.lines().next().unwrap_or(detail)
)
};
results.push(json!({
"ruleId": rule_id,
"level": level,
"message": { "text": msg },
"locations": [{
"physicalLocation": {
"artifactLocation": { "uri": e.file }
}
}]
}));
}
let sarif = json!({
"$schema": "https://json.schemastore.org/sarif-2.1.0.json",
"version": "2.1.0",
"runs": [{
"tool": {
"driver": {
"name": "elinvar",
"version": env!("CARGO_PKG_VERSION"),
"informationUri": "https://github.com/rustborg/elinvar"
}
},
"results": results
}]
});
serde_json::to_string_pretty(&sarif).unwrap_or_default() + "\n"
}
fn manifest_error(manifest_name: &str, message: String) -> Output {
let text = format!("elinvar ci ({manifest_name}): {message}\n");
Output {
status: 3,
text: text.clone(),
json: json!({
"elinvar": 1,
"command": "ci",
"manifest": manifest_name,
"errors": [{
"code": "ci.manifest",
"message": message,
"fix": "fix the syntax or fields in the CI manifest file",
}],
"story": text,
}),
}
}
pub fn run_manifest(
manifest_path: &str,
manifest_text: &str,
opts: &CiOptions,
on_progress: Option<&dyn Fn(&str)>,
) -> Output {
let manifest = match parse_manifest(manifest_text) {
Ok(m) => m,
Err(msg) => return manifest_error(manifest_path, msg),
};
let base_dir: Option<&Path> = if manifest_path == "-" || manifest_path == "<stdin>" {
None
} else {
Path::new(manifest_path).parent()
};
let started = Instant::now();
let total_timeout_ms = opts.timeout_ms.or(manifest.defaults.timeout_ms);
let deadline = total_timeout_ms.map(|ms| started + Duration::from_millis(ms));
let mut results: Vec<EntryResult> = Vec::with_capacity(manifest.entries.len());
for (idx, entry) in manifest.entries.iter().enumerate() {
let entry_started = Instant::now();
let kind = entry.kind.clone();
let default_file = field_str(entry, "file")
.ok()
.flatten()
.or_else(|| field_str(entry, "old").ok().flatten())
.unwrap_or("");
let name = field_str(entry, "name")
.ok()
.flatten()
.map(str::to_string)
.unwrap_or_else(|| format!("{kind}#{}", idx + 1));
let remaining_ms = match deadline {
Some(dl) => {
let rem = dl.saturating_duration_since(Instant::now());
if rem.is_zero() {
let expected = field_str(entry, "expect")
.ok()
.flatten()
.unwrap_or(default_expect(&kind))
.to_string();
results.push(EntryResult {
name,
kind,
file: default_file.to_string(),
expected,
actual: "unknown".to_string(),
outcome: "unknown",
elapsed_ms: 0,
message: Some("shared CI timeout exhausted".to_string()),
});
continue;
}
Some(rem.as_millis().max(1) as u64)
}
None => None,
};
if let Some(cb) = on_progress {
cb(&format!(
"ci {}/{}: {name} ({kind})",
idx + 1,
manifest.entries.len()
));
}
let res = match run_single_entry(entry, &name, base_dir, &manifest.defaults, remaining_ms) {
Ok(mut r) => {
r.elapsed_ms = entry_started.elapsed().as_millis() as u64;
r
}
Err(err_msg) => EntryResult {
name,
kind: entry.kind.clone(),
file: default_file.to_string(),
expected: default_expect(&entry.kind).to_string(),
actual: "error".to_string(),
outcome: "failed",
elapsed_ms: entry_started.elapsed().as_millis() as u64,
message: Some(err_msg),
},
};
results.push(res);
}
let elapsed_ms = started.elapsed().as_millis() as u64;
let passed = results.iter().filter(|r| r.outcome == "passed").count();
let failed = results.iter().filter(|r| r.outcome == "failed").count();
let unknown = results.iter().filter(|r| r.outcome == "unknown").count();
let (verdict, status) = if failed > 0 {
("failed", 1)
} else if unknown > 0 {
("unknown", 2)
} else {
("passed", 0)
};
let markdown = render_markdown(
manifest_path,
verdict,
passed,
failed,
unknown,
elapsed_ms,
&results,
);
let text = match opts.format.unwrap_or(CiFormat::Markdown) {
CiFormat::Markdown | CiFormat::Json => markdown.clone(),
CiFormat::Junit => render_junit(manifest_path, failed, unknown, elapsed_ms, &results),
CiFormat::Sarif => render_sarif(&results),
};
let entries_json: Vec<Value> = results
.iter()
.map(|r| {
let mut obj = json!({
"name": r.name,
"kind": r.kind,
"file": r.file,
"expected": r.expected,
"actual": r.actual,
"outcome": r.outcome,
"elapsed_ms": r.elapsed_ms,
});
if let Some(m) = &r.message {
obj["message"] = Value::String(m.clone());
}
obj
})
.collect();
Output {
status,
text,
json: json!({
"elinvar": 1,
"command": "ci",
"manifest": manifest_path,
"verdict": verdict,
"passed": passed,
"failed": failed,
"unknown": unknown,
"elapsed_ms": elapsed_ms,
"entries": entries_json,
"markdown": markdown,
}),
}
}
fn default_expect(kind: &str) -> &'static str {
match kind {
"check" => "holds",
"run" => "found",
"accepts" => "allowed",
"diff" => "equivalent",
"discover" => "completed",
"tests" => "passed",
_ => "passed",
}
}
struct EntryCtx<'a> {
entry: &'a ManifestEntry,
name: &'a str,
kind: &'a str,
base_dir: Option<&'a Path>,
expected: String,
with_paths: Vec<String>,
tables: Vec<String>,
with_ref: bool,
over: Overrides,
}
fn run_single_entry(
entry: &ManifestEntry,
name: &str,
base_dir: Option<&Path>,
defaults: &ManifestDefaults,
remaining_ms: Option<u64>,
) -> Result<EntryResult, String> {
let kind = entry.kind.as_str();
let expected = field_str(entry, "expect")?
.unwrap_or(default_expect(kind))
.to_ascii_lowercase();
let ctx = EntryCtx {
entry,
name,
kind,
base_dir,
expected,
with_paths: field_str_list(entry, "with")?,
tables: field_str_list(entry, "tables")?,
with_ref: field_bool(entry, "with_referencing")?,
over: Overrides {
scope: field_usize(entry, "scope")?.or(defaults.scope),
steps: field_usize(entry, "steps")?.or(defaults.steps),
budget: field_u64(entry, "budget")?.or(defaults.budget),
timeout_ms: remaining_ms,
explain: field_bool(entry, "explain")?,
inductive: field_usize(entry, "induction")?,
ignore_unread: field_bool(entry, "ignore_unread")?,
..Overrides::default()
},
};
match kind {
"check" | "run" => run_check_or_run_entry(ctx),
"accepts" => run_accepts_entry(ctx),
"diff" => run_diff_entry(ctx),
"discover" => run_discover_entry(ctx),
"tests" => run_tests_entry(ctx),
_ => Err(format!("unknown manifest section `[[{kind}]]`")),
}
}
fn run_check_or_run_entry(ctx: EntryCtx<'_>) -> Result<EntryResult, String> {
let raw_file = field_str(ctx.entry, "file")?.ok_or_else(|| {
format!(
"line {}: `[[{}]]` requires `file`",
ctx.entry.line, ctx.kind
)
})?;
let path = resolve_rel(ctx.base_dir, raw_file);
let (raw_text, is_sql, disp) = read_file_or_sql_dir(&path)?;
let (extra_sql, extra_als) = load_sidecars_rel(ctx.base_dir, &ctx.with_paths)?;
let cmd_name = field_str(ctx.entry, "command")?;
let verb_static: &'static str = if ctx.kind == "check" { "check" } else { "run" };
let mut over = ctx.over;
let text = if is_sql {
let full_sql = if extra_sql.is_empty() {
raw_text
} else {
format!("{raw_text}\n{extra_sql}")
};
match verbs::compose_sql_model_with_bitwidth(
verb_static,
&disp,
&full_sql,
extra_als.as_deref(),
&ctx.tables,
ctx.with_ref,
!over.from_any,
) {
Ok((m, bw)) => {
over.default_bitwidth = Some(bw);
m
}
Err(out) => {
return Ok(EntryResult {
name: ctx.name.to_string(),
kind: ctx.kind.to_string(),
file: raw_file.to_string(),
expected: ctx.expected,
actual: "error".to_string(),
outcome: "failed",
elapsed_ms: 0,
message: Some(out.text),
});
}
}
} else if let Some(extra) = extra_als {
format!("{raw_text}\n{extra}\n")
} else {
raw_text
};
let out =
verbs::solve_with_progress(verb_static, &disp, &text, cmd_name, over, !is_sql, &|_| {});
let actual = extract_solve_verdict(&out);
let (outcome, msg) = if actual == "unknown" && ctx.expected != "unknown" {
("unknown", Some(out.text))
} else if check_verdict_matches(&ctx.expected, &actual) {
("passed", None)
} else {
("failed", Some(out.text))
};
Ok(EntryResult {
name: ctx.name.to_string(),
kind: ctx.kind.to_string(),
file: raw_file.to_string(),
expected: ctx.expected,
actual,
outcome,
elapsed_ms: 0,
message: msg,
})
}
fn run_accepts_entry(ctx: EntryCtx<'_>) -> Result<EntryResult, String> {
let raw_file = field_str(ctx.entry, "file")?
.ok_or_else(|| format!("line {}: `[[accepts]]` requires `file`", ctx.entry.line))?;
let raw_trace = field_str(ctx.entry, "trace")?
.ok_or_else(|| format!("line {}: `[[accepts]]` requires `trace`", ctx.entry.line))?;
let path = resolve_rel(ctx.base_dir, raw_file);
let trace_path = resolve_rel(ctx.base_dir, raw_trace);
let (raw_text, is_sql, disp) = read_file_or_sql_dir(&path)?;
let trace_text = std::fs::read_to_string(&trace_path)
.map_err(|e| format!("cannot read `{}`: {e}", trace_path.display()))?;
let (extra_sql, extra_als) = load_sidecars_rel(ctx.base_dir, &ctx.with_paths)?;
let text = if is_sql && !extra_sql.is_empty() {
format!("{raw_text}\n{extra_sql}")
} else {
raw_text
};
let out = verbs::accepts_with_options(
&disp,
&text,
&trace_text,
!is_sql,
extra_als.as_deref(),
&ctx.tables,
ctx.with_ref,
);
let actual = if out.status == 3 {
"error".to_string()
} else if out.json.get("allowed").and_then(Value::as_bool) == Some(true) {
"allowed".to_string()
} else {
"refused".to_string()
};
let (outcome, msg) = if actual == ctx.expected {
("passed", None)
} else {
("failed", Some(out.text))
};
Ok(EntryResult {
name: ctx.name.to_string(),
kind: ctx.kind.to_string(),
file: raw_file.to_string(),
expected: ctx.expected,
actual,
outcome,
elapsed_ms: 0,
message: msg,
})
}
fn run_diff_entry(ctx: EntryCtx<'_>) -> Result<EntryResult, String> {
let raw_old = field_str(ctx.entry, "old")?
.ok_or_else(|| format!("line {}: `[[diff]]` requires `old`", ctx.entry.line))?;
let old_path = resolve_rel(ctx.base_dir, raw_old);
let (raw_old_text, old_is_sql, old_disp) = read_file_or_sql_dir(&old_path)?;
let (raw_new_text, new_is_sql, new_disp) = if let Some(mig) = field_str(ctx.entry, "migration")?
{
let mig_path = resolve_rel(ctx.base_dir, mig);
let mig_sql = std::fs::read_to_string(&mig_path)
.map_err(|e| format!("cannot read `{}`: {e}", mig_path.display()))?;
let combined = format!("{raw_old_text}\n-- migration: {mig}\n{mig_sql}\n");
let nd = format!(
"{}+{}.sql",
old_disp.trim_end_matches(".sql"),
mig.trim_end_matches(".sql")
);
(combined, true, nd)
} else {
let raw_new = field_str(ctx.entry, "new")?.ok_or_else(|| {
format!(
"line {}: `[[diff]]` requires `new` or `migration`",
ctx.entry.line
)
})?;
let new_path = resolve_rel(ctx.base_dir, raw_new);
read_file_or_sql_dir(&new_path)?
};
let (extra_sql, extra_als) = load_sidecars_rel(ctx.base_dir, &ctx.with_paths)?;
let old_text = if old_is_sql && !extra_sql.is_empty() {
format!("{raw_old_text}\n{extra_sql}")
} else {
raw_old_text
};
let new_text = if new_is_sql && !extra_sql.is_empty() {
format!("{raw_new_text}\n{extra_sql}")
} else {
raw_new_text
};
let out = if let Some(fun_name) = field_str(ctx.entry, "of")? {
verbs::diff_of_with_extra(
&old_disp,
&old_text,
!old_is_sql,
&new_disp,
&new_text,
!new_is_sql,
fun_name,
extra_als.as_deref(),
ctx.over,
)
} else {
verbs::diff_with_options_and_extra(
&old_disp,
&old_text,
!old_is_sql,
&new_disp,
&new_text,
!new_is_sql,
&ctx.tables,
ctx.with_ref,
extra_als.as_deref(),
ctx.over,
)
};
let actual = out
.json
.get("verdict")
.and_then(Value::as_str)
.unwrap_or("error")
.to_string();
let (outcome, msg) = if actual == "unknown" && ctx.expected != "unknown" {
("unknown", Some(out.text))
} else if actual == ctx.expected {
("passed", None)
} else {
("failed", Some(out.text))
};
Ok(EntryResult {
name: ctx.name.to_string(),
kind: ctx.kind.to_string(),
file: raw_old.to_string(),
expected: ctx.expected,
actual,
outcome,
elapsed_ms: 0,
message: msg,
})
}
fn run_discover_entry(ctx: EntryCtx<'_>) -> Result<EntryResult, String> {
let raw_file = field_str(ctx.entry, "file")?
.ok_or_else(|| format!("line {}: `[[discover]]` requires `file`", ctx.entry.line))?;
let path = resolve_rel(ctx.base_dir, raw_file);
let (raw_sql, _, disp) = read_file_or_sql_dir(&path)?;
let (extra_sql, extra_als) = load_sidecars_rel(ctx.base_dir, &ctx.with_paths)?;
let full_sql = if extra_sql.is_empty() {
raw_sql
} else {
format!("{raw_sql}\n{extra_sql}")
};
let dopts = DiscoverOptions {
tables: ctx.tables,
with_referencing: ctx.with_ref,
extra_als,
scope: ctx.over.scope.unwrap_or(3),
budget: ctx.over.budget,
timeout_ms: ctx.over.timeout_ms,
show_rejected: false,
};
let out = discover::discover(&disp, &full_sql, &dopts, None);
let actual = match out.status {
0 => "completed".to_string(),
2 => "unknown".to_string(),
_ => "error".to_string(),
};
let (outcome, msg) = if actual == "unknown" && ctx.expected != "unknown" {
("unknown", Some(out.text))
} else if actual == ctx.expected {
("passed", None)
} else {
("failed", Some(out.text))
};
Ok(EntryResult {
name: ctx.name.to_string(),
kind: ctx.kind.to_string(),
file: raw_file.to_string(),
expected: ctx.expected,
actual,
outcome,
elapsed_ms: 0,
message: msg,
})
}
fn run_tests_entry(ctx: EntryCtx<'_>) -> Result<EntryResult, String> {
let raw_file = field_str(ctx.entry, "file")?
.ok_or_else(|| format!("line {}: `[[tests]]` requires `file`", ctx.entry.line))?;
let path = resolve_rel(ctx.base_dir, raw_file);
let (raw_text, is_sql, disp) = read_file_or_sql_dir(&path)?;
let (extra_sql, extra_als) = load_sidecars_rel(ctx.base_dir, &ctx.with_paths)?;
let text = if is_sql && !extra_sql.is_empty() {
format!("{raw_text}\n{extra_sql}")
} else {
raw_text
};
let allow_dead = field_str_list(ctx.entry, "allow_dead")?;
let topts = TestsOptions {
as_sql: false,
tables: ctx.tables,
with_referencing: ctx.with_ref,
sample_values: BTreeMap::new(),
allow_dead,
extra_als,
};
let out = verbs::tests_with_options(&disp, &text, ctx.over, &topts, !is_sql, None);
let actual = match out.status {
0 => "passed".to_string(),
1 => "failed".to_string(),
2 => "unknown".to_string(),
_ => "error".to_string(),
};
let (outcome, msg) = if actual == "unknown" && ctx.expected != "unknown" {
("unknown", Some(out.text))
} else if actual == ctx.expected {
("passed", None)
} else {
("failed", Some(out.text))
};
Ok(EntryResult {
name: ctx.name.to_string(),
kind: ctx.kind.to_string(),
file: raw_file.to_string(),
expected: ctx.expected,
actual,
outcome,
elapsed_ms: 0,
message: msg,
})
}
fn extract_solve_verdict(out: &Output) -> String {
if out.status == 3 {
return "error".to_string();
}
if let Some(v) = out.json.get("verdict").and_then(Value::as_str) {
return v.to_string();
}
if let Some(results) = out.json.get("results").and_then(Value::as_array) {
let mut saw_unknown = false;
let mut saw_vacuous = false;
let mut saw_proved = true;
for r in results {
match r.get("verdict").and_then(Value::as_str) {
Some("counterexample") => return "counterexample".to_string(),
Some("none") => return "none".to_string(),
Some("unknown") => saw_unknown = true,
Some("vacuous") => saw_vacuous = true,
Some("proved") => {}
Some("holds") => saw_proved = false,
Some("found") => saw_proved = false,
_ => return "error".to_string(),
}
}
if saw_unknown {
return "unknown".to_string();
}
if saw_vacuous {
return "vacuous".to_string();
}
if let Some(first_v) = results
.first()
.and_then(|r| r.get("verdict"))
.and_then(Value::as_str)
{
if first_v == "found" {
return "found".to_string();
}
if saw_proved {
return "proved".to_string();
}
return "holds".to_string();
}
}
"error".to_string()
}