1use crate::cli_args::{
5 AnalyzeCommand, AnalyzeSubcommand, CalcitCommand, CallGraphCommand, CallGraphDiffCommand, CheckTypesCommand, CountCallsCommand,
6 CursorApplyCommand, CursorSetCommand, CursorShowCommand, CursorSubcommand, DeprecatedCommand, DynamicMethodsCommand,
7 EffectsGraphCommand, ToplevelCalcit, WeakTypesCommand,
8};
9
10const VIEW_COVERAGE: &str = "coverage";
13const VIEW_DYNAMIC_METHOD: &str = "dynamic-method";
14const VIEW_DEPRECATED_CALL: &str = "deprecated-call";
15pub const VIEW_OPTION_NIL_ROUNDTRIP: &str = "option-nil-roundtrip";
16pub const VIEW_INFERRED_DYNAMIC: &str = "inferred-dynamic";
17pub const VIEW_LEGACY_MIGRATION: &str = "legacy-migration";
18
19const NO_REPLACEMENT: &str = "";
21
22const 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`";
23const REPLACE_NS_DOC: &str = "`calcit edit ns <ns>` with the changed `:doc` of the `:ns` entry (from `query ns <ns> --format cirru`)";
24
25const REMOVED_GROUPS: &[&str] = &["analyze", "query", "tree", "cursor", "edit", "docs", "cirru", "config", "ffi"];
27
28const REMOVED_COMMANDS: &[(&str, &str, &str)] = &[
30 ("analyze", "dynamic-methods", "`calcit analyze weak-types --only dynamic-method`"),
31 ("analyze", "deprecated", "`calcit analyze weak-types --only deprecated-call`"),
32 (
33 "analyze",
34 "count-calls",
35 "`calcit analyze call-graph --counts` (with `--sort count|name` and `--format human|edn|json`)",
36 ),
37 ("analyze", "call-graph-diff", "`calcit analyze call-graph --diff <ref>`"),
38 ("analyze", "js-escape", NO_REPLACEMENT),
39 ("analyze", "js-unescape", NO_REPLACEMENT),
40 ("query", "pkg", "`calcit query config`, which prints the package name"),
41 ("query", "modules", "`calcit config modules`"),
42 ("query", "host-procs", NO_REPLACEMENT),
43 (
44 "tree",
45 "batch-delete",
46 "`calcit edit transaction` with one `tree delete` operation per path, highest index first",
47 ),
48 ("tree", "insert-before", "`calcit tree insert --at before`"),
49 ("tree", "insert-after", "`calcit tree insert --at after`"),
50 ("tree", "insert-child", "`calcit tree insert --at prepend-child`"),
51 ("tree", "append-child", "`calcit tree insert --at append-child`"),
52 ("tree", "swap-next", "`calcit tree swap --with next`"),
53 ("tree", "swap-prev", "`calcit tree swap --with prev`"),
54 ("cursor", "parent", "`calcit cursor move parent`"),
55 ("cursor", "child", "`calcit cursor move child [index] [--last]`"),
56 ("cursor", "next", "`calcit cursor move next [--count n]`"),
57 ("cursor", "prev", "`calcit cursor move prev [--count n]`"),
58 ("cursor", "back", "`calcit cursor move back [--count n]`"),
59 ("cursor", "forward", "`calcit cursor move forward [--count n]`"),
60 ("cursor", "backward", "`calcit cursor move backward [--count n]`"),
61 ("cursor", "clear-anchor", NO_REPLACEMENT),
62 ("cursor", "region", NO_REPLACEMENT),
63 ("cursor", "mark", NO_REPLACEMENT),
64 ("cursor", "goto", NO_REPLACEMENT),
65 ("cursor", "rm-mark", NO_REPLACEMENT),
66 ("cursor", "copy", NO_REPLACEMENT),
67 ("cursor", "cut", NO_REPLACEMENT),
68 ("cursor", "paste", NO_REPLACEMENT),
69 ("cursor", "clear-clipboard", NO_REPLACEMENT),
70 ("cursor", "slurp-next", "`calcit cursor apply slurp-next`"),
71 ("cursor", "slurp-prev", "`calcit cursor apply slurp-prev`"),
72 ("cursor", "barf-last", "`calcit cursor apply barf-last`"),
73 ("cursor", "barf-first", "`calcit cursor apply barf-first`"),
74 ("cursor", "duplicate", "`calcit cursor apply duplicate [--at before|after]`"),
75 ("edit", "rm-example", REPLACE_RM_EXAMPLE),
76 ("edit", "ns-doc", REPLACE_NS_DOC),
77 ("docs", "read-lines", "`calcit docs read <file> --start <n> --lines <n>`"),
78 ("cirru", "show-guide", "`calcit docs read cirru-syntax.md`"),
79 (
80 "config",
81 "version",
82 "`caps version get/set/bump`, which manages `deps.cirru :version`",
83 ),
84];
85
86const REMOVED_COMMANDS_0_41: &[(&str, &str, &str)] = &[
88 (
89 "analyze",
90 "check-types",
91 "`calcit analyze weak-types --only coverage` (level filter: `--coverage-level none,partial,full`)",
92 ),
93 (
94 "analyze",
95 "check-public",
96 "`calcit --check-only --ns <ns> [--deps] [--summary-only] [--format edn|json]`",
97 ),
98 (
99 "analyze",
100 "quality",
101 "`calcit --check-only` for correctness and `calcit analyze weak-types [--only coverage|deprecated-call]` to locate debt",
102 ),
103];
104
105const REMOVED_COMMANDS_0_53: &[(&str, &str, &str)] = &[
107 ("docs", "graph", "`calcit docs search` or `calcit query context <ns/def>`"),
108 (
109 "cursor",
110 "push",
111 "record target and path and restore with `calcit cursor set <ns/def> --path <path>` (`cursor move back` only rewinds navigation history, not saved checkpoints)",
112 ),
113 (
114 "cursor",
115 "pop",
116 "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",
117 ),
118 (
119 "query",
120 "next",
121 "`calcit query search` or `calcit query search-expr` with `--set-cursor <index>`",
122 ),
123 (
124 "query",
125 "prev",
126 "`calcit query search` or `calcit query search-expr` with `--set-cursor <index>`",
127 ),
128 (
129 "query",
130 "path",
131 "`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`",
132 ),
133 ("query", "anchors", "`calcit query search @anchor:`"),
134 ("edit", "doc", "`calcit edit meta <ns/def> --doc <text>`"),
135 (
136 "edit",
137 "tags",
138 "`calcit edit meta <ns/def> --tags <csv>` / `--add-tag` / `--rm-tag` / `--clear-tags` (or `calcit query def <ns/def>` to read)",
139 ),
140 ("edit", "examples", "`calcit edit meta <ns/def> --examples` / `--clear-examples`"),
141 ("edit", "add-example", "`calcit edit meta <ns/def> --add-example [--at <index>]`"),
142 ("edit", "rm-test", "`calcit edit meta <ns/def> --rm-test <name>`"),
143 ("edit", "cp", "`calcit tree` / `calcit cursor apply`"),
144 ("edit", "mv", "`calcit tree` / `calcit cursor apply`"),
145 ("edit", "inc", NO_REPLACEMENT),
146 ("analyze", "effects-graph", "`calcit analyze call-graph --effects`"),
147 ("query", "peek", "`calcit query def <ns/def> --summary`"),
148 ("query", "examples", "`calcit query def <ns/def> --only examples`"),
149 ("query", "tests", "`calcit query def <ns/def> --only tests`"),
150 ("cursor", "anchor", NO_REPLACEMENT),
151 ("cursor", "marks", NO_REPLACEMENT),
152 ("cursor", "clipboard", NO_REPLACEMENT),
153];
154
155const REMOVED_JSON_SWITCH: &[(&str, &str, &str)] = &[
157 ("query", "schema", "0.31.0"),
158 ("query", "def", "0.31.0"),
159 ("tree", "show", "0.31.0"),
160 ("ffi", "export", "0.53.0"),
161];
162
163fn find_removed(table: &[(&str, &str, &'static str)], group: &str, leaf: &str) -> Option<&'static str> {
164 table
165 .iter()
166 .find(|(removed_group, removed_leaf, _)| *removed_group == group && *removed_leaf == leaf)
167 .map(|(_, _, replacement)| *replacement)
168}
169
170fn removed_replacement(group: &str, leaf: &str) -> Option<&'static str> {
171 find_removed(REMOVED_COMMANDS, group, leaf)
172}
173
174fn removal_message(subject: &str, version: &str, replacement: &str) -> String {
175 if replacement == NO_REPLACEMENT {
176 format!("{subject} was removed in {version} and has no replacement. See docs/run/upgrade.md.")
177 } else {
178 format!("{subject} was removed in {version}; use {replacement}. See docs/run/upgrade.md.")
179 }
180}
181
182const TOP_LEVEL_VALUE_OPTIONS: &[&str] = &[
186 "--ns",
187 "--format",
188 "--emit-path",
189 "--init-fn",
190 "--reload-fn",
191 "--entry",
192 "--watch-dir",
193 "--timeout",
194 "--tips-level",
195 "--cursor-after",
196];
197
198fn subcommand_position(args: &[String]) -> Option<usize> {
202 let commands = <CalcitCommand as argh::SubCommands>::COMMANDS;
203 let mut index = 1;
204 while index < args.len() {
205 let arg = args[index].as_str();
206 if arg == "--" {
207 return None;
208 }
209 if arg.starts_with('-') {
210 index += if TOP_LEVEL_VALUE_OPTIONS.contains(&arg) { 2 } else { 1 };
211 continue;
212 }
213 if commands.iter().any(|command| command.name == arg) {
214 return Some(index);
215 }
216 index += 1;
217 }
218 None
219}
220
221pub fn removed_command_error(args: &[String]) -> Option<String> {
227 let top_level = &args[1.min(args.len())..subcommand_position(args).unwrap_or(args.len())];
229 if top_level.iter().take_while(|arg| *arg != "--").any(|arg| arg == "--compat-types") {
230 return Some(
231 "`--compat-types` was removed in 0.41.0 and has no replacement; fix the reported type diagnostics instead. See docs/run/upgrade.md."
232 .to_owned(),
233 );
234 }
235 if top_level.iter().take_while(|arg| *arg != "--").any(|arg| arg == "--strict-types") {
236 return Some(
237 "`--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."
238 .to_owned(),
239 );
240 }
241 let position = subcommand_position(args)?;
242 let group = args[position].as_str();
243 if !REMOVED_GROUPS.contains(&group) {
244 return None;
245 }
246 let leaf = args.get(position + 1)?.as_str();
247 if let Some(replacement) = removed_replacement(group, leaf) {
248 return Some(removal_message(&format!("`calcit {group} {leaf}`"), "0.31.0", replacement));
249 }
250 if let Some(replacement) = find_removed(REMOVED_COMMANDS_0_41, group, leaf) {
251 return Some(removal_message(&format!("`calcit {group} {leaf}`"), "0.41.0", replacement));
252 }
253 if let Some(replacement) = find_removed(REMOVED_COMMANDS_0_53, group, leaf) {
254 return Some(removal_message(&format!("`calcit {group} {leaf}`"), "0.53.0", replacement));
255 }
256 if let Some((_, _, version)) = REMOVED_JSON_SWITCH
257 .iter()
258 .find(|(json_group, json_leaf, _)| *json_group == group && *json_leaf == leaf)
259 && args[position + 2..].iter().any(|arg| arg == "--json")
260 {
261 return Some(removal_message(
262 &format!("`calcit {group} {leaf} --json`"),
263 version,
264 "`--format json`",
265 ));
266 }
267 None
268}
269
270const REMOVED_TRANSACTION_OPERATIONS: &[(&str, &str)] = &[
274 ("tree", "batch-delete"),
275 ("tree", "insert-before"),
276 ("tree", "insert-after"),
277 ("tree", "insert-child"),
278 ("tree", "append-child"),
279 ("tree", "swap-next"),
280 ("tree", "swap-prev"),
281 ("edit", "rm-example"),
282 ("edit", "ns-doc"),
283 ("config", "version"),
284];
285
286pub fn removed_transaction_operation_error(index: usize, group: &str, subcommand: &str) -> Option<String> {
288 if REMOVED_TRANSACTION_OPERATIONS.contains(&(group, subcommand))
289 && let Some(replacement) = removed_replacement(group, subcommand)
290 {
291 let replacement = match (group, subcommand) {
292 ("tree", "batch-delete") => "one `tree delete` operation per path, highest index first".to_owned(),
293 ("edit", "rm-example") => "an `edit meta <ns/def> --examples` operation with the remaining examples".to_owned(),
294 ("edit", "ns-doc") => "`calcit edit ns <ns>` with the changed `:ns` doc as its own guarded step".to_owned(),
295 ("tree", _) => replacement.replacen("`calcit ", "`", 1),
296 _ => replacement.to_owned(),
297 };
298 return Some(format!(
299 "Transaction operation {} uses `{group} {subcommand}`, which was removed in 0.31.0; use {replacement}. See docs/run/upgrade.md.",
300 index + 1
301 ));
302 }
303 if let Some(replacement) = find_removed(REMOVED_COMMANDS_0_53, group, subcommand) {
304 let advice = if replacement.is_empty() {
305 "which was removed in 0.53.0 and has no replacement".to_owned()
306 } else {
307 format!("which was removed in 0.53.0; use {replacement}")
308 };
309 return Some(format!(
310 "Transaction operation {} uses `{group} {subcommand}`, {advice}. See docs/run/upgrade.md.",
311 index + 1
312 ));
313 }
314 None
315}
316
317#[derive(Debug, Clone, PartialEq)]
319pub enum AnalyzeView {
320 Coverage(CheckTypesCommand),
322 DynamicMethods(DynamicMethodsCommand),
324 DeprecatedCalls(DeprecatedCommand),
326 CountCalls(CountCallsCommand),
328 CallGraphDiff(CallGraphDiffCommand),
330 EffectsGraph(EffectsGraphCommand),
332}
333
334#[derive(Debug, Clone, PartialEq)]
336pub enum CursorAction {
337 Set(CursorSetCommand),
338 Show(CursorShowCommand),
339 Clear,
340 Parent,
341 Child { index: Option<usize>, last: bool },
342 Next(usize),
343 Prev(usize),
344 Back(usize),
345 Forward(usize),
346 Backward(usize),
347 Apply(CursorApplyCommand),
348 SlurpNext,
349 SlurpPrev,
350 BarfLast,
351 BarfFirst,
352 Duplicate(String),
353}
354
355pub fn normalize_cursor_subcommand(subcommand: &CursorSubcommand) -> Result<CursorAction, String> {
358 match subcommand {
359 CursorSubcommand::Move(o) => {
360 let direction = o.direction.as_str();
361 if !matches!(direction, "parent" | "child" | "next" | "prev" | "forward" | "backward" | "back") {
362 return Err(format!(
363 "Unsupported `cursor move {direction}`. Use: parent, child, next, prev, forward, backward, back."
364 ));
365 }
366 if direction != "child" && (o.index.is_some() || o.last) {
367 return Err(format!(
368 "`cursor move {direction}` does not accept an index or --last; they belong to `child`."
369 ));
370 }
371 if matches!(direction, "parent" | "child") && o.count.is_some() {
372 return Err(format!("`cursor move {direction}` does not accept --count."));
373 }
374 let count = o.count.unwrap_or(1);
375 Ok(match direction {
376 "parent" => CursorAction::Parent,
377 "child" => CursorAction::Child {
378 index: o.index,
379 last: o.last,
380 },
381 "next" => CursorAction::Next(count),
382 "prev" => CursorAction::Prev(count),
383 "forward" => CursorAction::Forward(count),
384 "backward" => CursorAction::Backward(count),
385 _ => CursorAction::Back(count),
386 })
387 }
388 CursorSubcommand::Apply(o) => {
389 let operation = o.operation.as_str();
390 if !matches!(operation, "slurp-next" | "slurp-prev" | "barf-last" | "barf-first" | "duplicate") {
391 if o.at.is_some() {
392 return Err(format!(
393 "Cursor operation '{operation}' does not accept --at; it belongs to `duplicate`."
394 ));
395 }
396 return Ok(CursorAction::Apply(o.clone()));
397 }
398 if o.file.is_some() || o.code.is_some() || o.input_format != crate::cli_args::SyntaxInputFormat::Auto {
399 return Err(format!(
400 "Cursor operation '{operation}' does not accept --file, --code, or --input-format."
401 ));
402 }
403 if o.at.is_some() && operation != "duplicate" {
404 return Err(format!(
405 "Cursor operation '{operation}' does not accept --at; it belongs to `duplicate`."
406 ));
407 }
408 Ok(match operation {
409 "slurp-next" => CursorAction::SlurpNext,
410 "slurp-prev" => CursorAction::SlurpPrev,
411 "barf-last" => CursorAction::BarfLast,
412 "barf-first" => CursorAction::BarfFirst,
413 _ => CursorAction::Duplicate(o.at.clone().unwrap_or_else(|| "after".to_owned())),
414 })
415 }
416 CursorSubcommand::Set(o) => Ok(CursorAction::Set(o.clone())),
417 CursorSubcommand::Show(o) => Ok(CursorAction::Show(o.clone())),
418 CursorSubcommand::Clear(_) => Ok(CursorAction::Clear),
419 }
420}
421
422pub fn normalize_consolidated_views(cli_args: ToplevelCalcit) -> Result<(ToplevelCalcit, Option<AnalyzeView>), String> {
425 let (cli_args, view) = normalize_weak_types_view(cli_args)?;
426 if view.is_some() {
427 return Ok((cli_args, view));
428 }
429 let view = call_graph_view(&cli_args)?;
430 Ok((cli_args, view))
431}
432
433fn call_graph_view(cli_args: &ToplevelCalcit) -> Result<Option<AnalyzeView>, String> {
435 let Some(CalcitCommand::Analyze(AnalyzeCommand {
436 subcommand: AnalyzeSubcommand::CallGraph(options),
437 })) = &cli_args.subcommand
438 else {
439 return Ok(None);
440 };
441 let options: &CallGraphCommand = options;
442 let mode_count = (options.counts as u8) + (options.diff.is_some() as u8) + (options.effects as u8);
443 if mode_count > 1 {
444 return Err("`analyze call-graph` accepts at most one of `--counts`, `--diff <ref>`, or `--effects`.".to_owned());
445 }
446 let view = match (options.counts, &options.diff, options.effects) {
447 (false, None, false) => {
448 reject_flags(
449 "analyze call-graph",
450 &[
451 ("--sort", options.sort.is_some()),
452 ("--detail", options.detail.is_some()),
453 ("--color", options.color.is_some()),
454 ],
455 )?;
456 return Ok(None);
457 }
458 (true, None, false) => {
459 reject_flags(
460 "analyze call-graph --counts",
461 &[
462 ("--max-depth", options.max_depth.is_some()),
463 ("--show-unused", options.show_unused),
464 ("--detail", options.detail.is_some()),
465 ("--color", options.color.is_some()),
466 ],
467 )?;
468 AnalyzeView::CountCalls(CountCallsCommand {
469 root: options.root.clone(),
470 ns_prefix: options.ns_prefix.clone(),
471 include_core: options.include_core,
472 format: options.format.clone(),
473 sort: options.sort.clone().unwrap_or_else(|| "count".to_owned()),
474 })
475 }
476 (false, Some(git_ref), false) => {
477 reject_flags(
478 "analyze call-graph --diff",
479 &[
480 ("--show-unused", options.show_unused),
481 ("--format", !matches!(options.format.as_str(), "text" | "tree" | "human")),
482 ("--sort", options.sort.is_some()),
483 ("--detail", options.detail.is_some()),
484 ("--color", options.color.is_some()),
485 ],
486 )?;
487 AnalyzeView::CallGraphDiff(CallGraphDiffCommand {
488 git_ref: git_ref.clone(),
489 root: options.root.clone(),
490 ns_prefix: options.ns_prefix.clone(),
491 include_core: options.include_core,
492 max_depth: options.max_depth.unwrap_or(0),
493 })
494 }
495 (false, None, true) => {
496 reject_flags(
497 "analyze call-graph --effects",
498 &[("--show-unused", options.show_unused), ("--sort", options.sort.is_some())],
499 )?;
500 AnalyzeView::EffectsGraph(EffectsGraphCommand {
501 root: options.root.clone(),
502 ns_prefix: options.ns_prefix.clone(),
503 include_core: options.include_core,
504 max_depth: options.max_depth.unwrap_or(2),
505 format: options.format.clone(),
506 detail: options.detail.clone().unwrap_or_else(|| "summary".to_owned()),
507 color: options.color.unwrap_or(true),
508 })
509 }
510 _ => unreachable!("mode_count > 1 checked above"),
511 };
512 Ok(Some(view))
513}
514
515fn reject_flags(form: &str, rejected: &[(&str, bool)]) -> Result<(), String> {
516 for (flag, present) in rejected {
517 if *present {
518 return Err(format!("`{form}` does not support `{flag}`."));
519 }
520 }
521 Ok(())
522}
523
524fn view_kind(only: Option<&str>) -> Result<Option<&'static str>, String> {
525 let Some(raw) = only else {
526 return Ok(None);
527 };
528 let kinds = raw.split(',').map(str::trim).filter(|kind| !kind.is_empty()).collect::<Vec<_>>();
529 let views = [
530 VIEW_COVERAGE,
531 VIEW_DYNAMIC_METHOD,
532 VIEW_DEPRECATED_CALL,
533 VIEW_OPTION_NIL_ROUNDTRIP,
534 VIEW_INFERRED_DYNAMIC,
535 VIEW_LEGACY_MIGRATION,
536 ];
537 let selected = views.iter().copied().filter(|view| kinds.contains(view)).collect::<Vec<_>>();
538 match (selected.as_slice(), kinds.len()) {
539 ([], _) => Ok(None),
540 ([view], 1) => Ok(Some(view)),
541 _ => Err(format!(
542 "`analyze weak-types --only` accepts exactly one view ({}) or a list of match kinds, not a mix: `{raw}`.",
543 views.join(", ")
544 )),
545 }
546}
547
548fn reject_options(view: &str, rejected: &[(&str, bool)]) -> Result<(), String> {
549 reject_flags(&format!("analyze weak-types --only {view}"), rejected)
550}
551
552pub fn normalize_weak_types_view(cli_args: ToplevelCalcit) -> Result<(ToplevelCalcit, Option<AnalyzeView>), String> {
555 let Some(CalcitCommand::Analyze(AnalyzeCommand {
556 subcommand: AnalyzeSubcommand::WeakTypes(options),
557 })) = &cli_args.subcommand
558 else {
559 return Ok((cli_args, None));
560 };
561 let view = view_kind(options.only.as_deref())?;
562 if view.is_none() {
563 if options.coverage_level.is_some() {
564 return Err("`--coverage-level` requires `analyze weak-types --only coverage`.".to_owned());
565 }
566 return Ok((cli_args, None));
567 }
568 let options: &WeakTypesCommand = options;
569 let evidence_flags = [
570 ("--intent", options.intent.is_some()),
571 ("--ffi-evidence", options.ffi_evidence),
572 ("--schema-evidence", options.schema_evidence),
573 ];
574 if let Some(view @ (VIEW_OPTION_NIL_ROUNDTRIP | VIEW_INFERRED_DYNAMIC | VIEW_LEGACY_MIGRATION)) = view {
575 reject_options(view, &evidence_flags)?;
576 reject_options(
577 view,
578 &[
579 ("--incremental", options.incremental),
580 ("--coverage-level", options.coverage_level.is_some()),
581 ],
582 )?;
583 let mut options = options.clone();
584 options.only = Some(view.to_owned());
585 return Ok((
586 ToplevelCalcit {
587 subcommand: Some(CalcitCommand::Analyze(AnalyzeCommand {
588 subcommand: AnalyzeSubcommand::WeakTypes(options),
589 })),
590 ..cli_args
591 },
592 None,
593 ));
594 }
595 let analyze_view = match view {
596 Some(VIEW_COVERAGE) => {
597 reject_options(VIEW_COVERAGE, &evidence_flags)?;
598 AnalyzeView::Coverage(CheckTypesCommand {
599 ns: options.ns.clone(),
600 ns_prefix: options.ns_prefix.clone(),
601 only: options.coverage_level.clone(),
602 format: options.format.clone(),
603 deps: options.deps,
604 summary_only: options.summary_only,
605 incremental: options.incremental,
606 })
607 }
608 Some(VIEW_DYNAMIC_METHOD) => {
609 reject_options(VIEW_DYNAMIC_METHOD, &evidence_flags)?;
610 reject_options(
611 VIEW_DYNAMIC_METHOD,
612 &[
613 ("--ns", options.ns.is_some()),
614 ("--ns-prefix", options.ns_prefix.is_some()),
615 ("--coverage-level", options.coverage_level.is_some()),
616 ],
617 )?;
618 AnalyzeView::DynamicMethods(DynamicMethodsCommand {
619 format: options.format.clone(),
620 deps: options.deps,
621 summary_only: options.summary_only,
622 incremental: options.incremental,
623 })
624 }
625 Some(VIEW_DEPRECATED_CALL) => {
626 reject_options(VIEW_DEPRECATED_CALL, &evidence_flags)?;
627 reject_options(
628 VIEW_DEPRECATED_CALL,
629 &[
630 ("--incremental", options.incremental),
631 ("--coverage-level", options.coverage_level.is_some()),
632 ],
633 )?;
634 AnalyzeView::DeprecatedCalls(DeprecatedCommand {
635 ns: options.ns.clone(),
636 ns_prefix: options.ns_prefix.clone(),
637 format: options.format.clone(),
638 deps: options.deps,
639 summary_only: options.summary_only,
640 })
641 }
642 _ => unreachable!("view kind was validated"),
643 };
644 Ok((cli_args, Some(analyze_view)))
645}
646
647#[cfg(test)]
648mod tests {
649 use super::*;
650 use argh::FromArgs;
651
652 fn parse(args: &[&str]) -> ToplevelCalcit {
653 ToplevelCalcit::from_args(&["calcit"], args).expect("arguments should parse")
654 }
655
656 fn analyze(cli_args: &ToplevelCalcit) -> &AnalyzeSubcommand {
657 match &cli_args.subcommand {
658 Some(CalcitCommand::Analyze(cmd)) => &cmd.subcommand,
659 other => panic!("expected analyze command, got {other:?}"),
660 }
661 }
662
663 fn args(items: &[&str]) -> Vec<String> {
664 std::iter::once("calcit").chain(items.iter().copied()).map(str::to_owned).collect()
665 }
666
667 #[test]
668 fn removed_strict_types_flag_reports_migration_guidance() {
669 let error = super::removed_command_error(&args(&["--strict-types", "--check-only"]))
670 .expect("--strict-types should report its 0.52.0 removal");
671 assert!(error.contains("was removed in 0.52.0"), "{error}");
672 assert!(error.contains("--check-only"), "{error}");
673 }
674
675 #[test]
676 fn weak_types_views_select_their_analyzers() {
677 let (coverage, view) = normalize_weak_types_view(parse(&[
678 "analyze",
679 "weak-types",
680 "--only",
681 "coverage",
682 "--coverage-level",
683 "none,partial",
684 "--ns",
685 "app.main",
686 "--summary-only",
687 "--format",
688 "json",
689 ]))
690 .expect("coverage view");
691 assert!(matches!(analyze(&coverage), AnalyzeSubcommand::WeakTypes(_)));
692 assert_eq!(
693 view,
694 Some(AnalyzeView::Coverage(CheckTypesCommand {
695 ns: Some("app.main".to_owned()),
696 ns_prefix: None,
697 only: Some("none,partial".to_owned()),
698 format: "json".to_owned(),
699 deps: false,
700 summary_only: true,
701 incremental: false,
702 }))
703 );
704
705 let (_, dynamic) =
706 normalize_weak_types_view(parse(&["analyze", "weak-types", "--only", "dynamic-method", "--deps"])).expect("dynamic view");
707 assert_eq!(
708 dynamic,
709 Some(AnalyzeView::DynamicMethods(DynamicMethodsCommand {
710 format: "human".to_owned(),
711 deps: true,
712 summary_only: false,
713 incremental: false,
714 }))
715 );
716
717 let (_, deprecated) = normalize_weak_types_view(parse(&[
718 "analyze",
719 "weak-types",
720 "--only",
721 "deprecated-call",
722 "--ns-prefix",
723 "app.",
724 ]))
725 .expect("view");
726 assert_eq!(
727 deprecated,
728 Some(AnalyzeView::DeprecatedCalls(DeprecatedCommand {
729 ns: None,
730 ns_prefix: Some("app.".to_owned()),
731 format: "human".to_owned(),
732 deps: false,
733 summary_only: false,
734 }))
735 );
736 }
737
738 #[test]
739 fn weak_types_match_kinds_stay_unchanged() {
740 let cli_args = parse(&["analyze", "weak-types", "--only", "code-nil,code-dynamic"]);
741 assert_eq!(normalize_weak_types_view(cli_args.clone()).expect("kinds"), (cli_args, None));
742 }
743
744 #[test]
745 fn option_nil_view_keeps_the_shared_entry_and_normalizes_its_spelling() {
746 let options = ["analyze", "weak-types", "--only", "option-nil-roundtrip", "--ns", "app.main"];
747 let expected = parse(&options);
748 assert_eq!(normalize_weak_types_view(expected.clone()).unwrap(), (expected.clone(), None));
749 let padded = parse(&["analyze", "weak-types", "--only", " option-nil-roundtrip, ", "--ns", "app.main"]);
750 assert_eq!(normalize_weak_types_view(padded).unwrap(), (expected, None));
751
752 let migration_expected = parse(&["analyze", "weak-types", "--only", "legacy-migration", "--ns", "app.main"]);
753 let migration_padded = parse(&["analyze", "weak-types", "--only", " legacy-migration, ", "--ns", "app.main"]);
754 assert_eq!(normalize_weak_types_view(migration_padded).unwrap(), (migration_expected, None));
755 }
756
757 #[test]
758 fn weak_types_views_reject_mixed_or_unsupported_options() {
759 for cli_args in [
760 &["analyze", "weak-types", "--only", "coverage,code-nil"][..],
761 &["analyze", "weak-types", "--only", "coverage,deprecated-call"][..],
762 &["analyze", "weak-types", "--only", "dynamic-method", "--ns", "app.main"][..],
763 &["analyze", "weak-types", "--only", "deprecated-call", "--incremental"][..],
764 &["analyze", "weak-types", "--only", "coverage", "--intent", "unresolved"][..],
765 &["analyze", "weak-types", "--coverage-level", "none"][..],
766 ] {
767 assert!(
768 normalize_weak_types_view(parse(cli_args)).is_err(),
769 "{cli_args:?} should be rejected"
770 );
771 }
772 }
773
774 #[test]
775 fn entries_removed_in_0_41_name_their_replacement() {
776 for (cli_args, replacement) in [
777 (&["analyze", "check-types", "--ns", "app.main"][..], "weak-types --only coverage"),
778 (
779 &["calcit.cirru", "analyze", "check-public", "--ns", "app.lib"][..],
780 "--check-only --ns",
781 ),
782 (&["analyze", "quality", "--baseline", "config/q.cirru"][..], "--check-only"),
783 ] {
784 let error = removed_command_error(&args(cli_args)).expect("removed entry should be explained");
785 assert!(error.contains("was removed in 0.41.0") && error.contains(replacement), "{error}");
786 assert!(!error.contains('\n'), "message should be one line: {error}");
787 }
788 assert_eq!(removed_command_error(&args(&["analyze", "weak-types", "--only", "coverage"])), None);
789 for cli_args in [
790 &["--compat-types", "--check-only"][..],
791 &["calcit.cirru", "--compat-types", "test", "--tag", "unit"][..],
792 ] {
793 let error = removed_command_error(&args(cli_args)).expect("removed flag should be explained");
794 assert!(error.contains("`--compat-types` was removed in 0.41.0"), "{error}");
795 }
796 assert_eq!(removed_command_error(&args(&["eval", "--compat-types"])), None);
797 }
798
799 #[test]
800 fn removed_entries_explain_their_replacement() {
801 for (cli_args, replacement) in [
802 (&["query", "pkg"][..], "query config"),
803 (&["--entry", "page", "calcit.cirru", "query", "modules"][..], "config modules"),
804 (&["--entry", "tree", "cursor", "parent"][..], "cursor move parent"),
805 (
806 &["--tips-level", "none", "--entry", "cursor", "app.cirru", "tree", "swap-next"][..],
807 "tree swap --with next",
808 ),
809 (
810 &["-w", "--verbose", "calcit.cirru", "docs", "read-lines", "a.md"][..],
811 "docs read <file> --start",
812 ),
813 (&["query", "host-procs"][..], "has no replacement"),
814 (
815 &["tree", "insert-before", "app.main/f", "--path", "0"][..],
816 "tree insert --at before",
817 ),
818 (&["tree", "swap-prev", "app.main/f", "--path", "0"][..], "tree swap --with prev"),
819 (&["tree", "batch-delete", "app.main/f", "--paths", "0"][..], "edit transaction"),
820 (&["cursor", "parent"][..], "cursor move parent"),
821 (&["cursor", "duplicate", "--at", "before"][..], "cursor apply duplicate"),
822 (&["analyze", "count-calls"][..], "call-graph --counts"),
823 (&["analyze", "call-graph-diff", "HEAD"][..], "call-graph --diff"),
824 (&["analyze", "dynamic-methods"][..], "weak-types --only dynamic-method"),
825 (&["analyze", "deprecated"][..], "weak-types --only deprecated-call"),
826 (&["analyze", "js-escape", "a?"][..], "has no replacement"),
827 (&["edit", "rm-example", "app.main/f", "0"][..], "edit meta"),
828 (&["edit", "ns-doc", "app.main", "doc"][..], "edit ns <ns>"),
829 (&["docs", "read-lines", "a.md"][..], "docs read <file> --start"),
830 (&["cirru", "show-guide"][..], "docs read cirru-syntax.md"),
831 (&["config", "version", "patch"][..], "caps version"),
832 (&["query", "def", "app.main/f", "--json"][..], "`--format json`"),
833 (&["tree", "show", "app.main/f", "--json"][..], "`--format json`"),
834 ] {
835 let error = removed_command_error(&args(cli_args)).expect("removed entry should be explained");
836 assert!(error.contains("was removed in 0.31.0") && error.contains(replacement), "{error}");
837 assert!(!error.contains('\n'), "message should be one line: {error}");
838 }
839 for (cli_args, replacement) in [
840 (&["docs", "graph", "build"][..], "docs search"),
841 (&["cursor", "push"][..], "cursor set"),
842 (&["cursor", "pop"][..], "navigation history"),
843 (&["query", "next"][..], "--set-cursor"),
844 (&["query", "prev"][..], "--set-cursor"),
845 (&["query", "path", "app.main", "--selector", "path"][..], "numeric coordinates"),
846 (&["query", "anchors", "app.main"][..], "query search @anchor:"),
847 (&["edit", "doc", "app.main/f", "hello"][..], "edit meta <ns/def> --doc"),
848 (&["edit", "tags", "app.main/f", "public"][..], "edit meta <ns/def> --tags"),
849 (&["edit", "examples", "app.main/f", "--clear"][..], "edit meta <ns/def> --examples"),
850 (
851 &["edit", "add-example", "app.main/f", "--code", "quote 1"][..],
852 "edit meta <ns/def> --add-example",
853 ),
854 (&["edit", "rm-test", "app.main/f", "basic"][..], "edit meta <ns/def> --rm-test"),
855 (&["edit", "cp", "app.main/f", "--from", "0", "--path", "1"][..], "calcit tree"),
856 (&["edit", "mv", "app.main/f", "--from", "0", "--path", "1"][..], "calcit tree"),
857 (&["edit", "inc", "--changed", "app.main/f"][..], "has no replacement"),
858 (&["analyze", "effects-graph"][..], "analyze call-graph --effects"),
859 (&["query", "peek", "app.main/f"][..], "query def <ns/def> --summary"),
860 (&["query", "examples", "app.main/f"][..], "query def <ns/def> --only examples"),
861 (&["query", "tests", "app.main/f"][..], "query def <ns/def> --only tests"),
862 (&["cursor", "anchor"][..], "has no replacement"),
863 (&["cursor", "marks"][..], "has no replacement"),
864 (&["cursor", "clipboard"][..], "has no replacement"),
865 (&["ffi", "export", "--json"][..], "`--format json`"),
866 ] {
867 let error = removed_command_error(&args(cli_args)).expect("0.53.0 removed entry should be explained");
868 assert!(error.contains("was removed in 0.53.0") && error.contains(replacement), "{error}");
869 assert!(!error.contains('\n'), "message should be one line: {error}");
870 }
871 for cli_args in [
872 &["query", "def", "app.main/f", "--format", "json"][..],
873 &["query", "search-expr", "[\"defn\"]", "--json"][..],
874 &["docs", "read", "query", "modules"][..],
875 &["cursor", "move", "parent"][..],
876 &["tree", "insert", "a/b", "--path", "0", "--at", "after"][..],
877 &["analyze", "call-graph", "--counts"][..],
878 &["--check-only"][..],
879 &["ffi", "export", "--format", "json"][..],
880 &["--entry", "query", "calcit.cirru", "js"][..],
882 &["query", "def", "query/pkg"][..],
883 &["edit", "def", "app.main/f", "--code", "query pkg"][..],
884 &["calcit.cirru", "js", "query", "pkg"][..],
885 &["--ns", "tree", "--check-only", "calcit.cirru"][..],
886 &["--", "query", "pkg"][..],
887 ] {
888 assert_eq!(removed_command_error(&args(cli_args)), None, "{cli_args:?}");
889 }
890 }
891
892 #[test]
893 fn call_graph_options_select_their_analyzers() {
894 let view = |cli_args: &[&str]| normalize_consolidated_views(parse(cli_args)).expect("call-graph option").1;
895 assert_eq!(
896 view(&[
897 "analyze",
898 "call-graph",
899 "--counts",
900 "--sort",
901 "name",
902 "--format",
903 "json",
904 "--root",
905 "app.main/main!",
906 "--include-core",
907 ]),
908 Some(AnalyzeView::CountCalls(CountCallsCommand {
909 root: Some("app.main/main!".to_owned()),
910 ns_prefix: None,
911 include_core: true,
912 format: "json".to_owned(),
913 sort: "name".to_owned(),
914 }))
915 );
916 assert_eq!(
917 view(&[
918 "analyze",
919 "call-graph",
920 "--diff",
921 "HEAD~1",
922 "--max-depth",
923 "3",
924 "--ns-prefix",
925 "app."
926 ]),
927 Some(AnalyzeView::CallGraphDiff(CallGraphDiffCommand {
928 git_ref: "HEAD~1".to_owned(),
929 root: None,
930 ns_prefix: Some("app.".to_owned()),
931 include_core: false,
932 max_depth: 3,
933 }))
934 );
935 assert_eq!(
936 view(&[
937 "analyze",
938 "call-graph",
939 "--effects",
940 "--max-depth",
941 "4",
942 "--detail",
943 "full",
944 "--color",
945 "false",
946 "--format",
947 "json",
948 ]),
949 Some(AnalyzeView::EffectsGraph(EffectsGraphCommand {
950 root: None,
951 ns_prefix: None,
952 include_core: false,
953 max_depth: 4,
954 format: "json".to_owned(),
955 detail: "full".to_owned(),
956 color: false,
957 }))
958 );
959 let plain = parse(&["analyze", "call-graph", "--show-unused"]);
960 assert_eq!(
961 normalize_consolidated_views(plain.clone()).expect("plain call-graph"),
962 (plain, None)
963 );
964 for cli_args in [
965 &["analyze", "call-graph", "--counts", "--diff", "HEAD"][..],
966 &["analyze", "call-graph", "--counts", "--effects"][..],
967 &["analyze", "call-graph", "--diff", "HEAD", "--effects"][..],
968 &["analyze", "call-graph", "--sort", "name"][..],
969 &["analyze", "call-graph", "--detail", "full"][..],
970 &["analyze", "call-graph", "--color", "false"][..],
971 &["analyze", "call-graph", "--effects", "--show-unused"][..],
972 &["analyze", "call-graph", "--counts", "--max-depth", "2"][..],
973 &["analyze", "call-graph", "--counts", "--show-unused"][..],
974 &["analyze", "call-graph", "--diff", "HEAD", "--format", "json"][..],
975 &["analyze", "call-graph", "--diff", "HEAD", "--show-unused"][..],
976 ] {
977 assert!(
978 normalize_consolidated_views(parse(cli_args)).is_err(),
979 "{cli_args:?} should be rejected"
980 );
981 }
982 }
983
984 #[test]
985 fn removed_transaction_operations_name_their_replacement() {
986 for (group, subcommand, replacement) in [
987 ("tree", "batch-delete", "tree delete"),
988 ("tree", "insert-before", "`tree insert --at before`"),
989 ("tree", "append-child", "`tree insert --at append-child`"),
990 ("tree", "swap-next", "`tree swap --with next`"),
991 ("edit", "rm-example", "edit meta"),
992 ("edit", "ns-doc", "edit ns <ns>"),
993 ("config", "version", "caps version"),
994 ] {
995 let error = removed_transaction_operation_error(1, group, subcommand).expect("removed operation should be explained");
996 assert!(
997 error.starts_with("Transaction operation 2") && error.contains("removed in 0.31.0") && error.contains(replacement),
998 "{error}"
999 );
1000 }
1001 for (group, subcommand, replacement) in [
1002 ("edit", "doc", "edit meta"),
1003 ("edit", "tags", "edit meta"),
1004 ("edit", "examples", "edit meta"),
1005 ("edit", "add-example", "edit meta"),
1006 ("edit", "rm-test", "edit meta"),
1007 ("edit", "cp", "calcit tree"),
1008 ("edit", "mv", "calcit tree"),
1009 ("edit", "inc", "has no replacement"),
1010 ] {
1011 let error = removed_transaction_operation_error(1, group, subcommand).expect("0.53.0 removed operation should be explained");
1012 assert!(
1013 error.starts_with("Transaction operation 2") && error.contains("removed in 0.53.0") && error.contains(replacement),
1014 "{error}"
1015 );
1016 }
1017 assert_eq!(removed_transaction_operation_error(0, "edit", "meta"), None);
1018 assert_eq!(removed_transaction_operation_error(0, "tree", "insert"), None);
1019 for (group, subcommand) in [
1021 ("cursor", "copy"),
1022 ("query", "pkg"),
1023 ("docs", "read-lines"),
1024 ("analyze", "count-calls"),
1025 ] {
1026 assert_eq!(
1027 removed_transaction_operation_error(0, group, subcommand),
1028 None,
1029 "{group} {subcommand}"
1030 );
1031 }
1032 }
1033
1034 #[test]
1035 fn top_level_value_options_match_the_parser() {
1036 let help = match <ToplevelCalcit as argh::FromArgs>::from_args(&["calcit"], &["--help"]) {
1037 Err(early_exit) => early_exit.output,
1038 Ok(_) => panic!("--help should exit early"),
1039 };
1040 let usage = help.lines().next().expect("usage line");
1041 let mut from_parser = usage
1042 .split('[')
1043 .filter_map(|item| {
1044 let item = item.trim().trim_end_matches(']');
1045 let (flag, value) = item.split_once(' ')?;
1046 (flag.starts_with("--") && value.starts_with('<')).then(|| flag.to_owned())
1047 })
1048 .collect::<Vec<_>>();
1049 let mut listed = TOP_LEVEL_VALUE_OPTIONS.iter().map(|flag| (*flag).to_owned()).collect::<Vec<_>>();
1050 from_parser.sort();
1051 listed.sort();
1052 assert_eq!(listed, from_parser, "usage: {usage}");
1053 let commands = <CalcitCommand as argh::SubCommands>::COMMANDS;
1054 for group in REMOVED_GROUPS {
1055 assert!(
1056 commands.iter().any(|command| command.name == *group),
1057 "{group} should be a subcommand"
1058 );
1059 }
1060 }
1061
1062 #[test]
1063 fn cursor_forms_resolve_to_their_actions() {
1064 let cursor = |cli_args: &[&str]| match parse(cli_args).subcommand {
1065 Some(CalcitCommand::Cursor(cmd)) => normalize_cursor_subcommand(&cmd.subcommand),
1066 other => panic!("expected cursor command, got {other:?}"),
1067 };
1068 assert_eq!(cursor(&["cursor", "move", "parent"]), Ok(CursorAction::Parent));
1069 assert_eq!(
1070 cursor(&["cursor", "move", "child", "2"]),
1071 Ok(CursorAction::Child {
1072 index: Some(2),
1073 last: false
1074 })
1075 );
1076 assert_eq!(cursor(&["cursor", "move", "next", "--count", "3"]), Ok(CursorAction::Next(3)));
1077 assert_eq!(
1078 cursor(&["cursor", "apply", "duplicate", "--at", "before"]),
1079 Ok(CursorAction::Duplicate("before".to_owned()))
1080 );
1081 assert!(cursor(&["cursor", "move", "sideways"]).is_err());
1082 assert!(cursor(&["cursor", "apply", "slurp-next", "--at", "before"]).is_err());
1083 }
1084}