use super::contract;
use crate::cli::{meta::MetaCommand, Cli};
use crate::error::{ExitNumber, Failure, Result};
use crate::output::Envelope;
use clap::CommandFactory;
use serde_json::{json, Value};
pub fn execute(command: &MetaCommand, cli: &Cli) -> Result<Envelope> {
match command {
MetaCommand::Commands(args) => Ok(commands(args.with_globals)),
MetaCommand::Schema(args) => schema(args.command.as_deref(), args.types),
MetaCommand::Version => Ok(version()),
MetaCommand::Manual(_) => Ok(manual()),
MetaCommand::Completions(args) => completions(args.shell),
}
.map(|envelope| annotate(envelope, cli))
}
const fn annotate(envelope: Envelope, _cli: &Cli) -> Envelope {
envelope
}
fn commands(with_globals: bool) -> Envelope {
let root = Cli::command();
let mut rows = Vec::new();
collect(&root, &mut Vec::new(), &mut rows);
rows.sort_by(|left, right| left["name"].as_str().cmp(&right["name"].as_str()));
let mut data = json!({ "rows": rows });
if with_globals {
data["globals"] = global_flags(&root);
}
Envelope::new("meta commands", data)
}
fn collect(command: &clap::Command, path: &mut Vec<String>, rows: &mut Vec<Value>) {
for sub in command.get_subcommands() {
path.push(sub.get_name().to_owned());
if sub.get_subcommands().next().is_some() {
collect(sub, path, rows);
} else {
let name = path.join(" ");
let served = is_served(&name);
rows.push(json!({
"name": name,
"about": sub.get_about().map(ToString::to_string).unwrap_or_default(),
"state": if served { "served" } else { "planned" },
}));
}
path.pop();
}
}
#[must_use]
pub fn is_served(name: &str) -> bool {
super::SERVED_LEAVES.contains(&name)
}
fn global_flags(root: &clap::Command) -> Value {
let mut flags: Vec<Value> = root
.get_arguments()
.filter(|arg| arg.is_global_set())
.map(|arg| {
json!({
"name": arg.get_long().unwrap_or_else(|| arg.get_id().as_str()),
"about": arg.get_help().map(ToString::to_string).unwrap_or_default(),
})
})
.collect();
flags.sort_by(|left, right| left["name"].as_str().cmp(&right["name"].as_str()));
Value::Array(flags)
}
fn schema(command: Option<&str>, types: bool) -> Result<Envelope> {
if types {
return Ok(Envelope::new("meta schema", type_map()));
}
let Some(wanted) = command else {
let root = Cli::command();
let mut rows = Vec::new();
collect(&root, &mut Vec::new(), &mut rows);
let names: Vec<Value> = rows.into_iter().map(|row| row["name"].clone()).collect();
return Ok(Envelope::new("meta schema", json!({ "rows": names })));
};
let root = Cli::command();
let mut rows = Vec::new();
collect(&root, &mut Vec::new(), &mut rows);
let carried = actions_under(wanted, &rows);
if !carried.is_empty() {
return Ok(Envelope::new(
"meta schema",
json!({
"command": wanted,
"state": if carried.iter().all(|leaf| is_served(leaf)) { "served" } else { "planned" },
"actions": carried,
"failures": contract::failure_shape(),
"envelope": contract::envelope_shape(),
}),
));
}
if !rows.iter().any(|row| row["name"] == wanted) {
return Err(Failure::absence(
"schema.unknown_command",
format!("`{wanted}` is not a command of this product"),
)
.with_detail("detail", wanted)
.with_hint("run `meta commands` to see the published tree"));
}
let mut data = json!({
"command": wanted,
"state": if is_served(wanted) { "served" } else { "planned" },
"inputs": contract::inputs_of(&root, wanted),
"effect": contract::effect_of(wanted),
"data": contract::data_shape_of(wanted),
"failures": contract::failure_shape(),
"envelope": contract::envelope_shape(),
});
let marked = contract::marks_absence(wanted);
if !marked.is_empty() {
data["absent_when_missing"] = json!(marked);
}
Ok(Envelope::new("meta schema", data))
}
fn actions_under(wanted: &str, rows: &[Value]) -> Vec<String> {
let prefix = format!("{wanted} ");
rows.iter()
.filter_map(|row| row["name"].as_str())
.filter(|name| name.starts_with(&prefix))
.map(ToOwned::to_owned)
.collect()
}
fn type_map() -> Value {
let rows: Vec<Value> = crate::types::map::published()
.iter()
.map(|entry| {
json!({
"family": entry.family.as_str(),
"emitted": entry.shape.as_str(),
"reason": entry.note,
})
})
.collect();
json!({ "rows": rows, "notes": TYPE_MAP_NOTES })
}
const TYPE_MAP_NOTES: &[&str] = &[
"The family of a stored value comes from the type the catalogue declares \
for the column it lives in, never from the packet it arrived in: the \
result packet of this server does not tell a universal identifier or a \
network address apart from ordinary text.",
"A result column the server declares no stored origin for was produced \
rather than read, so there is no catalogue type to ask about it and its \
family comes from the packet.",
"The structured document of this server is text the server itself \
validates, and not a binary type of its own.",
"A text column with no validation declared for it is never turned into a \
structure by guessing.",
];
fn version() -> Envelope {
Envelope::new(
"meta version",
json!({
"name": env!("CARGO_PKG_NAME"),
"version": env!("CARGO_PKG_VERSION"),
"encrypted_channel_available": crate::ENCRYPTED_CHANNEL_AVAILABLE,
"crypto_provider": crate::conn::provider::PROVIDER_NAME,
"crypto_provider_audited": crate::conn::provider::PROVIDER_IS_AUDITED,
"envelope_schema_version": crate::output::SCHEMA_VERSION,
}),
)
}
fn manual() -> Envelope {
Envelope::new(
"meta manual",
json!({ "format": "roff", "page": manual_page() }),
)
.with_raw_field("page")
}
fn manual_page() -> String {
use clap_mangen::roff::{bold, roman, Roff};
let root = Cli::command();
let mut page = Vec::new();
let _ = clap_mangen::Man::new(root.clone())
.title(env!("CARGO_PKG_NAME").to_uppercase())
.section("1")
.source(concat!(
env!("CARGO_PKG_NAME"),
" ",
env!("CARGO_PKG_VERSION")
))
.manual(crate::i18n::report::prose(
crate::i18n::report::MANUAL_SECTION,
&[],
))
.render(&mut page);
let mut extra = Roff::new();
let mut rows = Vec::new();
collect(&root, &mut Vec::new(), &mut rows);
rows.sort_by(|left, right| left["name"].as_str().cmp(&right["name"].as_str()));
extra.control("SH", ["COMMANDS"]);
extra.text([roman(
"Every command this build publishes, with the state it is in. A command \
marked planned is on the surface but not served by this build, and \
answers with the usage number rather than pretending to work.",
)]);
for row in &rows {
let name = row["name"].as_str().unwrap_or_default();
let state = row["state"].as_str().unwrap_or_default();
let about = row["about"].as_str().unwrap_or_default();
extra.control("TP", []);
extra.text([bold(name), roman(format!(" ({state})"))]);
extra.text([roman(about)]);
}
extra.control("SH", ["EXIT NUMBERS"]);
extra.text([roman(
"The list is closed. A number outside it does not exist in the product.",
)]);
for (number, meaning) in EXIT_MEANINGS {
extra.control("TP", []);
extra.text([bold(number.code().to_string())]);
extra.text([roman(*meaning)]);
}
extra.control("SH", ["NOTES"]);
for (heading, text) in MANUAL_NOTES {
extra.control("TP", []);
extra.text([bold(*heading)]);
extra.text([roman(*text)]);
}
String::from_utf8_lossy(&page).into_owned() + &extra.render()
}
const EXIT_MEANINGS: &[(ExitNumber, &str)] = {
use ExitNumber::{
Absence, Authentication, BrokenPipe, Config, Conflict, Interrupted, Limit, Network,
Permission, Server, Success, Timeout, Usage, Validation,
};
&[
(Success, "Success."),
(Usage, "Incorrect use of this tool."),
(Validation, "Analysis refused the statement before sending."),
(Config, "Configuration missing or invalid."),
(Network, "The server could not be reached."),
(Authentication, "The credential was refused."),
(Permission, "The credential may not do what was asked."),
(Absence, "The requested object does not exist."),
(Conflict, "Lock conflict, deadlock or constraint."),
(Limit, "A size, row or packet ceiling was reached."),
(Server, "The server returned an error of its own."),
(Timeout, "Some phase exceeded its time budget."),
(Interrupted, "Interrupted by a signal from the caller."),
(BrokenPipe, "The output channel was closed by the reader."),
]
};
const MANUAL_NOTES: &[(&str, &str)] = &[
(
"Channels",
"The primary channel carries data only, in the published shape. \
Diagnostics, progress and warnings go to the auxiliary channel and \
never mix with data.",
),
(
"One shot",
"The process is born, does its work and dies within a single \
invocation. There is no daemon, no connection reused across \
invocations and no state that survives the process.",
),
(
"Defence against unintended change",
"Statements travel as prepared statements, so the server refuses more \
than one per call. Classification reads the syntax tree, never the \
first word. A credential restricted on the server is the only defence \
that does not depend on this tool behaving correctly.",
),
(
"Configuration",
"Every setting is written and read through the config commands. No \
setting is ever read from the process environment.",
),
(
"Encrypted channel",
"The default build carries a cryptography provider written entirely in \
Rust, so it installs on a host with no C toolchain. Run meta version \
to see which provider this build carries and whether it is audited.",
),
(
"Cutting an answer down",
"Two ceilings cut, and they cut different things. --truncate-cell \
shortens one value; --max-output-bytes bounds the whole envelope. \
There is deliberately no --truncate-content between them: it would \
name no third thing to cut and would need an order against both. \
Whatever a cut leaves out is reported under applied, so an answer that \
was shortened never reads as a complete one.",
),
(
"Reading an input",
"limits.max_input_bytes bounds what one invocation will read from a \
file or the standard input, before any of it is judged. It is not \
limits.max_statement_bytes, which bounds how large one statement may \
be: a script of many small statements is legitimate and its total is \
not a statement. Raising conn.max_packet_bytes without raising this \
one leaves the higher packet ceiling unreachable through a file, \
because the reading stops first.",
),
];
fn completions(shell: Option<crate::cli::meta::Shell>) -> Result<Envelope> {
let Some(shell) = shell else {
return Err(Failure::usage(
"meta.shell_missing",
"completion support is generated for a shell, and none was named",
)
.with_hint(
"name one of bash, zsh, fish, elvish or powershell, \
as in `meta completions bash`",
));
};
let mut root = Cli::command();
let mut script = Vec::new();
clap_complete::generate(
clap_complete::Shell::from(shell),
&mut root,
env!("CARGO_PKG_NAME"),
&mut script,
);
Ok(Envelope::new(
"meta completions",
json!({
"shell": format!("{shell:?}").to_lowercase(),
"script": String::from_utf8_lossy(&script),
}),
))
}
#[cfg(test)]
mod tests {
use super::*;
fn rows_of(envelope: &Envelope) -> &Vec<Value> {
envelope.data["rows"].as_array().expect("array payload")
}
#[test]
fn the_tree_publishes_every_command_with_its_state() {
let envelope = commands(false);
let rows = rows_of(&envelope);
assert!(rows.len() >= 59, "the whole tree must be published");
for row in rows {
let state = row["state"].as_str().expect("state present");
assert!(
matches!(state, "served" | "planned"),
"unexpected state {state}"
);
}
}
#[test]
fn the_tree_is_ordered_so_the_same_run_gives_the_same_bytes() {
let first = serde_json::to_string(&commands(false)).expect("serialises");
let second = serde_json::to_string(&commands(false)).expect("serialises");
assert_eq!(first, second);
}
#[test]
fn asking_a_contract_for_an_unknown_command_is_an_absence() {
let failure = schema(Some("query nonexistent"), false).expect_err("must refuse");
assert_eq!(failure.category(), crate::error::Category::Absence);
assert_eq!(failure.exit_number().code(), 8);
}
#[test]
fn a_published_command_always_has_a_contract() {
let envelope = schema(Some("query run"), false).expect("published command");
assert_eq!(envelope.data["command"], "query run");
}
#[test]
fn the_type_map_covers_every_family_the_contract_names() {
let envelope = schema(None, true).expect("type map");
let published = crate::types::map::published();
assert_eq!(rows_of(&envelope).len(), published.len());
for (row, entry) in rows_of(&envelope).iter().zip(published) {
assert_eq!(row["family"], entry.family.as_str());
assert_eq!(row["emitted"], entry.shape.as_str());
}
}
#[test]
fn the_served_list_and_the_published_tree_name_the_same_commands() {
let root = Cli::command();
let mut rows = Vec::new();
collect(&root, &mut Vec::new(), &mut rows);
let published: Vec<&str> = rows
.iter()
.map(|row| row["name"].as_str().expect("name present"))
.collect();
for leaf in published {
let times = super::super::SERVED_LEAVES
.iter()
.filter(|served| **served == leaf)
.count();
assert_eq!(times, 1, "`{leaf}` must be listed exactly once");
}
for served in super::super::SERVED_LEAVES {
assert!(
rows.iter().any(|row| row["name"] == served),
"`{served}` is listed but not published"
);
}
}
#[test]
fn the_manual_describes_the_surface_this_build_carries() {
let envelope = manual();
let page = envelope.data["page"]
.as_str()
.expect("a page is carried")
.replace('\\', "");
assert_eq!(envelope.data["format"], "roff");
assert!(
page.contains(env!("CARGO_PKG_NAME")),
"the product names itself"
);
for leaf in super::super::SERVED_LEAVES {
assert!(page.contains(leaf), "`{leaf}` is missing from the manual");
}
for (number, _) in EXIT_MEANINGS {
let published = number.code().to_string();
assert!(
page.contains(&published),
"exit number {published} is missing"
);
}
}
#[test]
fn every_exit_number_the_product_can_return_is_explained() {
let explained: Vec<u8> = EXIT_MEANINGS
.iter()
.map(|(number, _)| number.code())
.collect();
assert!(
explained.contains(&ExitNumber::Success.code()),
"the manual does not explain the number a successful invocation returns"
);
for category in crate::error::Category::ALL {
let number = category.exit_number().code();
assert!(
explained.contains(&number),
"`{category:?}` ends a process with {number} and the manual \
explains no such number, so a reader meeting it has nowhere to \
look it up"
);
}
}
#[test]
fn the_manual_carries_the_sections_a_manual_page_has() {
let page = manual().data["page"]
.as_str()
.expect("a page is carried")
.to_owned();
for section in [".TH", "SYNOPSIS", "COMMANDS", "EXIT NUMBERS", "NOTES"] {
assert!(
page.contains(section),
"`{section}` is missing from the page"
);
}
}
#[test]
fn completion_support_without_a_shell_is_refused_with_a_code() {
let failure = completions(None).expect_err("must refuse");
assert_eq!(failure.code(), "meta.shell_missing");
assert_eq!(failure.exit_number().code(), 2);
assert!(failure.hint().is_some_and(|hint| hint.contains("bash")));
}
#[test]
fn a_command_that_carries_actions_answers_for_the_group() {
let envelope = schema(Some("query named"), false).expect("a group is not an absence");
assert_eq!(envelope.data["command"], "query named");
let actions = envelope.data["actions"]
.as_array()
.expect("the actions travel with the answer");
assert!(
actions.iter().any(|action| action == "query named list"),
"the actions are read from the published tree: {actions:?}"
);
assert!(envelope.data["envelope"]["command"].is_string());
}
#[test]
fn the_build_reports_its_own_encryption_capability() {
let envelope = version();
assert_eq!(
envelope.data["encrypted_channel_available"],
crate::ENCRYPTED_CHANNEL_AVAILABLE
);
}
#[test]
fn the_build_names_the_cryptography_it_carries() {
let envelope = version();
let named = envelope.data["crypto_provider"]
.as_str()
.expect("the provider is always named");
assert_eq!(named == "none", !crate::ENCRYPTED_CHANNEL_AVAILABLE);
assert_eq!(
envelope.data["crypto_provider_audited"],
crate::conn::provider::PROVIDER_IS_AUDITED
);
}
}