use elinvar::cli::{audit, ci, discover, fuzz, mcp, verbs};
use std::io::{Read as _, Write as _};
use std::process::ExitCode;
use verbs::{Output, Overrides};
const VERSION: &str = env!("CARGO_PKG_VERSION");
const HELP: &str = "elinvar: find the holes in a design before you build it
usage: elinvar <verb> [arguments] [flags]
verbs:
check FILE [NAME] run every check command of an Alloy file, or the one named
run FILE [NAME] run every run command, or the one named (`--all` enumerates all)
tests FILE generate step reachability and per-guard refusal tests from a model
accepts FILE TRACE check whether a model allows a trace JSON or SQL DML script
fuzz FILE --against CMD run seeded random SQL scripts on both a real database and the model
discover FILE discover and prove common invariants of a `.sql` schema by induction
audit FILE --data DUMP check table rules and single-state promises directly on a SQL dump (no solver)
ci [MANIFEST] run a repository manifest under one timeout (Markdown, JUnit, SARIF, JSON)
diff OLD NEW compare two Alloy models (or two `.sql` schemas) and show differences
import FILE import SQL DDL (CREATE TABLE, UNIQUE INDEX, TRIGGER) into Alloy 6
render RESULT render a result JSON's instance or trace as DOT, Mermaid, or SQL
eval FILE RESULT EXPR evaluate an expression or formula on a result's instance or
trace, without solving again
explain [CODE|schema:<verb>|skill]
explain an error code, print a verb's JSON Schema (or `schema`
to list them), print the embedded agent guide, or list every code
serve --mcp run the Model Context Protocol (MCP) server over stdio
Pass `-` for any single input file argument to read from stdin.
`elinvar <verb> --help` explains each verb in full; `elinvar --version` prints the version.
exit status: 0 every promise holds, or the instance was found; 1 a counterexample was
found, or no instance exists; 2 a verdict is unknown or vacuous; 3 the model or the
arguments have errors.";
const CHECK_HELP: &str =
"elinvar check FILE [NAME] [--with FILE] [--from-any] [--tables A,B [--with-referencing]] [--json] [--explain] [--brief] [--summary] [--climb] [--induction [K]] [--no-slicing] [--scope N] [--steps N] [--budget N] [--timeout DUR]
Runs every `check` command of FILE (an Alloy 6 model, or a `.sql` schema paired
with `--with promises.als`), or only the one named NAME (its label, or the
assertion it checks).
For a `.sql` schema, traces start from empty tables by default (`--from-empty`);
pass `--from-any` to start from any state the schema's rules allow.
Each result says one of:
holds no counterexample up to the scope searched; a larger case might
still break the promise
proved proved for any number of steps within the scope by k-induction
counterexample a case that breaks it, shrunk to the fewest atoms and tuples
vacuous the rules allow no case at all, so nothing can break the promise:
the rules are wrong, not the promise right
unknown the budget ran out first; the note says what is known
flags:
--with FILE append sidecar `.als` promises or `.sql` views/queries (repeatable)
--from-any for a `.sql` schema, start from any allowed state (default: empty tables)
--from-empty for a `.sql` schema, start from empty tables (default on `check`)
--tables A,B for a `.sql` schema, import only these tables and their FK targets
--with-referencing with `--tables`, also include tables pointing into the slice
--json print the result as JSON (schema: `elinvar explain schema:result`);
one result is an object, several are an array
--explain on holds, proved, or vacuous checks, extract the minimal unsat core
of rules that established the verdict
--brief omit empty relations and ordering helpers from text output
--summary print one compact Markdown table across all checks (and JSON summary)
--climb climb scopes automatically under the conflict budget until a hole is
found or the budget runs out
--induction [K] prove `always P` for any number of steps by k-induction (default K=1);
falls back to bounded traces if the inductive step does not close
--no-slicing solve every check whole, without first slicing away what the
assertion cannot see: slower, and the reference answer
--scope N the scope of every top-level signature the command does not name
--steps N at most N states in a trace
--budget N at most N solver conflicts per solve (default 10000000)
--timeout DUR wall-clock time limit per solve (e.g. `500ms`, `30s`, `2m`)
exit status: 0 all hold/proved (or every `expect` is met); 1 a counterexample (or an `expect` is not met); 2 unknown or vacuous; 3 errors.";
const RUN_HELP: &str =
"elinvar run FILE [NAME] [--with FILE] [--from-any] [--tables A,B [--with-referencing]] [--shrink] [--all [--limit N] [--sql]] [--json] [--explain] [--brief] [--scope N] [--steps N] [--budget N] [--timeout DUR]
Runs every `run` command of FILE (an Alloy 6 model or `.sql` schema), or only
the one named NAME (its label, or the predicate it runs), and shows an instance
of the facts and the predicate, or says there is none up to the scope.
For a `.sql` schema, traces start from empty tables by default (`--from-empty`);
pass `--from-any` to start from any state the schema's rules allow.
With `--with FILE`, appends sidecar `.als` predicates/commands or `.sql` views.
With `--shrink`, shrinks the found instance to the fewest atoms and tuples.
With `--explain`, when there is no instance, names the minimal set of rules
that, with the run's predicate, allows none.
With `--all`, enumerates every non-isomorphic instance up to the scope (capped at
`--limit N`, default 1000). With `--sql`, renders each instance as SQL inserts.
exit status: 0 found; 1 none; 2 unknown; 3 errors.";
const TESTS_HELP: &str =
"elinvar tests FILE [--with FILE] [--json] [--sql] [--tables A,B [--with-referencing]] [--values SPEC] [--allow-dead S1,S2] [--scope N] [--steps N] [--budget N] [--timeout DUR]
Generates step reachability and per-guard refusal tests from a model with steps
(or a `.sql` schema, imported with `--temporal --from-empty`):
- For each step: the shortest trace in which it fires (or flags it as a dead step).
- For each guard condition of each step: the shortest trace where that condition
alone refuses the step (or flags it as unreachable / redundant).
In text mode, each test is printed as soon as it finishes; `--budget N` bounds
each test individually and names any unfinished tests at the end.
flags:
--with FILE append sidecar `.als` promises/pragmas or `.sql` views (repeatable)
--sql render each test case as an executable SQL replay script
--tables A,B for a `.sql` schema, test only these tables and their FK targets
--with-referencing with `--tables`, also include tables pointing into the slice
--values SPEC sample values for SQL columns (`table.col=v1,v2` or `@file`, repeatable)
--allow-dead S1,S2 steps expected to be dead (exit 0); also read from `-- expect-dead:` comments
--scope N scope per top-level signature (default 3)
--steps N at most N states per trace (default 5 for `.sql`, 4 for `.als`)
--budget N at most N solver conflicts per test
--timeout DUR wall-clock time limit per test (e.g. `500ms`, `30s`, `2m`)
--json print all results as one JSON document
exit status: 0 all steps reachable (or expected dead) and all guards decide; 1 unexpected dead step or unreachable guard; 2 not reached within steps or unknown; 3 errors.";
const ACCEPTS_HELP: &str =
"elinvar accepts FILE TRACE [--with FILE] [--tables A,B [--with-referencing]] [--json]
Checks whether TRACE (a result/trace JSON file, or a SQL script of INSERT/UPDATE/DELETE
statements) is allowed by FILE (an Alloy 6 model or a `.sql` schema) and whether every
`check` promise in FILE (and any `--with` sidecar) holds along it.
exit status: 0 trace is allowed and every check holds; 1 refused or a check breaks; 3 errors.";
const FUZZ_HELP: &str =
"elinvar fuzz FILE [--against CMD] [--seed N] [--scripts N] [--length N] [--require-coverage] [--with FILE] [--tables A,B [--with-referencing]] [--timeout DUR] [--json]
Generates seeded random SQL DML scripts (`INSERT`, `UPDATE`, `DELETE`) from a
`.sql` schema in foreign-key dependency order, runs every statement against both
the real database (`--against`, default `sqlite3`) and Elinvar's imported model,
and shrinks the first statement they judge differently.
flags:
--against CMD external database CLI (default `sqlite3`; e.g. `sqlite3` or `psql mydb`)
--seed N deterministic random seed (default 1)
--scripts N number of random scripts to test (default 100)
--length N statements per script (default 8)
--require-coverage exit 2 if any table received 0 rows or any read rule never fired
--with FILE append sidecar `.als` or `.sql` views/queries (repeatable)
--tables A,B import only these tables and their FK targets
--with-referencing with `--tables`, also include tables pointing into the slice
--timeout DUR wall-clock time limit for the fuzz run (e.g. `30s`, `2m`)
--json print the result as JSON (schema: `elinvar explain schema:fuzz`)
exit status: 0 all scripts agreed; 1 shrunk disagreement found; 2 timeout or incomplete coverage; 3 errors.";
const DISCOVER_HELP: &str =
"elinvar discover FILE [--with FILE] [--tables A,B [--with-referencing]] [--show-rejected] [--scope N] [--budget N] [--timeout DUR] [--json]
Tries common database invariants on each table of FILE (a `.sql` schema):
- rows never deleted (append-only)
- rows never deleted while referenced by a child table
- columns never changing after insert, never changing once set, never cleared,
always present, non-decreasing, or unique across live rows
- at most one open/active row per key (nullable marker column unset)
Keeps only the invariants proved for any number of steps within scope by
k-induction, and prints each in plain English together with the triggers and
rules it rests on.
flags:
--with FILE append sidecar `.als` rules or `.sql` views/queries (repeatable)
--tables A,B discover invariants only on these tables (importing their FK targets)
--with-referencing with `--tables`, also include tables pointing into the slice
--show-rejected also print candidates that failed, each with its counterexample
--scope N scope per top-level signature (default 3)
--budget N at most N solver conflicts per candidate (default 200000)
--timeout DUR wall-clock time limit for the discovery run (e.g. `30s`, `2m`)
--json print the result as JSON (schema: `elinvar explain schema:discover`)
exit status: 0 all candidates finished; 2 some candidates did not finish within budget/timeout; 3 errors.";
const DIFF_HELP: &str =
"elinvar diff OLD NEW [--with FILE] [--from-any | --from-empty] [--of FUN] [--tables A,B [--with-referencing]] [--ignore-unread] [--no-slicing] [--json] [--scope N] [--steps N] [--budget N] [--timeout DUR]
elinvar diff BASE --migration MIG.sql [...]
Compares two Alloy 6 models sharing the same signatures and fields, or two
`.sql` schemas (or directories of ordered `.sql` migration files; with
`--migration MIG.sql`, compares BASE against BASE plus MIG.sql). Unread rules
identical on both sides are listed once under `unchanged_skipped`, while changed
unread rules stop with `sql.skipped` unless `--ignore-unread` is passed. Finds a
minimal shrunk instance or trace allowed by OLD and forbidden by NEW (tightened),
and one allowed by NEW and forbidden by OLD (loosened).
With `--of FUN`, compares the tuples returned by function or query FUN across
cases allowed by both models, showing tuples lost or gained by NEW.
Verdicts:
equivalent both models (or functions) agree up to the scope
tightened NEW forbids at least one case (or drops a tuple) OLD allows
loosened NEW allows at least one case (or gains a tuple) OLD forbids
diverged each side allows a case (or tuple) the other lacks
unknown the budget ran out first
vacuous with `--of`, the two models together allow no case, so there is
nothing to compare the functions on: fix the rules
flags:
--migration FILE apply SQL migration FILE on top of BASE and diff BASE vs BASE+FILE
--with FILE append sidecar `.als` or `.sql` views/queries to both sides (repeatable)
--from-any for `.sql` schemas, compare transitions from any allowed state (default on `diff`, 2 steps)
--from-empty for `.sql` schemas, start traces from empty tables (4 steps by default)
--of FUN compare one function, view, parameterized predicate, or expression
--tables A,B for `.sql` schemas, compare only these tables plus their FK
and trigger targets
--with-referencing with `--tables`, also include tables pointing into the slice
--ignore-unread for `.sql` schemas, compare what is read and list differing unread
rules under `not_compared` (exits 2 so unread changes are never silent)
--no-slicing solve each side whole, without slicing or reductions: slower,
and the reference answer
--json print the diff report as JSON
--scope N the scope of every top-level signature (default 3)
--steps N at most N states in a trace
--budget N at most N solver conflicts per solve
--timeout DUR wall-clock time limit per solve (e.g. `500ms`, `30s`, `2m`)
exit status: 0 equivalent; 1 tightened, loosened, or diverged; 2 unknown, vacuous, or not_compared; 3 errors.";
const IMPORT_HELP: &str =
"elinvar import FILE|DIR [--with FILE] [--json] [--strict] [--temporal [--from-empty | --from-any]] [--tables A,B [--with-referencing]] [--only-ruled]
Reads SQL DDL (CREATE TABLE, CREATE TYPE ... AS ENUM, ALTER TABLE, DROP TABLE/INDEX/TRIGGER,
CREATE UNIQUE INDEX, PRIMARY KEY, NOT NULL, UNIQUE, FOREIGN KEY / REFERENCES, CHECK
constraints, and with `--temporal`, CREATE TRIGGER statements) from FILE (or a directory
of ordered `*.sql` migration files) and emits an Alloy 6 model in Elinvar's subset.
With `--with FILE`, appends sidecar `.sql` views/queries and `.als` promises/predicates.
With `--temporal`, traces start from any allowed state by default (`--from-any`); pass
`--from-empty` to require all tables to start empty.
Any statement or constraint not carried into the model is noted as a `-- not
read` comment, listed under `skipped` in `--json`, and summarized on stderr.
flags:
--json print `{ elinvar, tables, skipped, ignored, outside_referencing_tables, dropped_triggers, sample_values, views, model }` as JSON (`views` only when there are some; `elinvar explain schema:import`)
--strict fail with exit 3 if any SQL rule was skipped (non-rule statements
such as `CREATE INDEX` and `PRAGMA` are listed under `ignored`)
--temporal emit stateful `var` tables, insert/update/delete steps, and triggers
--from-empty with `--temporal`, require all tables to start empty so every state
is reached by guarded steps
--tables A,B import only these tables and those they reference via foreign keys
--with-referencing with `--tables`, also include tables that point into the slice via FKs
--only-ruled omit columns not mentioned in any key, index, constraint, or trigger
exit status: 0 imported; 3 errors (or skipped rules with `--strict`).";
const RENDER_HELP: &str =
"elinvar render FILE [--format dot|mermaid|sql] [--dot] [--mermaid] [--sql] [--state K] [--values SPEC] [--json]
Renders either:
- a result JSON file from `elinvar check --json` or `elinvar run --json`, as
Graphviz DOT (default), Mermaid, or executable SQL replay statements (`--sql`), or
- an Alloy model (`.als`) or SQL schema (`.sql`), as a DOT or Mermaid overview of
its signatures, `var` relations, `extends` hierarchy, fields, and step predicates.
flags:
--format FMT output format: `dot` (default), `mermaid`, or `sql`
--dot shorthand for `--format dot`
--mermaid shorthand for `--format mermaid`
--sql shorthand for `--format sql` (result JSON only)
--state K for a trace result, render only state K (from 0)
--values SPEC sample column values for `--sql` (`table.col=v1,v2` or `@file`, repeatable)
--json print `{ elinvar, format, diagram, ... }` as JSON
exit status: 0 rendered; 3 errors.";
const EVAL_HELP: &str = "elinvar eval FILE RESULT EXPR [--state K] [--with FILE] [--tables A,B [--with-referencing]] [--json]
Evaluates EXPR, an expression or a formula in the model of FILE (an Alloy `.als`
model, a `.sql` schema, or a SQL migrations directory), on the instance or trace
of RESULT, a file with the JSON of one result of `elinvar check --json` or
`elinvar run --json` for that model. Relations are matched by name. With a trace,
--state K picks the state, from 0 (default 0).
An expression prints its tuples, `{A, B}` or `{A -> B}`; a formula prints `true`
or `false`.
flags:
--state K for a trace result, evaluate at state K (from 0, default 0)
--with FILE append sidecar `.als` promises or `.sql` views/queries (repeatable)
--tables A,B narrow a `.sql` schema to these tables and their FK targets
--with-referencing with `--tables`, also include tables pointing into the slice
--json print the evaluated result as JSON (schema: `elinvar explain schema:eval`)
exit status: 0 evaluated; 3 errors.";
const AUDIT_HELP: &str =
"elinvar audit SCHEMA --data DUMP.sql [--with FILE] [--tables A,B [--with-referencing]] [--json]
Audits the rows of a real database dump (INSERT statements from `sqlite3 .dump`
or `pg_dump --inserts`) as one state against SCHEMA (a `.sql` file or migrations
directory) and any sidecar `--with promises.als` / `.sql` views.
Evaluates every table rule (NOT NULL, PRIMARY KEY, UNIQUE, partial UNIQUE,
FOREIGN KEY, CHECK, enum) and every single-state promise directly without
invoking the SAT solver (R7). Multi-step temporal promises are listed under
`skipped_promises`.
What the dump holds and the audit does not read is a warning: rows of a table
not in SCHEMA or its `--tables` slice (`audit.dropped_rows`), a statement that
is not an INSERT, such as `COPY` or `UPDATE` (`audit.ignored_statement`), and a
dump with no INSERT at all (`audit.no_rows`). A file with no INSERT and other
text is not a dump, and is an error (`audit.parse`).
flags:
--data FILE SQL dump file containing INSERT statements (required; `-` for stdin)
--with FILE append sidecar `.als` promises or `.sql` views/queries (repeatable)
--tables A,B audit only these tables and their FK targets
--with-referencing with `--tables`, also include tables pointing into the slice
--json print the audit report as JSON (schema: `elinvar explain schema:audit`)
exit status: 0 all rules and promises hold; 1 at least one rule or promise was broken; 3 errors.";
const CI_HELP: &str =
"elinvar ci [MANIFEST] [--timeout DUR] [--junit | --sarif | --json]
Runs every entry (`[[check]]`, `[[run]]`, `[[accepts]]`, `[[diff]]`,
`[[discover]]`, `[[tests]]`) in MANIFEST (default `elinvar.toml`) under one
shared wall-clock time limit, checking each entry against its `expect` verdict.
Outputs a Markdown summary table by default, or JUnit XML (`--junit`),
SARIF 2.1.0 (`--sarif`), or JSON (`--json`, schema: `elinvar explain schema:ci`).
flags:
--timeout DUR shared wall-clock time limit overriding manifest `timeout` (e.g. `60s`, `5m`)
--junit write a JUnit XML report
--sarif write a SARIF 2.1.0 report
--json print the full CI report as JSON
exit status: 0 all entries met expectations; 1 at least one entry failed; 2 at least one timed out / unknown; 3 manifest or argument error.";
const EXPLAIN_HELP: &str = "elinvar explain [CODE | schema[:NAME] | skill] [--json]
With a code, such as `arity.mismatch`, says when it is raised and how to fix it.
With `schema:<name>` (`schema:result`, `schema:diff`, `schema:import`, `schema:render`,
`schema:eval`, `schema:tests`, `schema:accepts`, `schema:fuzz`, `schema:discover`,
`schema:ci`, `schema:audit`), prints that verb's JSON Schema; with `schema`, lists all schemas. With
`skill`, prints the embedded agent guide (SKILL.md). With nothing, lists every code.";
const SERVE_HELP: &str = "elinvar serve --mcp
Serves the Model Context Protocol over stdin and stdout, one JSON-RPC message per
line. Exposes tools (check, run, tests, accepts, discover, audit, diff, import_sql,
render, eval, explain), server instructions on initialize, and resources
(`skill://elinvar/SKILL.md` and `elinvar://schema/<verb>-v1.json`). The server
keeps no state between calls.";
struct Args {
positional: Vec<String>,
json: bool,
help: bool,
mcp: bool,
strict: bool,
temporal: bool,
from_empty: bool,
from_any: bool,
tables: Vec<String>,
with_files: Vec<String>,
with_referencing: bool,
only_ruled: bool,
values: Vec<String>,
allow_dead: Vec<String>,
all: bool,
limit: Option<usize>,
diff_of: Option<String>,
migration: Option<String>,
data_file: Option<String>,
against: Option<String>,
seed: Option<u64>,
scripts: Option<usize>,
length: Option<usize>,
require_coverage: bool,
show_rejected: bool,
junit: bool,
sarif: bool,
over: Overrides,
state: Option<usize>,
format: elinvar::DiagramFormat,
format_set: bool,
}
fn parse(args: &[String]) -> Result<Args, String> {
let mut a = Args {
positional: Vec::new(),
json: false,
help: false,
mcp: false,
strict: false,
temporal: false,
from_empty: false,
from_any: false,
tables: Vec::new(),
with_files: Vec::new(),
with_referencing: false,
only_ruled: false,
values: Vec::new(),
allow_dead: Vec::new(),
all: false,
limit: None,
diff_of: None,
migration: None,
data_file: None,
against: None,
seed: None,
scripts: None,
length: None,
require_coverage: false,
show_rejected: false,
junit: false,
sarif: false,
over: Overrides::default(),
state: None,
format: elinvar::DiagramFormat::Dot,
format_set: false,
};
let mut it = args.iter().peekable();
while let Some(x) = it.next() {
let mut number = |flag: &str| -> Result<usize, String> {
it.next()
.and_then(|v| v.parse().ok())
.ok_or_else(|| format!("{flag} needs a number"))
};
match x.as_str() {
"--json" => a.json = true,
"--explain" => a.over.explain = true,
"--brief" => a.over.brief = true,
"--climb" => a.over.climb = true,
"--no-slicing" => a.over.no_slicing = true,
"--summary" => a.over.summary = true,
"--shrink" => a.over.shrink = true,
"--all" => a.all = true,
"--limit" => a.limit = Some(number("--limit")?),
"--of" => {
let name = it
.next()
.ok_or("--of needs a function name or expression")?;
a.diff_of = Some(name.clone());
}
"--migration" => {
let path = it.next().ok_or("--migration needs a SQL file path")?;
a.migration = Some(path.clone());
}
"--data" => {
let path = it.next().ok_or("--data needs a SQL dump file path")?;
a.data_file = Some(path.clone());
}
"--against" => {
let cmd = it
.next()
.ok_or("--against needs a database command (for example `sqlite3`)")?;
a.against = Some(cmd.clone());
}
"--seed" => a.seed = Some(number("--seed")? as u64),
"--scripts" => a.scripts = Some(number("--scripts")?),
"--length" => a.length = Some(number("--length")?),
"--require-coverage" => a.require_coverage = true,
"--show-rejected" => a.show_rejected = true,
"--junit" => a.junit = true,
"--sarif" => a.sarif = true,
"--ignore-unread" => a.over.ignore_unread = true,
"--help" | "-h" => a.help = true,
"--mcp" => a.mcp = true,
"--strict" => a.strict = true,
"--temporal" => a.temporal = true,
"--from-empty" => {
a.from_empty = true;
a.over.from_empty = true;
}
"--from-any" => {
a.from_any = true;
a.over.from_any = true;
}
"--with" => {
let path = it.next().ok_or("--with needs a file path")?;
a.with_files.push(path.clone());
}
"--with-referencing" => a.with_referencing = true,
"--only-ruled" => a.only_ruled = true,
"--values" => {
let raw = it
.next()
.ok_or("--values needs `table.col=val1,val2` or `@file`")?;
a.values.push(raw.clone());
}
"--allow-dead" => {
let raw = it
.next()
.ok_or("--allow-dead needs a comma-separated list of step names")?;
for part in raw.split(',') {
let s = part.trim();
if !s.is_empty() {
a.allow_dead.push(s.to_string());
}
}
}
"--tables" => {
let raw = it
.next()
.ok_or("--tables needs a comma-separated list of table names")?;
for part in raw.split(',') {
let t = part.trim();
if !t.is_empty() {
a.tables.push(t.to_string());
}
}
if a.tables.is_empty() {
return Err("--tables needs at least one table name".to_string());
}
}
"--dot" => {
a.format = elinvar::DiagramFormat::Dot;
a.format_set = true;
}
"--mermaid" => {
a.format = elinvar::DiagramFormat::Mermaid;
a.format_set = true;
}
"--sql" => {
a.format = elinvar::DiagramFormat::Sql;
a.format_set = true;
}
"--format" => {
let name = it
.next()
.ok_or("--format needs `dot`, `mermaid`, or `sql`")?;
a.format = verbs::diagram_format(name).ok_or_else(|| {
format!("unknown format `{name}` (use `dot`, `mermaid`, or `sql`)")
})?;
a.format_set = true;
}
"--scope" => a.over.scope = Some(number("--scope")?),
"--steps" => a.over.steps = Some(number("--steps")?),
"--budget" => a.over.budget = Some(number("--budget")? as u64),
"--timeout" => {
let raw = it
.next()
.ok_or("--timeout needs a duration (e.g. `500ms`, `30s`, `2m`)")?;
a.over.timeout_ms = Some(verbs::parse_duration_ms(raw)?);
}
"--induction" => {
let k = if let Some(next) = it.peek()
&& let Ok(n) = next.parse::<usize>()
&& n >= 1
{
let _ = it.next();
n
} else {
1
};
a.over.inductive = Some(k);
}
"--state" => a.state = Some(number("--state")?),
f if f.starts_with('-') && f.len() > 1 => return Err(format!("unknown flag `{f}`")),
_ => a.positional.push(x.clone()),
}
}
Ok(a)
}
fn validate_flags(verb: &str, a: &Args) -> Result<(), String> {
if a.over.explain && verb != "check" && verb != "run" {
return Err(format!(
"`--explain` is only valid for `check` and `run`, not `{verb}`"
));
}
if a.over.inductive.is_some() && verb != "check" {
return Err(format!(
"`--induction` is only valid for `check`, not `{verb}`"
));
}
if a.over.climb && verb != "check" {
return Err(format!("`--climb` is only valid for `check`, not `{verb}`"));
}
if a.over.no_slicing && !matches!(verb, "check" | "diff") {
return Err(format!(
"`--no-slicing` is only valid for `check` and `diff`, not `{verb}`"
));
}
if a.over.summary && verb != "check" {
return Err(format!(
"`--summary` is only valid for `check`, not `{verb}`"
));
}
if a.over.shrink && verb != "run" {
return Err(format!("`--shrink` is only valid for `run`, not `{verb}`"));
}
if a.diff_of.is_some() && verb != "diff" {
return Err(format!("`--of` is only valid for `diff`, not `{verb}`"));
}
if a.migration.is_some() && verb != "diff" {
return Err(format!(
"`--migration` is only valid for `diff`, not `{verb}`"
));
}
if a.data_file.is_some() && verb != "audit" {
return Err(format!("`--data` is only valid for `audit`, not `{verb}`"));
}
if a.over.ignore_unread && verb != "diff" {
return Err(format!(
"`--ignore-unread` is only valid for `diff`, not `{verb}`"
));
}
if (a.junit || a.sarif) && verb != "ci" {
return Err(format!(
"`--junit` and `--sarif` are only valid for `ci`, not `{verb}`"
));
}
if a.junit && a.sarif {
return Err("cannot pass both `--junit` and `--sarif`".to_string());
}
if (a.junit || a.sarif) && a.json {
return Err("cannot combine `--junit` or `--sarif` with `--json`".to_string());
}
if a.over.brief && !matches!(verb, "check" | "run") {
return Err(format!(
"`--brief` is only valid for `check` and `run`, not `{verb}`"
));
}
if (a.over.scope.is_some() || a.over.budget.is_some())
&& !matches!(verb, "check" | "run" | "diff" | "tests" | "discover")
{
return Err(format!(
"`--scope` and `--budget` are not valid for `{verb}`"
));
}
if a.over.steps.is_some() && !matches!(verb, "check" | "run" | "diff" | "tests") {
return Err(format!("`--steps` is not valid for `{verb}`"));
}
if a.over.timeout_ms.is_some()
&& !matches!(
verb,
"check" | "run" | "diff" | "tests" | "fuzz" | "discover" | "ci"
)
{
return Err(format!("`--timeout` is not valid for `{verb}`"));
}
if (a.against.is_some()
|| a.seed.is_some()
|| a.scripts.is_some()
|| a.length.is_some()
|| a.require_coverage)
&& verb != "fuzz"
{
return Err(format!(
"`--against`, `--seed`, `--scripts`, `--length`, and `--require-coverage` are only valid for `fuzz`, not `{verb}`"
));
}
if a.show_rejected && verb != "discover" {
return Err(format!(
"`--show-rejected` is only valid for `discover`, not `{verb}`"
));
}
if (a.all || a.limit.is_some()) && verb != "run" {
return Err(format!(
"`--all` and `--limit` are only valid for `run`, not `{verb}`"
));
}
if a.limit.is_some() && !a.all {
return Err("`--limit` requires `--all`".to_string());
}
if a.all && a.over.explain {
return Err(
"`--explain` explains a run with no instance; `--all` lists instances, so they do not go together"
.to_string(),
);
}
if verb == "run" && a.format_set && a.format == elinvar::DiagramFormat::Sql && !a.all {
return Err("`--sql` on `run` requires `--all`".to_string());
}
if a.format_set {
let sql_on_other =
a.format == elinvar::DiagramFormat::Sql && matches!(verb, "tests" | "run");
if verb != "render" && !sql_on_other {
return Err(format!(
"`--format`, `--dot`, `--mermaid`, and `--sql` are not valid for `{verb}`"
));
}
}
if a.state.is_some() && !matches!(verb, "eval" | "render") {
return Err(format!(
"`--state` is only valid for `eval` and `render`, not `{verb}`"
));
}
if a.mcp && verb != "serve" {
return Err(format!("`--mcp` is only valid for `serve`, not `{verb}`"));
}
if (a.strict || a.temporal || a.only_ruled) && verb != "import" {
return Err(format!(
"`--strict`, `--temporal`, and `--only-ruled` are only valid for `import`, not `{verb}`"
));
}
if a.from_empty && a.from_any {
return Err("`--from-empty` and `--from-any` cannot both be set".to_string());
}
if a.from_empty && !matches!(verb, "import" | "check" | "run" | "diff") {
return Err(format!(
"`--from-empty` is only valid for `import`, `check`, `run`, and `diff`, not `{verb}`"
));
}
if a.from_any && !matches!(verb, "import" | "check" | "run" | "diff") {
return Err(format!(
"`--from-any` is only valid for `import`, `check`, `run`, and `diff`, not `{verb}`"
));
}
if verb == "import" && (a.from_empty || a.from_any) && !a.temporal {
return Err("`--from-empty` and `--from-any` on `import` require `--temporal`".to_string());
}
if a.with_referencing && a.tables.is_empty() {
return Err("`--with-referencing` requires `--tables`".to_string());
}
if (!a.tables.is_empty() || a.with_referencing)
&& !matches!(
verb,
"import"
| "tests"
| "diff"
| "check"
| "run"
| "accepts"
| "fuzz"
| "discover"
| "audit"
| "eval"
)
{
return Err(format!(
"`--tables` and `--with-referencing` are not valid for `{verb}`"
));
}
if !a.with_files.is_empty()
&& !matches!(
verb,
"check"
| "run"
| "tests"
| "diff"
| "accepts"
| "import"
| "fuzz"
| "discover"
| "audit"
| "eval"
)
{
return Err(format!("`--with` is not valid for `{verb}`"));
}
if !a.values.is_empty() && !matches!(verb, "tests" | "render") {
return Err(format!(
"`--values` is only valid for `tests` and `render`, not `{verb}`"
));
}
if !a.allow_dead.is_empty() && verb != "tests" {
return Err(format!(
"`--allow-dead` is only valid for `tests`, not `{verb}`"
));
}
Ok(())
}
fn parse_sample_values(
specs: &[String],
) -> Result<std::collections::BTreeMap<String, Vec<String>>, Refusal> {
let mut out: std::collections::BTreeMap<String, Vec<String>> =
std::collections::BTreeMap::new();
let mut parse_line = |raw: &str| -> Result<(), String> {
let t = raw.trim();
if t.is_empty() || t.starts_with('#') || t.starts_with("--") {
return Ok(());
}
let (key, vals_raw) = t.split_once('=').ok_or_else(|| {
format!("malformed `--values` entry `{t}` (expected `table.col=v1,v2`)")
})?;
let k = key.trim().to_ascii_lowercase();
let vals: Vec<String> = vals_raw
.split(',')
.map(|v| v.trim().to_string())
.filter(|v| !v.is_empty())
.collect();
if k.is_empty() || vals.is_empty() {
return Err(format!(
"malformed `--values` entry `{t}` (expected `table.col=v1,v2`)"
));
}
out.entry(k).or_default().extend(vals);
Ok(())
};
for spec in specs {
if let Some(path) = spec.strip_prefix('@') {
let body = read(path)?;
for line in body.lines() {
parse_line(line)?;
}
} else {
parse_line(spec)?;
}
}
Ok(out)
}
fn is_sql_input(path: &str) -> bool {
path.ends_with(".sql") || (path != "-" && std::path::Path::new(path).is_dir())
}
fn sql_display_path(path: &str) -> String {
if path == "-" {
"<stdin>".to_string()
} else if std::path::Path::new(path).is_dir() {
format!("{}.sql", path.trim_end_matches('/'))
} else {
path.to_string()
}
}
fn read(path: &str) -> Result<String, Refusal> {
if path == "-" {
let mut buf = String::new();
std::io::stdin()
.read_to_string(&mut buf)
.map_err(|e| Refusal::input(format!("cannot read stdin: {e}")))?;
Ok(buf)
} else if std::path::Path::new(path).is_dir() {
elinvar::cli::migrations::read(std::path::Path::new(path)).map_err(Refusal::input)
} else {
std::fs::read_to_string(path)
.map_err(|e| Refusal::input(format!("cannot read `{path}`: {e}")))
}
}
fn parse_json(text: &str, path: &str) -> Result<serde_json::Value, Refusal> {
serde_json::from_str(text)
.map_err(|e| Refusal::input(format!("`{}` is not JSON: {e}", display_path(path))))
}
fn verb_help(verb: &str) -> Option<&'static str> {
Some(match verb {
"check" => CHECK_HELP,
"run" => RUN_HELP,
"tests" => TESTS_HELP,
"accepts" => ACCEPTS_HELP,
"fuzz" => FUZZ_HELP,
"discover" => DISCOVER_HELP,
"audit" => AUDIT_HELP,
"ci" => CI_HELP,
"diff" => DIFF_HELP,
"import" => IMPORT_HELP,
"render" => RENDER_HELP,
"eval" => EVAL_HELP,
"explain" => EXPLAIN_HELP,
"serve" => SERVE_HELP,
_ => return None,
})
}
fn display_path(path: &str) -> &str {
if path == "-" { "<stdin>" } else { path }
}
fn load_sidecars(paths: &[String]) -> Result<(String, Option<String>), Refusal> {
let mut extra_sql = String::new();
let mut extra_als = String::new();
for path in paths {
let body = read(path)?;
if path.ends_with(".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))
}
fn read_pair(a: &str, b: &str) -> Result<(String, String), Refusal> {
if a == "-" && b == "-" {
return Err(Refusal::from("cannot read both inputs from stdin (`-`)"));
}
Ok((read(a)?, read(b)?))
}
fn print(out: &Output, json: bool) -> ExitCode {
let mut stdout = std::io::stdout().lock();
let _ = if json {
let mut v = out.json.clone();
elinvar::cli::migrations::remap_json(&mut v);
writeln!(
stdout,
"{}",
serde_json::to_string_pretty(&v).unwrap_or_default()
)
} else {
write!(
stdout,
"{}",
elinvar::cli::migrations::remap_text(&out.text)
)
};
ExitCode::from(out.status)
}
struct ProgressReporter {
state: std::sync::Arc<(std::sync::Mutex<(bool, String)>, std::sync::Condvar)>,
thread: Option<std::thread::JoinHandle<()>>,
}
impl ProgressReporter {
fn start(initial: String) -> Self {
let state = std::sync::Arc::new((
std::sync::Mutex::new((false, initial)),
std::sync::Condvar::new(),
));
let bg = std::sync::Arc::clone(&state);
let started = std::time::Instant::now();
let thread = std::thread::spawn(move || {
let (lock, cvar) = &*bg;
let mut guard = match lock.lock() {
Ok(g) => g,
Err(_) => return,
};
let interval = std::time::Duration::from_secs(3);
while !guard.0 {
let (g, timeout) = match cvar.wait_timeout(guard, interval) {
Ok(pair) => pair,
Err(_) => return,
};
guard = g;
if guard.0 {
break;
}
if timeout.timed_out() {
let secs = started.elapsed().as_secs();
eprintln!("[elinvar] {} ({secs}s elapsed)...", guard.1);
}
}
});
ProgressReporter {
state,
thread: Some(thread),
}
}
fn set(&self, status: &str) {
if let Ok(mut guard) = self.state.0.lock() {
guard.1.clear();
guard.1.push_str(status);
}
}
}
impl Drop for ProgressReporter {
fn drop(&mut self) {
if let Ok(mut guard) = self.state.0.lock() {
guard.0 = true;
self.state.1.notify_all();
}
if let Some(handle) = self.thread.take() {
let _ = handle.join();
}
}
}
struct Refusal {
code: &'static str,
message: String,
}
impl Refusal {
fn input(message: String) -> Refusal {
Refusal {
code: "cli.input",
message,
}
}
}
impl From<String> for Refusal {
fn from(message: String) -> Refusal {
Refusal {
code: "cli.usage",
message,
}
}
}
impl From<&String> for Refusal {
fn from(message: &String) -> Refusal {
Refusal::from(message.clone())
}
}
impl From<&str> for Refusal {
fn from(message: &str) -> Refusal {
Refusal::from(message.to_string())
}
}
impl From<&Refusal> for Refusal {
fn from(r: &Refusal) -> Refusal {
Refusal {
code: r.code,
message: r.message.clone(),
}
}
}
fn usage(refusal: impl Into<Refusal>, help: &str, json: bool) -> ExitCode {
let Refusal { code, message } = refusal.into();
if json {
let body = serde_json::json!({
"elinvar": 1,
"code": code,
"error": message,
"help": help,
});
let mut stdout = std::io::stdout().lock();
let _ = writeln!(
stdout,
"{}",
serde_json::to_string_pretty(&body).unwrap_or_default()
);
} else {
eprintln!("elinvar: error[{code}]: {message}\n\n{help}");
}
ExitCode::from(3)
}
fn main() -> ExitCode {
match elinvar::cli::model_thread().spawn(run) {
Ok(handle) => handle.join().unwrap_or(ExitCode::from(101)),
Err(_) => run(),
}
}
fn run() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
let Some(verb) = args.first() else {
println!("{HELP}");
return ExitCode::SUCCESS;
};
let wants_json = args.iter().any(|x| x == "--json");
if matches!(verb.as_str(), "--version" | "-V" | "version") {
if wants_json {
let body = serde_json::json!({
"elinvar": 1,
"version": VERSION,
});
println!(
"{}",
serde_json::to_string_pretty(&body).unwrap_or_default()
);
} else {
println!("elinvar {VERSION}");
}
return ExitCode::SUCCESS;
}
let mut a = match parse(&args[1..]) {
Ok(a) => a,
Err(m) => return usage(&m, HELP, wants_json),
};
let help = verb_help(verb).unwrap_or(HELP);
if a.help && verb_help(verb).is_some() {
println!("{help}");
return ExitCode::SUCCESS;
}
if verb_help(verb).is_some()
&& let Err(m) = validate_flags(verb, &a)
{
return usage(&m, help, a.json);
}
let p: Vec<&str> = a.positional.iter().map(String::as_str).collect();
match verb.as_str() {
"--help" | "-h" | "help" => {
println!("{HELP}");
ExitCode::SUCCESS
}
"check" | "run" => {
let (file, name) = match p[..] {
[f] => (f, None),
[f, n] => (f, Some(n)),
_ => return usage("expected FILE and an optional NAME", help, a.json),
};
let raw_text = match read(file) {
Ok(t) => t,
Err(m) => return usage(&m, help, a.json),
};
let (extra_sql, extra_als) = match load_sidecars(&a.with_files) {
Ok(pair) => pair,
Err(m) => return usage(&m, help, a.json),
};
let verb: &'static str = if verb == "check" { "check" } else { "run" };
let file_disp = sql_display_path(file);
let is_sql = is_sql_input(file);
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,
&file_disp,
&full_sql,
extra_als.as_deref(),
&a.tables,
a.with_referencing,
!a.from_any,
) {
Ok((m, bw)) => {
a.over.default_bitwidth = Some(bw);
m
}
Err(out) => return print(&out, a.json),
}
} else if let Some(extra) = extra_als {
format!("{raw_text}\n{extra}\n")
} else {
raw_text
};
let allow_local = file != "-" && !is_sql;
let progress = ProgressReporter::start(format!("{verb} {}", display_path(file)));
let out = if verb == "run" && a.all {
let as_sql = a.format_set && a.format == elinvar::DiagramFormat::Sql;
verbs::run_all(
display_path(file),
&text,
name,
a.over,
as_sql,
a.limit.unwrap_or(1000),
allow_local,
)
} else {
verbs::solve_with_progress(
verb,
display_path(file),
&text,
name,
a.over,
allow_local,
&|msg| progress.set(msg),
)
};
drop(progress);
print(&out, a.json)
}
"tests" => {
let [file] = p[..] else {
return usage("expected FILE", help, a.json);
};
let raw_text = match read(file) {
Ok(t) => t,
Err(m) => return usage(&m, help, a.json),
};
let (extra_sql, extra_als) = match load_sidecars(&a.with_files) {
Ok(pair) => pair,
Err(m) => return usage(&m, help, a.json),
};
let file_disp = sql_display_path(file);
let is_sql = is_sql_input(file);
let text = if is_sql && !extra_sql.is_empty() {
format!("{raw_text}\n{extra_sql}")
} else {
raw_text
};
let sample_values = match parse_sample_values(&a.values) {
Ok(v) => v,
Err(m) => return usage(&m, help, a.json),
};
let as_sql = a.format_set && a.format == elinvar::DiagramFormat::Sql;
let opts = verbs::TestsOptions {
as_sql,
tables: a.tables,
with_referencing: a.with_referencing,
sample_values,
allow_dead: a.allow_dead,
extra_als,
};
if a.json {
let _progress = ProgressReporter::start(format!("tests {file_disp}"));
let out = verbs::tests_with_options(
&file_disp,
&text,
a.over,
&opts,
file != "-" && !is_sql,
None,
);
print(&out, true)
} else {
let mut stream_cb = |chunk: &str| {
let mut stdout = std::io::stdout().lock();
let _ = write!(stdout, "{chunk}");
let _ = stdout.flush();
};
let out = verbs::tests_with_options(
&file_disp,
&text,
a.over,
&opts,
file != "-" && !is_sql,
Some(&mut stream_cb),
);
if out.status == 3 {
return print(&out, false);
}
ExitCode::from(out.status)
}
}
"accepts" => {
let [file, trace_file] = p[..] else {
return usage("expected FILE and TRACE", help, a.json);
};
let (raw_text, trace_text) = match read_pair(file, trace_file) {
Ok(pair) => pair,
Err(m) => return usage(&m, help, a.json),
};
let (extra_sql, extra_als) = match load_sidecars(&a.with_files) {
Ok(pair) => pair,
Err(m) => return usage(&m, help, a.json),
};
let file_disp = sql_display_path(file);
let is_sql = is_sql_input(file);
let text = if is_sql && !extra_sql.is_empty() {
format!("{raw_text}\n{extra_sql}")
} else {
raw_text
};
let out = verbs::accepts_with_options(
&file_disp,
&text,
&trace_text,
file != "-" && !is_sql,
extra_als.as_deref(),
&a.tables,
a.with_referencing,
);
print(&out, a.json)
}
"fuzz" => {
let [file] = p[..] else {
return usage("expected FILE (a `.sql` schema)", help, a.json);
};
let raw_sql = match read(file) {
Ok(t) => t,
Err(m) => return usage(&m, help, a.json),
};
let (extra_sql, extra_als) = match load_sidecars(&a.with_files) {
Ok(pair) => pair,
Err(m) => return usage(&m, help, a.json),
};
let full_sql = if extra_sql.is_empty() {
raw_sql
} else {
format!("{raw_sql}\n{extra_sql}")
};
let opts = fuzz::FuzzOptions {
against: a.against.unwrap_or_else(|| "sqlite3".to_string()),
seed: a.seed.unwrap_or(1),
scripts: a.scripts.unwrap_or(100),
length: a.length.unwrap_or(8),
tables: a.tables,
with_referencing: a.with_referencing,
extra_als,
timeout_ms: a.over.timeout_ms,
require_coverage: a.require_coverage,
};
let progress = ProgressReporter::start(format!("fuzz {}", display_path(file)));
let out = fuzz::fuzz(
display_path(file),
&full_sql,
&opts,
Some(&|m| progress.set(m)),
);
drop(progress);
print(&out, a.json)
}
"discover" => {
let [file] = p[..] else {
return usage("expected FILE (a `.sql` schema)", help, a.json);
};
let raw_sql = match read(file) {
Ok(t) => t,
Err(m) => return usage(&m, help, a.json),
};
let (extra_sql, extra_als) = match load_sidecars(&a.with_files) {
Ok(pair) => pair,
Err(m) => return usage(&m, help, a.json),
};
let full_sql = if extra_sql.is_empty() {
raw_sql
} else {
format!("{raw_sql}\n{extra_sql}")
};
let opts = discover::DiscoverOptions {
tables: a.tables,
with_referencing: a.with_referencing,
extra_als,
scope: a.over.scope.unwrap_or(3),
budget: a.over.budget,
timeout_ms: a.over.timeout_ms,
show_rejected: a.show_rejected,
};
let progress = ProgressReporter::start(format!("discover {}", display_path(file)));
let out = discover::discover(
display_path(file),
&full_sql,
&opts,
Some(&|m| progress.set(m)),
);
drop(progress);
print(&out, a.json)
}
"audit" => {
let [schema_file] = p[..] else {
return usage(
"expected SCHEMA (a `.sql` file or migrations directory)",
help,
a.json,
);
};
let Some(data_file) = a.data_file.as_deref() else {
return usage("`audit` requires `--data DUMP.sql`", help, a.json);
};
let (raw_schema, data_sql) = match read_pair(schema_file, data_file) {
Ok(pair) => pair,
Err(m) => return usage(&m, help, a.json),
};
let (extra_sql, extra_als) = match load_sidecars(&a.with_files) {
Ok(pair) => pair,
Err(m) => return usage(&m, help, a.json),
};
let full_schema = if extra_sql.is_empty() {
raw_schema
} else {
format!("{raw_schema}\n{extra_sql}")
};
let opts = audit::AuditOptions {
tables: a.tables,
with_referencing: a.with_referencing,
extra_als,
};
let out = audit::audit(
&sql_display_path(schema_file),
&full_schema,
display_path(data_file),
&data_sql,
&opts,
);
print(&out, a.json)
}
"ci" => {
let manifest_file = match p[..] {
[] => "elinvar.toml",
[f] => f,
_ => return usage("expected at most one MANIFEST file", help, a.json),
};
let manifest_text = match read(manifest_file) {
Ok(t) => t,
Err(m) => return usage(&m, help, a.json),
};
let format = if a.junit {
Some(ci::CiFormat::Junit)
} else if a.sarif {
Some(ci::CiFormat::Sarif)
} else if a.json {
Some(ci::CiFormat::Json)
} else {
Some(ci::CiFormat::Markdown)
};
let opts = ci::CiOptions {
timeout_ms: a.over.timeout_ms,
format,
};
let progress = ProgressReporter::start(format!("ci {}", display_path(manifest_file)));
let out = ci::run_manifest(
display_path(manifest_file),
&manifest_text,
&opts,
Some(&|m| progress.set(m)),
);
drop(progress);
print(&out, a.json)
}
"diff" => {
let (old_disp, new_disp, raw_old, raw_new, old_local, new_local) =
if let Some(mig_file) = a.migration.as_deref() {
let [base_file] = p[..] else {
return usage(
"with `--migration`, expected BASE schema file or directory",
help,
a.json,
);
};
let (base_sql, mig_sql) = match read_pair(base_file, mig_file) {
Ok(pair) => pair,
Err(m) => return usage(&m, help, a.json),
};
let old_d = sql_display_path(base_file);
let new_d = format!(
"{}+{}.sql",
old_d.trim_end_matches(".sql"),
mig_file.trim_end_matches(".sql")
);
let new_sql = format!("{base_sql}\n-- migration: {mig_file}\n{mig_sql}\n");
(old_d, new_d, base_sql, new_sql, false, false)
} else {
let [old_file, new_file] = p[..] else {
return usage("expected OLD and NEW model files", help, a.json);
};
let (ro, rn) = match read_pair(old_file, new_file) {
Ok(pair) => pair,
Err(m) => return usage(&m, help, a.json),
};
(
sql_display_path(old_file),
sql_display_path(new_file),
ro,
rn,
old_file != "-" && !is_sql_input(old_file),
new_file != "-" && !is_sql_input(new_file),
)
};
let (extra_sql, extra_als) = match load_sidecars(&a.with_files) {
Ok(pair) => pair,
Err(m) => return usage(&m, help, a.json),
};
let old_text = if old_disp.ends_with(".sql") && !extra_sql.is_empty() {
format!("{raw_old}\n{extra_sql}")
} else {
raw_old
};
let new_text = if new_disp.ends_with(".sql") && !extra_sql.is_empty() {
format!("{raw_new}\n{extra_sql}")
} else {
raw_new
};
let _progress = ProgressReporter::start(format!("diff {old_disp} {new_disp}"));
let out = if let Some(fun_name) = a.diff_of.as_deref() {
verbs::diff_of_with_extra(
&old_disp,
&old_text,
old_local,
&new_disp,
&new_text,
new_local,
fun_name,
extra_als.as_deref(),
a.over,
)
} else {
verbs::diff_with_options_and_extra(
&old_disp,
&old_text,
old_local,
&new_disp,
&new_text,
new_local,
&a.tables,
a.with_referencing,
extra_als.as_deref(),
a.over,
)
};
print(&out, a.json)
}
"import" => {
let [file] = p[..] else {
return usage("expected FILE (a SQL DDL schema)", help, a.json);
};
let raw_sql = match read(file) {
Ok(t) => t,
Err(m) => return usage(&m, help, a.json),
};
let (extra_sql, extra_als) = match load_sidecars(&a.with_files) {
Ok(pair) => pair,
Err(m) => return usage(&m, help, a.json),
};
let sql = if extra_sql.is_empty() {
raw_sql
} else {
format!("{raw_sql}\n{extra_sql}")
};
let opts = elinvar_als::SqlImportOptions::new()
.temporal(a.temporal)
.from_empty(a.from_empty)
.tables(a.tables)
.with_referencing(a.with_referencing)
.only_ruled(a.only_ruled);
let (out, note) = verbs::import_sql_with_extra(
display_path(file),
&sql,
&opts,
a.strict,
extra_als.as_deref(),
);
if let Some(msg) = note {
eprintln!("{msg}");
}
print(&out, a.json)
}
"render" => {
let [input] = p[..] else {
return usage(
"expected FILE (a result JSON, `.als` model, or `.sql` schema)",
help,
a.json,
);
};
let input_text = match read(input) {
Ok(r) => r,
Err(m) => return usage(&m, help, a.json),
};
let is_model = input.ends_with(".als")
|| input.ends_with(".sql")
|| (!input.ends_with(".json") && !input_text.trim_start().starts_with('{'));
if is_model {
print(
&verbs::render_model_text(
display_path(input),
&input_text,
a.format,
input != "-",
),
a.json,
)
} else {
let sample_values = match parse_sample_values(&a.values) {
Ok(v) => v,
Err(m) => return usage(&m, help, a.json),
};
let value = match parse_json(&input_text, input) {
Ok(v) => v,
Err(m) => return usage(&m, help, a.json),
};
print(
&verbs::render_with_values(&value, a.format, a.state, &sample_values),
a.json,
)
}
}
"eval" => {
let [file, result, expr] = p[..] else {
return usage("expected FILE, RESULT, and EXPR", help, a.json);
};
let (text, result_text) = match read_pair(file, result) {
Ok(pair) => pair,
Err(m) => return usage(&m, help, a.json),
};
let (extra_sql, extra_als) = match load_sidecars(&a.with_files) {
Ok(pair) => pair,
Err(m) => return usage(&m, help, a.json),
};
let combined_text = if extra_sql.is_empty() {
text
} else {
format!("{text}\n{extra_sql}\n")
};
let extra_als_opt = extra_als.as_deref();
let value = match parse_json(&result_text, result) {
Ok(v) => v,
Err(m) => return usage(&m, help, a.json),
};
let out = verbs::eval_with_options(
&sql_display_path(file),
&combined_text,
&value,
expr,
a.state.unwrap_or(0),
extra_als_opt,
&a.tables,
a.with_referencing,
file != "-" && !is_sql_input(file),
);
print(&out, a.json)
}
"explain" => {
if p.len() > 1 {
return usage(
"expected at most one subject (CODE, schema:result, or skill)",
help,
a.json,
);
}
print(&verbs::explain(p.first().copied()), a.json)
}
"serve" => {
if !a.mcp {
return usage("`serve` needs a mode: `--mcp`", SERVE_HELP, a.json);
}
mcp::serve();
ExitCode::SUCCESS
}
other => usage(format!("unknown verb `{other}`"), HELP, a.json),
}
}