use crate::cli_args::{
AnalyzeCommand, AnalyzeSubcommand, CalcitCommand, CallGraphCommand, CallGraphDiffCommand, CheckTypesCommand, CountCallsCommand,
CursorApplyCommand, CursorSetCommand, CursorShowCommand, CursorSubcommand, DeprecatedCommand, DynamicMethodsCommand,
EffectsGraphCommand, ToplevelCalcit, WeakTypesCommand,
};
const VIEW_COVERAGE: &str = "coverage";
const VIEW_DYNAMIC_METHOD: &str = "dynamic-method";
const VIEW_DEPRECATED_CALL: &str = "deprecated-call";
pub const VIEW_OPTION_NIL_ROUNDTRIP: &str = "option-nil-roundtrip";
pub const VIEW_INFERRED_DYNAMIC: &str = "inferred-dynamic";
pub const VIEW_LEGACY_MIGRATION: &str = "legacy-migration";
const NO_REPLACEMENT: &str = "";
const REPLACE_RM_EXAMPLE: &str = "`calcit edit meta <ns/def> --examples` with the remaining examples (from `query def --only examples`), or `calcit edit ns` with the changed `:examples`";
const REPLACE_NS_DOC: &str = "`calcit edit ns <ns>` with the changed `:doc` of the `:ns` entry (from `query ns <ns> --format cirru`)";
const REMOVED_GROUPS: &[&str] = &["analyze", "query", "tree", "cursor", "edit", "docs", "cirru", "config", "ffi"];
const REMOVED_COMMANDS: &[(&str, &str, &str)] = &[
("analyze", "dynamic-methods", "`calcit analyze weak-types --only dynamic-method`"),
("analyze", "deprecated", "`calcit analyze weak-types --only deprecated-call`"),
(
"analyze",
"count-calls",
"`calcit analyze call-graph --counts` (with `--sort count|name` and `--format human|edn|json`)",
),
("analyze", "call-graph-diff", "`calcit analyze call-graph --diff <ref>`"),
("analyze", "js-escape", NO_REPLACEMENT),
("analyze", "js-unescape", NO_REPLACEMENT),
("query", "pkg", "`calcit query config`, which prints the package name"),
("query", "modules", "`calcit config modules`"),
("query", "host-procs", NO_REPLACEMENT),
(
"tree",
"batch-delete",
"`calcit edit transaction` with one `tree delete` operation per path, highest index first",
),
("tree", "insert-before", "`calcit tree insert --at before`"),
("tree", "insert-after", "`calcit tree insert --at after`"),
("tree", "insert-child", "`calcit tree insert --at prepend-child`"),
("tree", "append-child", "`calcit tree insert --at append-child`"),
("tree", "swap-next", "`calcit tree swap --with next`"),
("tree", "swap-prev", "`calcit tree swap --with prev`"),
("cursor", "parent", "`calcit cursor move parent`"),
("cursor", "child", "`calcit cursor move child [index] [--last]`"),
("cursor", "next", "`calcit cursor move next [--count n]`"),
("cursor", "prev", "`calcit cursor move prev [--count n]`"),
("cursor", "back", "`calcit cursor move back [--count n]`"),
("cursor", "forward", "`calcit cursor move forward [--count n]`"),
("cursor", "backward", "`calcit cursor move backward [--count n]`"),
("cursor", "clear-anchor", NO_REPLACEMENT),
("cursor", "region", NO_REPLACEMENT),
("cursor", "mark", NO_REPLACEMENT),
("cursor", "goto", NO_REPLACEMENT),
("cursor", "rm-mark", NO_REPLACEMENT),
("cursor", "copy", NO_REPLACEMENT),
("cursor", "cut", NO_REPLACEMENT),
("cursor", "paste", NO_REPLACEMENT),
("cursor", "clear-clipboard", NO_REPLACEMENT),
("cursor", "slurp-next", "`calcit cursor apply slurp-next`"),
("cursor", "slurp-prev", "`calcit cursor apply slurp-prev`"),
("cursor", "barf-last", "`calcit cursor apply barf-last`"),
("cursor", "barf-first", "`calcit cursor apply barf-first`"),
("cursor", "duplicate", "`calcit cursor apply duplicate [--at before|after]`"),
("edit", "rm-example", REPLACE_RM_EXAMPLE),
("edit", "ns-doc", REPLACE_NS_DOC),
("docs", "read-lines", "`calcit docs read <file> --start <n> --lines <n>`"),
("cirru", "show-guide", "`calcit docs read cirru-syntax.md`"),
(
"config",
"version",
"`caps version get/set/bump`, which manages `deps.cirru :version`",
),
];
const REMOVED_COMMANDS_0_41: &[(&str, &str, &str)] = &[
(
"analyze",
"check-types",
"`calcit analyze weak-types --only coverage` (level filter: `--coverage-level none,partial,full`)",
),
(
"analyze",
"check-public",
"`calcit --check-only --ns <ns> [--deps] [--summary-only] [--format edn|json]`",
),
(
"analyze",
"quality",
"`calcit --check-only` for correctness and `calcit analyze weak-types [--only coverage|deprecated-call]` to locate debt",
),
];
const REMOVED_COMMANDS_0_53: &[(&str, &str, &str)] = &[
("docs", "graph", "`calcit docs search` or `calcit query context <ns/def>`"),
(
"cursor",
"push",
"record target and path and restore with `calcit cursor set <ns/def> --path <path>` (`cursor move back` only rewinds navigation history, not saved checkpoints)",
),
(
"cursor",
"pop",
"restore saved locations with `calcit cursor set <ns/def> --path <path>` (`cursor move back` only rewinds navigation history, not stack checkpoints); resolve pending stack entries on the previous CLI release before upgrading",
),
(
"query",
"next",
"`calcit query search` or `calcit query search-expr` with `--set-cursor <index>`",
),
(
"query",
"prev",
"`calcit query search` or `calcit query search-expr` with `--set-cursor <index>`",
),
(
"query",
"path",
"`calcit tree show <ns/def> --path <numeric-path>` (dot-separated numeric coordinates such as `@2.1.0`), after locating the node with `calcit query search`",
),
("query", "anchors", "`calcit query search @anchor:`"),
("edit", "doc", "`calcit edit meta <ns/def> --doc <text>`"),
(
"edit",
"tags",
"`calcit edit meta <ns/def> --tags <csv>` / `--add-tag` / `--rm-tag` / `--clear-tags` (or `calcit query def <ns/def>` to read)",
),
("edit", "examples", "`calcit edit meta <ns/def> --examples` / `--clear-examples`"),
("edit", "add-example", "`calcit edit meta <ns/def> --add-example [--at <index>]`"),
("edit", "rm-test", "`calcit edit meta <ns/def> --rm-test <name>`"),
("edit", "cp", "`calcit tree` / `calcit cursor apply`"),
("edit", "mv", "`calcit tree` / `calcit cursor apply`"),
("edit", "inc", NO_REPLACEMENT),
("analyze", "effects-graph", "`calcit analyze call-graph --effects`"),
("query", "peek", "`calcit query def <ns/def> --summary`"),
("query", "examples", "`calcit query def <ns/def> --only examples`"),
("query", "tests", "`calcit query def <ns/def> --only tests`"),
("cursor", "anchor", NO_REPLACEMENT),
("cursor", "marks", NO_REPLACEMENT),
("cursor", "clipboard", NO_REPLACEMENT),
];
const REMOVED_JSON_SWITCH: &[(&str, &str, &str)] = &[
("query", "schema", "0.31.0"),
("query", "def", "0.31.0"),
("tree", "show", "0.31.0"),
("ffi", "export", "0.53.0"),
];
fn find_removed(table: &[(&str, &str, &'static str)], group: &str, leaf: &str) -> Option<&'static str> {
table
.iter()
.find(|(removed_group, removed_leaf, _)| *removed_group == group && *removed_leaf == leaf)
.map(|(_, _, replacement)| *replacement)
}
fn removed_replacement(group: &str, leaf: &str) -> Option<&'static str> {
find_removed(REMOVED_COMMANDS, group, leaf)
}
fn removal_message(subject: &str, version: &str, replacement: &str) -> String {
if replacement == NO_REPLACEMENT {
format!("{subject} was removed in {version} and has no replacement. See docs/run/upgrade.md.")
} else {
format!("{subject} was removed in {version}; use {replacement}. See docs/run/upgrade.md.")
}
}
const TOP_LEVEL_VALUE_OPTIONS: &[&str] = &[
"--ns",
"--format",
"--emit-path",
"--init-fn",
"--reload-fn",
"--entry",
"--watch-dir",
"--timeout",
"--tips-level",
"--cursor-after",
];
fn subcommand_position(args: &[String]) -> Option<usize> {
let commands = <CalcitCommand as argh::SubCommands>::COMMANDS;
let mut index = 1;
while index < args.len() {
let arg = args[index].as_str();
if arg == "--" {
return None;
}
if arg.starts_with('-') {
index += if TOP_LEVEL_VALUE_OPTIONS.contains(&arg) { 2 } else { 1 };
continue;
}
if commands.iter().any(|command| command.name == arg) {
return Some(index);
}
index += 1;
}
None
}
pub fn removed_command_error(args: &[String]) -> Option<String> {
let top_level = &args[1.min(args.len())..subcommand_position(args).unwrap_or(args.len())];
if top_level.iter().take_while(|arg| *arg != "--").any(|arg| arg == "--compat-types") {
return Some(
"`--compat-types` was removed in 0.41.0 and has no replacement; fix the reported type diagnostics instead. See docs/run/upgrade.md."
.to_owned(),
);
}
if top_level.iter().take_while(|arg| *arg != "--").any(|arg| arg == "--strict-types") {
return Some(
"`--strict-types` was removed in 0.52.0; strict diagnostics are always enabled (use `--check-only` to pre-check the entry). See docs/run/upgrade.md."
.to_owned(),
);
}
let position = subcommand_position(args)?;
let group = args[position].as_str();
if !REMOVED_GROUPS.contains(&group) {
return None;
}
let leaf = args.get(position + 1)?.as_str();
if let Some(replacement) = removed_replacement(group, leaf) {
return Some(removal_message(&format!("`calcit {group} {leaf}`"), "0.31.0", replacement));
}
if let Some(replacement) = find_removed(REMOVED_COMMANDS_0_41, group, leaf) {
return Some(removal_message(&format!("`calcit {group} {leaf}`"), "0.41.0", replacement));
}
if let Some(replacement) = find_removed(REMOVED_COMMANDS_0_53, group, leaf) {
return Some(removal_message(&format!("`calcit {group} {leaf}`"), "0.53.0", replacement));
}
if let Some((_, _, version)) = REMOVED_JSON_SWITCH
.iter()
.find(|(json_group, json_leaf, _)| *json_group == group && *json_leaf == leaf)
&& args[position + 2..].iter().any(|arg| arg == "--json")
{
return Some(removal_message(
&format!("`calcit {group} {leaf} --json`"),
version,
"`--format json`",
));
}
None
}
const REMOVED_TRANSACTION_OPERATIONS: &[(&str, &str)] = &[
("tree", "batch-delete"),
("tree", "insert-before"),
("tree", "insert-after"),
("tree", "insert-child"),
("tree", "append-child"),
("tree", "swap-next"),
("tree", "swap-prev"),
("edit", "rm-example"),
("edit", "ns-doc"),
("config", "version"),
];
pub fn removed_transaction_operation_error(index: usize, group: &str, subcommand: &str) -> Option<String> {
if REMOVED_TRANSACTION_OPERATIONS.contains(&(group, subcommand))
&& let Some(replacement) = removed_replacement(group, subcommand)
{
let replacement = match (group, subcommand) {
("tree", "batch-delete") => "one `tree delete` operation per path, highest index first".to_owned(),
("edit", "rm-example") => "an `edit meta <ns/def> --examples` operation with the remaining examples".to_owned(),
("edit", "ns-doc") => "`calcit edit ns <ns>` with the changed `:ns` doc as its own guarded step".to_owned(),
("tree", _) => replacement.replacen("`calcit ", "`", 1),
_ => replacement.to_owned(),
};
return Some(format!(
"Transaction operation {} uses `{group} {subcommand}`, which was removed in 0.31.0; use {replacement}. See docs/run/upgrade.md.",
index + 1
));
}
if let Some(replacement) = find_removed(REMOVED_COMMANDS_0_53, group, subcommand) {
let advice = if replacement.is_empty() {
"which was removed in 0.53.0 and has no replacement".to_owned()
} else {
format!("which was removed in 0.53.0; use {replacement}")
};
return Some(format!(
"Transaction operation {} uses `{group} {subcommand}`, {advice}. See docs/run/upgrade.md.",
index + 1
));
}
None
}
#[derive(Debug, Clone, PartialEq)]
pub enum AnalyzeView {
Coverage(CheckTypesCommand),
DynamicMethods(DynamicMethodsCommand),
DeprecatedCalls(DeprecatedCommand),
CountCalls(CountCallsCommand),
CallGraphDiff(CallGraphDiffCommand),
EffectsGraph(EffectsGraphCommand),
}
#[derive(Debug, Clone, PartialEq)]
pub enum CursorAction {
Set(CursorSetCommand),
Show(CursorShowCommand),
Clear,
Parent,
Child { index: Option<usize>, last: bool },
Next(usize),
Prev(usize),
Back(usize),
Forward(usize),
Backward(usize),
Apply(CursorApplyCommand),
SlurpNext,
SlurpPrev,
BarfLast,
BarfFirst,
Duplicate(String),
}
pub fn normalize_cursor_subcommand(subcommand: &CursorSubcommand) -> Result<CursorAction, String> {
match subcommand {
CursorSubcommand::Move(o) => {
let direction = o.direction.as_str();
if !matches!(direction, "parent" | "child" | "next" | "prev" | "forward" | "backward" | "back") {
return Err(format!(
"Unsupported `cursor move {direction}`. Use: parent, child, next, prev, forward, backward, back."
));
}
if direction != "child" && (o.index.is_some() || o.last) {
return Err(format!(
"`cursor move {direction}` does not accept an index or --last; they belong to `child`."
));
}
if matches!(direction, "parent" | "child") && o.count.is_some() {
return Err(format!("`cursor move {direction}` does not accept --count."));
}
let count = o.count.unwrap_or(1);
Ok(match direction {
"parent" => CursorAction::Parent,
"child" => CursorAction::Child {
index: o.index,
last: o.last,
},
"next" => CursorAction::Next(count),
"prev" => CursorAction::Prev(count),
"forward" => CursorAction::Forward(count),
"backward" => CursorAction::Backward(count),
_ => CursorAction::Back(count),
})
}
CursorSubcommand::Apply(o) => {
let operation = o.operation.as_str();
if !matches!(operation, "slurp-next" | "slurp-prev" | "barf-last" | "barf-first" | "duplicate") {
if o.at.is_some() {
return Err(format!(
"Cursor operation '{operation}' does not accept --at; it belongs to `duplicate`."
));
}
return Ok(CursorAction::Apply(o.clone()));
}
if o.file.is_some() || o.code.is_some() || o.input_format != crate::cli_args::SyntaxInputFormat::Auto {
return Err(format!(
"Cursor operation '{operation}' does not accept --file, --code, or --input-format."
));
}
if o.at.is_some() && operation != "duplicate" {
return Err(format!(
"Cursor operation '{operation}' does not accept --at; it belongs to `duplicate`."
));
}
Ok(match operation {
"slurp-next" => CursorAction::SlurpNext,
"slurp-prev" => CursorAction::SlurpPrev,
"barf-last" => CursorAction::BarfLast,
"barf-first" => CursorAction::BarfFirst,
_ => CursorAction::Duplicate(o.at.clone().unwrap_or_else(|| "after".to_owned())),
})
}
CursorSubcommand::Set(o) => Ok(CursorAction::Set(o.clone())),
CursorSubcommand::Show(o) => Ok(CursorAction::Show(o.clone())),
CursorSubcommand::Clear(_) => Ok(CursorAction::Clear),
}
}
pub fn normalize_consolidated_views(cli_args: ToplevelCalcit) -> Result<(ToplevelCalcit, Option<AnalyzeView>), String> {
let (cli_args, view) = normalize_weak_types_view(cli_args)?;
if view.is_some() {
return Ok((cli_args, view));
}
let view = call_graph_view(&cli_args)?;
Ok((cli_args, view))
}
fn call_graph_view(cli_args: &ToplevelCalcit) -> Result<Option<AnalyzeView>, String> {
let Some(CalcitCommand::Analyze(AnalyzeCommand {
subcommand: AnalyzeSubcommand::CallGraph(options),
})) = &cli_args.subcommand
else {
return Ok(None);
};
let options: &CallGraphCommand = options;
let mode_count = (options.counts as u8) + (options.diff.is_some() as u8) + (options.effects as u8);
if mode_count > 1 {
return Err("`analyze call-graph` accepts at most one of `--counts`, `--diff <ref>`, or `--effects`.".to_owned());
}
let view = match (options.counts, &options.diff, options.effects) {
(false, None, false) => {
reject_flags(
"analyze call-graph",
&[
("--sort", options.sort.is_some()),
("--detail", options.detail.is_some()),
("--color", options.color.is_some()),
],
)?;
return Ok(None);
}
(true, None, false) => {
reject_flags(
"analyze call-graph --counts",
&[
("--max-depth", options.max_depth.is_some()),
("--show-unused", options.show_unused),
("--detail", options.detail.is_some()),
("--color", options.color.is_some()),
],
)?;
AnalyzeView::CountCalls(CountCallsCommand {
root: options.root.clone(),
ns_prefix: options.ns_prefix.clone(),
include_core: options.include_core,
format: options.format.clone(),
sort: options.sort.clone().unwrap_or_else(|| "count".to_owned()),
})
}
(false, Some(git_ref), false) => {
reject_flags(
"analyze call-graph --diff",
&[
("--show-unused", options.show_unused),
("--format", !matches!(options.format.as_str(), "text" | "tree" | "human")),
("--sort", options.sort.is_some()),
("--detail", options.detail.is_some()),
("--color", options.color.is_some()),
],
)?;
AnalyzeView::CallGraphDiff(CallGraphDiffCommand {
git_ref: git_ref.clone(),
root: options.root.clone(),
ns_prefix: options.ns_prefix.clone(),
include_core: options.include_core,
max_depth: options.max_depth.unwrap_or(0),
})
}
(false, None, true) => {
reject_flags(
"analyze call-graph --effects",
&[("--show-unused", options.show_unused), ("--sort", options.sort.is_some())],
)?;
AnalyzeView::EffectsGraph(EffectsGraphCommand {
root: options.root.clone(),
ns_prefix: options.ns_prefix.clone(),
include_core: options.include_core,
max_depth: options.max_depth.unwrap_or(2),
format: options.format.clone(),
detail: options.detail.clone().unwrap_or_else(|| "summary".to_owned()),
color: options.color.unwrap_or(true),
})
}
_ => unreachable!("mode_count > 1 checked above"),
};
Ok(Some(view))
}
fn reject_flags(form: &str, rejected: &[(&str, bool)]) -> Result<(), String> {
for (flag, present) in rejected {
if *present {
return Err(format!("`{form}` does not support `{flag}`."));
}
}
Ok(())
}
fn view_kind(only: Option<&str>) -> Result<Option<&'static str>, String> {
let Some(raw) = only else {
return Ok(None);
};
let kinds = raw.split(',').map(str::trim).filter(|kind| !kind.is_empty()).collect::<Vec<_>>();
let views = [
VIEW_COVERAGE,
VIEW_DYNAMIC_METHOD,
VIEW_DEPRECATED_CALL,
VIEW_OPTION_NIL_ROUNDTRIP,
VIEW_INFERRED_DYNAMIC,
VIEW_LEGACY_MIGRATION,
];
let selected = views.iter().copied().filter(|view| kinds.contains(view)).collect::<Vec<_>>();
match (selected.as_slice(), kinds.len()) {
([], _) => Ok(None),
([view], 1) => Ok(Some(view)),
_ => Err(format!(
"`analyze weak-types --only` accepts exactly one view ({}) or a list of match kinds, not a mix: `{raw}`.",
views.join(", ")
)),
}
}
fn reject_options(view: &str, rejected: &[(&str, bool)]) -> Result<(), String> {
reject_flags(&format!("analyze weak-types --only {view}"), rejected)
}
pub fn normalize_weak_types_view(cli_args: ToplevelCalcit) -> Result<(ToplevelCalcit, Option<AnalyzeView>), String> {
let Some(CalcitCommand::Analyze(AnalyzeCommand {
subcommand: AnalyzeSubcommand::WeakTypes(options),
})) = &cli_args.subcommand
else {
return Ok((cli_args, None));
};
let view = view_kind(options.only.as_deref())?;
if view.is_none() {
if options.coverage_level.is_some() {
return Err("`--coverage-level` requires `analyze weak-types --only coverage`.".to_owned());
}
return Ok((cli_args, None));
}
let options: &WeakTypesCommand = options;
let evidence_flags = [
("--intent", options.intent.is_some()),
("--ffi-evidence", options.ffi_evidence),
("--schema-evidence", options.schema_evidence),
];
if let Some(view @ (VIEW_OPTION_NIL_ROUNDTRIP | VIEW_INFERRED_DYNAMIC | VIEW_LEGACY_MIGRATION)) = view {
reject_options(view, &evidence_flags)?;
reject_options(
view,
&[
("--incremental", options.incremental),
("--coverage-level", options.coverage_level.is_some()),
],
)?;
let mut options = options.clone();
options.only = Some(view.to_owned());
return Ok((
ToplevelCalcit {
subcommand: Some(CalcitCommand::Analyze(AnalyzeCommand {
subcommand: AnalyzeSubcommand::WeakTypes(options),
})),
..cli_args
},
None,
));
}
let analyze_view = match view {
Some(VIEW_COVERAGE) => {
reject_options(VIEW_COVERAGE, &evidence_flags)?;
AnalyzeView::Coverage(CheckTypesCommand {
ns: options.ns.clone(),
ns_prefix: options.ns_prefix.clone(),
only: options.coverage_level.clone(),
format: options.format.clone(),
deps: options.deps,
summary_only: options.summary_only,
incremental: options.incremental,
})
}
Some(VIEW_DYNAMIC_METHOD) => {
reject_options(VIEW_DYNAMIC_METHOD, &evidence_flags)?;
reject_options(
VIEW_DYNAMIC_METHOD,
&[
("--ns", options.ns.is_some()),
("--ns-prefix", options.ns_prefix.is_some()),
("--coverage-level", options.coverage_level.is_some()),
],
)?;
AnalyzeView::DynamicMethods(DynamicMethodsCommand {
format: options.format.clone(),
deps: options.deps,
summary_only: options.summary_only,
incremental: options.incremental,
})
}
Some(VIEW_DEPRECATED_CALL) => {
reject_options(VIEW_DEPRECATED_CALL, &evidence_flags)?;
reject_options(
VIEW_DEPRECATED_CALL,
&[
("--incremental", options.incremental),
("--coverage-level", options.coverage_level.is_some()),
],
)?;
AnalyzeView::DeprecatedCalls(DeprecatedCommand {
ns: options.ns.clone(),
ns_prefix: options.ns_prefix.clone(),
format: options.format.clone(),
deps: options.deps,
summary_only: options.summary_only,
})
}
_ => unreachable!("view kind was validated"),
};
Ok((cli_args, Some(analyze_view)))
}
#[cfg(test)]
mod tests {
use super::*;
use argh::FromArgs;
fn parse(args: &[&str]) -> ToplevelCalcit {
ToplevelCalcit::from_args(&["calcit"], args).expect("arguments should parse")
}
fn analyze(cli_args: &ToplevelCalcit) -> &AnalyzeSubcommand {
match &cli_args.subcommand {
Some(CalcitCommand::Analyze(cmd)) => &cmd.subcommand,
other => panic!("expected analyze command, got {other:?}"),
}
}
fn args(items: &[&str]) -> Vec<String> {
std::iter::once("calcit").chain(items.iter().copied()).map(str::to_owned).collect()
}
#[test]
fn removed_strict_types_flag_reports_migration_guidance() {
let error = super::removed_command_error(&args(&["--strict-types", "--check-only"]))
.expect("--strict-types should report its 0.52.0 removal");
assert!(error.contains("was removed in 0.52.0"), "{error}");
assert!(error.contains("--check-only"), "{error}");
}
#[test]
fn weak_types_views_select_their_analyzers() {
let (coverage, view) = normalize_weak_types_view(parse(&[
"analyze",
"weak-types",
"--only",
"coverage",
"--coverage-level",
"none,partial",
"--ns",
"app.main",
"--summary-only",
"--format",
"json",
]))
.expect("coverage view");
assert!(matches!(analyze(&coverage), AnalyzeSubcommand::WeakTypes(_)));
assert_eq!(
view,
Some(AnalyzeView::Coverage(CheckTypesCommand {
ns: Some("app.main".to_owned()),
ns_prefix: None,
only: Some("none,partial".to_owned()),
format: "json".to_owned(),
deps: false,
summary_only: true,
incremental: false,
}))
);
let (_, dynamic) =
normalize_weak_types_view(parse(&["analyze", "weak-types", "--only", "dynamic-method", "--deps"])).expect("dynamic view");
assert_eq!(
dynamic,
Some(AnalyzeView::DynamicMethods(DynamicMethodsCommand {
format: "human".to_owned(),
deps: true,
summary_only: false,
incremental: false,
}))
);
let (_, deprecated) = normalize_weak_types_view(parse(&[
"analyze",
"weak-types",
"--only",
"deprecated-call",
"--ns-prefix",
"app.",
]))
.expect("view");
assert_eq!(
deprecated,
Some(AnalyzeView::DeprecatedCalls(DeprecatedCommand {
ns: None,
ns_prefix: Some("app.".to_owned()),
format: "human".to_owned(),
deps: false,
summary_only: false,
}))
);
}
#[test]
fn weak_types_match_kinds_stay_unchanged() {
let cli_args = parse(&["analyze", "weak-types", "--only", "code-nil,code-dynamic"]);
assert_eq!(normalize_weak_types_view(cli_args.clone()).expect("kinds"), (cli_args, None));
}
#[test]
fn option_nil_view_keeps_the_shared_entry_and_normalizes_its_spelling() {
let options = ["analyze", "weak-types", "--only", "option-nil-roundtrip", "--ns", "app.main"];
let expected = parse(&options);
assert_eq!(normalize_weak_types_view(expected.clone()).unwrap(), (expected.clone(), None));
let padded = parse(&["analyze", "weak-types", "--only", " option-nil-roundtrip, ", "--ns", "app.main"]);
assert_eq!(normalize_weak_types_view(padded).unwrap(), (expected, None));
let migration_expected = parse(&["analyze", "weak-types", "--only", "legacy-migration", "--ns", "app.main"]);
let migration_padded = parse(&["analyze", "weak-types", "--only", " legacy-migration, ", "--ns", "app.main"]);
assert_eq!(normalize_weak_types_view(migration_padded).unwrap(), (migration_expected, None));
}
#[test]
fn weak_types_views_reject_mixed_or_unsupported_options() {
for cli_args in [
&["analyze", "weak-types", "--only", "coverage,code-nil"][..],
&["analyze", "weak-types", "--only", "coverage,deprecated-call"][..],
&["analyze", "weak-types", "--only", "dynamic-method", "--ns", "app.main"][..],
&["analyze", "weak-types", "--only", "deprecated-call", "--incremental"][..],
&["analyze", "weak-types", "--only", "coverage", "--intent", "unresolved"][..],
&["analyze", "weak-types", "--coverage-level", "none"][..],
] {
assert!(
normalize_weak_types_view(parse(cli_args)).is_err(),
"{cli_args:?} should be rejected"
);
}
}
#[test]
fn entries_removed_in_0_41_name_their_replacement() {
for (cli_args, replacement) in [
(&["analyze", "check-types", "--ns", "app.main"][..], "weak-types --only coverage"),
(
&["calcit.cirru", "analyze", "check-public", "--ns", "app.lib"][..],
"--check-only --ns",
),
(&["analyze", "quality", "--baseline", "config/q.cirru"][..], "--check-only"),
] {
let error = removed_command_error(&args(cli_args)).expect("removed entry should be explained");
assert!(error.contains("was removed in 0.41.0") && error.contains(replacement), "{error}");
assert!(!error.contains('\n'), "message should be one line: {error}");
}
assert_eq!(removed_command_error(&args(&["analyze", "weak-types", "--only", "coverage"])), None);
for cli_args in [
&["--compat-types", "--check-only"][..],
&["calcit.cirru", "--compat-types", "test", "--tag", "unit"][..],
] {
let error = removed_command_error(&args(cli_args)).expect("removed flag should be explained");
assert!(error.contains("`--compat-types` was removed in 0.41.0"), "{error}");
}
assert_eq!(removed_command_error(&args(&["eval", "--compat-types"])), None);
}
#[test]
fn removed_entries_explain_their_replacement() {
for (cli_args, replacement) in [
(&["query", "pkg"][..], "query config"),
(&["--entry", "page", "calcit.cirru", "query", "modules"][..], "config modules"),
(&["--entry", "tree", "cursor", "parent"][..], "cursor move parent"),
(
&["--tips-level", "none", "--entry", "cursor", "app.cirru", "tree", "swap-next"][..],
"tree swap --with next",
),
(
&["-w", "--verbose", "calcit.cirru", "docs", "read-lines", "a.md"][..],
"docs read <file> --start",
),
(&["query", "host-procs"][..], "has no replacement"),
(
&["tree", "insert-before", "app.main/f", "--path", "0"][..],
"tree insert --at before",
),
(&["tree", "swap-prev", "app.main/f", "--path", "0"][..], "tree swap --with prev"),
(&["tree", "batch-delete", "app.main/f", "--paths", "0"][..], "edit transaction"),
(&["cursor", "parent"][..], "cursor move parent"),
(&["cursor", "duplicate", "--at", "before"][..], "cursor apply duplicate"),
(&["analyze", "count-calls"][..], "call-graph --counts"),
(&["analyze", "call-graph-diff", "HEAD"][..], "call-graph --diff"),
(&["analyze", "dynamic-methods"][..], "weak-types --only dynamic-method"),
(&["analyze", "deprecated"][..], "weak-types --only deprecated-call"),
(&["analyze", "js-escape", "a?"][..], "has no replacement"),
(&["edit", "rm-example", "app.main/f", "0"][..], "edit meta"),
(&["edit", "ns-doc", "app.main", "doc"][..], "edit ns <ns>"),
(&["docs", "read-lines", "a.md"][..], "docs read <file> --start"),
(&["cirru", "show-guide"][..], "docs read cirru-syntax.md"),
(&["config", "version", "patch"][..], "caps version"),
(&["query", "def", "app.main/f", "--json"][..], "`--format json`"),
(&["tree", "show", "app.main/f", "--json"][..], "`--format json`"),
] {
let error = removed_command_error(&args(cli_args)).expect("removed entry should be explained");
assert!(error.contains("was removed in 0.31.0") && error.contains(replacement), "{error}");
assert!(!error.contains('\n'), "message should be one line: {error}");
}
for (cli_args, replacement) in [
(&["docs", "graph", "build"][..], "docs search"),
(&["cursor", "push"][..], "cursor set"),
(&["cursor", "pop"][..], "navigation history"),
(&["query", "next"][..], "--set-cursor"),
(&["query", "prev"][..], "--set-cursor"),
(&["query", "path", "app.main", "--selector", "path"][..], "numeric coordinates"),
(&["query", "anchors", "app.main"][..], "query search @anchor:"),
(&["edit", "doc", "app.main/f", "hello"][..], "edit meta <ns/def> --doc"),
(&["edit", "tags", "app.main/f", "public"][..], "edit meta <ns/def> --tags"),
(&["edit", "examples", "app.main/f", "--clear"][..], "edit meta <ns/def> --examples"),
(
&["edit", "add-example", "app.main/f", "--code", "quote 1"][..],
"edit meta <ns/def> --add-example",
),
(&["edit", "rm-test", "app.main/f", "basic"][..], "edit meta <ns/def> --rm-test"),
(&["edit", "cp", "app.main/f", "--from", "0", "--path", "1"][..], "calcit tree"),
(&["edit", "mv", "app.main/f", "--from", "0", "--path", "1"][..], "calcit tree"),
(&["edit", "inc", "--changed", "app.main/f"][..], "has no replacement"),
(&["analyze", "effects-graph"][..], "analyze call-graph --effects"),
(&["query", "peek", "app.main/f"][..], "query def <ns/def> --summary"),
(&["query", "examples", "app.main/f"][..], "query def <ns/def> --only examples"),
(&["query", "tests", "app.main/f"][..], "query def <ns/def> --only tests"),
(&["cursor", "anchor"][..], "has no replacement"),
(&["cursor", "marks"][..], "has no replacement"),
(&["cursor", "clipboard"][..], "has no replacement"),
(&["ffi", "export", "--json"][..], "`--format json`"),
] {
let error = removed_command_error(&args(cli_args)).expect("0.53.0 removed entry should be explained");
assert!(error.contains("was removed in 0.53.0") && error.contains(replacement), "{error}");
assert!(!error.contains('\n'), "message should be one line: {error}");
}
for cli_args in [
&["query", "def", "app.main/f", "--format", "json"][..],
&["query", "search-expr", "[\"defn\"]", "--json"][..],
&["docs", "read", "query", "modules"][..],
&["cursor", "move", "parent"][..],
&["tree", "insert", "a/b", "--path", "0", "--at", "after"][..],
&["analyze", "call-graph", "--counts"][..],
&["--check-only"][..],
&["ffi", "export", "--format", "json"][..],
&["--entry", "query", "calcit.cirru", "js"][..],
&["query", "def", "query/pkg"][..],
&["edit", "def", "app.main/f", "--code", "query pkg"][..],
&["calcit.cirru", "js", "query", "pkg"][..],
&["--ns", "tree", "--check-only", "calcit.cirru"][..],
&["--", "query", "pkg"][..],
] {
assert_eq!(removed_command_error(&args(cli_args)), None, "{cli_args:?}");
}
}
#[test]
fn call_graph_options_select_their_analyzers() {
let view = |cli_args: &[&str]| normalize_consolidated_views(parse(cli_args)).expect("call-graph option").1;
assert_eq!(
view(&[
"analyze",
"call-graph",
"--counts",
"--sort",
"name",
"--format",
"json",
"--root",
"app.main/main!",
"--include-core",
]),
Some(AnalyzeView::CountCalls(CountCallsCommand {
root: Some("app.main/main!".to_owned()),
ns_prefix: None,
include_core: true,
format: "json".to_owned(),
sort: "name".to_owned(),
}))
);
assert_eq!(
view(&[
"analyze",
"call-graph",
"--diff",
"HEAD~1",
"--max-depth",
"3",
"--ns-prefix",
"app."
]),
Some(AnalyzeView::CallGraphDiff(CallGraphDiffCommand {
git_ref: "HEAD~1".to_owned(),
root: None,
ns_prefix: Some("app.".to_owned()),
include_core: false,
max_depth: 3,
}))
);
assert_eq!(
view(&[
"analyze",
"call-graph",
"--effects",
"--max-depth",
"4",
"--detail",
"full",
"--color",
"false",
"--format",
"json",
]),
Some(AnalyzeView::EffectsGraph(EffectsGraphCommand {
root: None,
ns_prefix: None,
include_core: false,
max_depth: 4,
format: "json".to_owned(),
detail: "full".to_owned(),
color: false,
}))
);
let plain = parse(&["analyze", "call-graph", "--show-unused"]);
assert_eq!(
normalize_consolidated_views(plain.clone()).expect("plain call-graph"),
(plain, None)
);
for cli_args in [
&["analyze", "call-graph", "--counts", "--diff", "HEAD"][..],
&["analyze", "call-graph", "--counts", "--effects"][..],
&["analyze", "call-graph", "--diff", "HEAD", "--effects"][..],
&["analyze", "call-graph", "--sort", "name"][..],
&["analyze", "call-graph", "--detail", "full"][..],
&["analyze", "call-graph", "--color", "false"][..],
&["analyze", "call-graph", "--effects", "--show-unused"][..],
&["analyze", "call-graph", "--counts", "--max-depth", "2"][..],
&["analyze", "call-graph", "--counts", "--show-unused"][..],
&["analyze", "call-graph", "--diff", "HEAD", "--format", "json"][..],
&["analyze", "call-graph", "--diff", "HEAD", "--show-unused"][..],
] {
assert!(
normalize_consolidated_views(parse(cli_args)).is_err(),
"{cli_args:?} should be rejected"
);
}
}
#[test]
fn removed_transaction_operations_name_their_replacement() {
for (group, subcommand, replacement) in [
("tree", "batch-delete", "tree delete"),
("tree", "insert-before", "`tree insert --at before`"),
("tree", "append-child", "`tree insert --at append-child`"),
("tree", "swap-next", "`tree swap --with next`"),
("edit", "rm-example", "edit meta"),
("edit", "ns-doc", "edit ns <ns>"),
("config", "version", "caps version"),
] {
let error = removed_transaction_operation_error(1, group, subcommand).expect("removed operation should be explained");
assert!(
error.starts_with("Transaction operation 2") && error.contains("removed in 0.31.0") && error.contains(replacement),
"{error}"
);
}
for (group, subcommand, replacement) in [
("edit", "doc", "edit meta"),
("edit", "tags", "edit meta"),
("edit", "examples", "edit meta"),
("edit", "add-example", "edit meta"),
("edit", "rm-test", "edit meta"),
("edit", "cp", "calcit tree"),
("edit", "mv", "calcit tree"),
("edit", "inc", "has no replacement"),
] {
let error = removed_transaction_operation_error(1, group, subcommand).expect("0.53.0 removed operation should be explained");
assert!(
error.starts_with("Transaction operation 2") && error.contains("removed in 0.53.0") && error.contains(replacement),
"{error}"
);
}
assert_eq!(removed_transaction_operation_error(0, "edit", "meta"), None);
assert_eq!(removed_transaction_operation_error(0, "tree", "insert"), None);
for (group, subcommand) in [
("cursor", "copy"),
("query", "pkg"),
("docs", "read-lines"),
("analyze", "count-calls"),
] {
assert_eq!(
removed_transaction_operation_error(0, group, subcommand),
None,
"{group} {subcommand}"
);
}
}
#[test]
fn top_level_value_options_match_the_parser() {
let help = match <ToplevelCalcit as argh::FromArgs>::from_args(&["calcit"], &["--help"]) {
Err(early_exit) => early_exit.output,
Ok(_) => panic!("--help should exit early"),
};
let usage = help.lines().next().expect("usage line");
let mut from_parser = usage
.split('[')
.filter_map(|item| {
let item = item.trim().trim_end_matches(']');
let (flag, value) = item.split_once(' ')?;
(flag.starts_with("--") && value.starts_with('<')).then(|| flag.to_owned())
})
.collect::<Vec<_>>();
let mut listed = TOP_LEVEL_VALUE_OPTIONS.iter().map(|flag| (*flag).to_owned()).collect::<Vec<_>>();
from_parser.sort();
listed.sort();
assert_eq!(listed, from_parser, "usage: {usage}");
let commands = <CalcitCommand as argh::SubCommands>::COMMANDS;
for group in REMOVED_GROUPS {
assert!(
commands.iter().any(|command| command.name == *group),
"{group} should be a subcommand"
);
}
}
#[test]
fn cursor_forms_resolve_to_their_actions() {
let cursor = |cli_args: &[&str]| match parse(cli_args).subcommand {
Some(CalcitCommand::Cursor(cmd)) => normalize_cursor_subcommand(&cmd.subcommand),
other => panic!("expected cursor command, got {other:?}"),
};
assert_eq!(cursor(&["cursor", "move", "parent"]), Ok(CursorAction::Parent));
assert_eq!(
cursor(&["cursor", "move", "child", "2"]),
Ok(CursorAction::Child {
index: Some(2),
last: false
})
);
assert_eq!(cursor(&["cursor", "move", "next", "--count", "3"]), Ok(CursorAction::Next(3)));
assert_eq!(
cursor(&["cursor", "apply", "duplicate", "--at", "before"]),
Ok(CursorAction::Duplicate("before".to_owned()))
);
assert!(cursor(&["cursor", "move", "sideways"]).is_err());
assert!(cursor(&["cursor", "apply", "slurp-next", "--at", "before"]).is_err());
}
}