use crate::cli_args::{
EditAddImportCommand, EditAddNsCommand, EditAddTestCommand, EditCommand, EditDefCommand, EditFfiCommand, EditFormatCommand,
EditImportsCommand, EditMergeCommand, EditMetaCommand, EditMvDefCommand, EditRenameCommand, EditRmDefCommand, EditRmImportCommand,
EditRmNsCommand, EditSchemaCommand, EditSplitDefCommand, EditSubcommand, EditTransactionCommand, SyntaxInputFormat,
};
use crate::program_diff::{CirruEditStrategy, analyze_cirru_edit_advice};
use calcit_core::calcit::{CalcitTypeAnnotation, DYNAMIC_TYPE};
use calcit_core::program::validate_import_rules;
use calcit_core::snapshot::{
self, CodeEntry, FileInSnapShot, NsEntry, Snapshot, TestEntry, render_snapshot_content, save_snapshot_to_file,
};
use cirru_edn::{Edn, EdnMapView, EdnStructView, EdnTag};
use cirru_parser::Cirru;
use colored::Colorize;
use md5::{Digest, Md5};
#[cfg(test)]
use semver::Version;
use serde::Serialize;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::ffi::OsString;
use std::fs;
use std::path::Path;
use std::process::Command;
use std::sync::Arc;
use calcit_core::util::string::strip_shebang;
use super::atomic_write::stage_atomic_file;
use super::common::{
ERR_CODE_INPUT_REQUIRED, decode_mutation_syntax_input, format_path, guard_snapshot_mutation_toolchain, parse_input_to_cirru,
parse_path, parse_quoted_cirru_nodes, print_cli_warning_block, read_code_input, resolve_definition_lookup, shell_quote,
};
use super::cursor::{
maintain_cursor_after_any_mutation, maintain_cursor_after_definition_delete, maintain_cursor_after_definition_move,
maintain_cursor_after_definition_replace, maintain_cursor_after_namespace_delete, maintain_cursor_after_node_move,
maintain_cursor_after_split_definition, maintain_cursor_after_tree_mutation, resolve_active_cursor_reference,
resolve_cursor_path_argument, resolve_cursor_target_argument,
};
use super::handle_scaffold_command;
use super::structured_output::{StructuredOutputFormat, format_json_value_as_edn};
use super::tips::{Tips, command_guidance_enabled};
use super::tree_mutation::{TreeCursorMutation, TreeOperation, adjusted_source_path_after_insertion, path_is_strict_descendant};
pub(crate) fn parse_target(target: &str) -> Result<(&str, &str), String> {
target
.split_once('/')
.ok_or_else(|| format!("Invalid target format: '{target}'. Expected 'namespace/definition' (e.g. 'app.core/main')"))
}
pub(crate) fn process_node_with_references(
node: &Cirru,
references: &std::collections::BTreeMap<String, Cirru>,
) -> Result<Cirru, String> {
match node {
Cirru::Leaf(s) => {
if let Some(replacement) = references.get(s.as_ref()) {
return Ok(replacement.clone());
}
Ok(node.clone())
}
Cirru::List(items) => {
let processed_items: Result<Vec<Cirru>, String> =
items.iter().map(|item| process_node_with_references(item, references)).collect();
Ok(Cirru::List(processed_items?))
}
}
}
pub fn handle_edit_command(cmd: &EditCommand, snapshot_file: &str) -> Result<(), String> {
let _writer = if edit_mutates_snapshot(&cmd.subcommand) {
Some(calcit_core::util::atomic_write::SnapshotWriteGuard::acquire(snapshot_file)?)
} else {
None
};
if edit_mutates_snapshot(&cmd.subcommand) {
guard_snapshot_mutation_toolchain(snapshot_file)?;
}
let mut resolved = cmd.clone();
resolve_edit_cursor_references(&mut resolved, snapshot_file)?;
let result = match &resolved.subcommand {
EditSubcommand::Format(opts) => handle_format(opts, snapshot_file),
EditSubcommand::Merge(opts) => handle_merge(opts, snapshot_file),
EditSubcommand::Transaction(opts) => handle_transaction(opts, snapshot_file),
EditSubcommand::Scaffold(opts) => handle_scaffold_command(opts, snapshot_file),
EditSubcommand::Def(opts) => handle_def(opts, snapshot_file),
EditSubcommand::MvDef(opts) => handle_mv_def(opts, snapshot_file),
EditSubcommand::RmDef(opts) => handle_rm_def(opts, snapshot_file),
EditSubcommand::Rename(opts) => handle_rename(opts, snapshot_file),
EditSubcommand::SplitDef(opts) => handle_split_def(opts, snapshot_file),
EditSubcommand::Meta(opts) => handle_meta(opts, snapshot_file),
EditSubcommand::Schema(opts) => handle_schema(opts, snapshot_file),
EditSubcommand::Ffi(opts) => handle_ffi(opts, snapshot_file),
EditSubcommand::AddTest(opts) => handle_add_test(opts, snapshot_file),
EditSubcommand::AddNs(opts) => handle_add_ns(opts, snapshot_file),
EditSubcommand::RmNs(opts) => handle_rm_ns(opts, snapshot_file),
EditSubcommand::Ns(opts) => super::ns_view::handle_edit_ns(opts, snapshot_file),
EditSubcommand::Imports(opts) => handle_imports(opts, snapshot_file),
EditSubcommand::AddImport(opts) => handle_add_import(opts, snapshot_file),
EditSubcommand::RmImport(opts) => handle_rm_import(opts, snapshot_file),
};
result?;
maintain_cursor_after_edit(&resolved, snapshot_file)
}
fn edit_mutates_snapshot(cmd: &EditSubcommand) -> bool {
match cmd {
EditSubcommand::Transaction(opts) => !opts.dry_run,
EditSubcommand::Scaffold(opts) => !opts.dry_run,
EditSubcommand::Ns(opts) => !opts.dry_run,
EditSubcommand::Meta(opts) => !opts.dry_run,
EditSubcommand::Merge(_) => false,
_ => true,
}
}
fn resolve_edit_cursor_references(cmd: &mut EditCommand, snapshot_file: &str) -> Result<(), String> {
let target = match &mut cmd.subcommand {
EditSubcommand::Def(opts) => Some(&mut opts.target),
EditSubcommand::MvDef(opts) => Some(&mut opts.source),
EditSubcommand::RmDef(opts) => Some(&mut opts.target),
EditSubcommand::Meta(opts) => Some(&mut opts.target),
EditSubcommand::Schema(opts) => Some(&mut opts.target),
EditSubcommand::Ffi(opts) => Some(&mut opts.target),
EditSubcommand::AddTest(opts) => Some(&mut opts.target),
EditSubcommand::Rename(opts) => Some(&mut opts.source),
EditSubcommand::SplitDef(opts) => Some(&mut opts.target),
EditSubcommand::Format(_)
| EditSubcommand::Merge(_)
| EditSubcommand::Transaction(_)
| EditSubcommand::Scaffold(_)
| EditSubcommand::AddNs(_)
| EditSubcommand::RmNs(_)
| EditSubcommand::Ns(_)
| EditSubcommand::Imports(_)
| EditSubcommand::AddImport(_)
| EditSubcommand::RmImport(_) => None,
};
let active_reference = if target.as_deref().is_some_and(|target| target == "@cursor") {
Some(resolve_active_cursor_reference(snapshot_file)?)
} else {
None
};
if let Some(target) = target {
*target = match &active_reference {
Some((active_target, _)) => active_target.clone(),
None => resolve_cursor_target_argument(snapshot_file, target)?,
};
}
let resolve_path = |target: &str, path: &str| -> Result<String, String> {
if path == "@cursor"
&& let Some((active_target, active_path)) = &active_reference
{
if active_target != target {
return Err(format!(
"Cursor target mismatch: cursor points to '{active_target}', but command targets '{target}'."
));
}
Ok(active_path.clone())
} else {
resolve_cursor_path_argument(snapshot_file, target, path)
}
};
if let EditSubcommand::SplitDef(opts) = &mut cmd.subcommand {
opts.path = resolve_path(&opts.target, &opts.path)?;
}
Ok(())
}
fn maintain_cursor_after_edit(cmd: &EditCommand, snapshot_file: &str) -> Result<(), String> {
match &cmd.subcommand {
EditSubcommand::Def(opts) => maintain_cursor_after_definition_replace(snapshot_file, &opts.target),
EditSubcommand::MvDef(opts) => maintain_cursor_after_definition_move(snapshot_file, &opts.source, &opts.target),
EditSubcommand::RmDef(opts) => maintain_cursor_after_definition_delete(snapshot_file, &opts.target),
EditSubcommand::RmNs(opts) => maintain_cursor_after_namespace_delete(snapshot_file, &opts.namespace),
EditSubcommand::Rename(opts) => {
let (namespace, _) = parse_target(&opts.source)?;
maintain_cursor_after_definition_move(snapshot_file, &opts.source, &format!("{namespace}/{}", opts.new_name))
}
EditSubcommand::SplitDef(opts) => {
let (namespace, _) = parse_target(&opts.target)?;
maintain_cursor_after_split_definition(
snapshot_file,
&opts.target,
&parse_path(&opts.path)?,
&format!("{namespace}/{}", opts.new_name),
)
}
EditSubcommand::Meta(opts) if !opts.dry_run => {
maintain_cursor_after_tree_mutation(snapshot_file, &opts.target, &TreeCursorMutation::NoPathShift)
}
EditSubcommand::Schema(opts) => maintain_cursor_after_tree_mutation(snapshot_file, &opts.target, &TreeCursorMutation::NoPathShift),
EditSubcommand::Ffi(opts) => maintain_cursor_after_tree_mutation(snapshot_file, &opts.target, &TreeCursorMutation::NoPathShift),
EditSubcommand::AddTest(opts) => maintain_cursor_after_tree_mutation(snapshot_file, &opts.target, &TreeCursorMutation::NoPathShift),
EditSubcommand::Transaction(opts) if !opts.dry_run => {
maintain_cursor_after_any_mutation(snapshot_file, "validated after edit transaction")
}
EditSubcommand::Scaffold(opts) if !opts.dry_run => {
maintain_cursor_after_any_mutation(snapshot_file, "validated after scaffold apply")
}
EditSubcommand::Ns(opts) if !opts.dry_run => maintain_cursor_after_any_mutation(snapshot_file, "validated after edit ns"),
_ => Ok(()),
}
}
fn handle_merge(opts: &EditMergeCommand, snapshot_file: &str) -> Result<(), String> {
let base = load_snapshot(&opts.base)?;
let ours = load_snapshot(snapshot_file)?;
let theirs = load_snapshot(&opts.theirs)?;
let result = super::snapshot_scope::merge_snapshots(&base, &ours, &theirs)?;
let content = render_snapshot_content(&result.merged)?;
fs::write(snapshot_file, content.as_bytes()).map_err(|error| format!("Failed to write merged Snapshot {snapshot_file}: {error}"))?;
if result.conflicts.is_empty() {
println!("{} Merged Snapshot per definition into '{}'", "✓".green(), snapshot_file.cyan());
println!("Run `calcit --check-only` and the project tests before committing the merge.");
return Ok(());
}
println!("# Snapshot merge conflicts\n");
println!("Both sides changed these units differently; the file keeps our version of each:\n");
for unit in &result.conflicts {
println!("- `{unit}`");
if let Some(path) = unit.strip_prefix("def:")
&& let Some((namespace, definition)) = path.split_once('/')
{
for (label, side) in [("base", &base), ("ours", &ours), ("theirs", &theirs)] {
match side.files.get(namespace).and_then(|file| file.defs.get(definition)) {
Some(entry) => println!(
" - {label}: `{}`",
entry.code.format_one_liner().unwrap_or_else(|_| "(unprintable)".to_owned())
),
None => println!(" - {label}: _(absent)_"),
}
}
}
}
Err(format!(
"{} Snapshot unit(s) conflict; resolve them with `calcit edit`, then run `calcit --check-only`",
result.conflicts.len()
))
}
fn load_dependency_namespaces(snapshot: &snapshot::Snapshot, snapshot_file: &str) -> Option<HashSet<String>> {
let base_dir = Path::new(snapshot_file).parent().unwrap_or_else(|| Path::new("."));
let module_folder = calcit_core::project_module_folder(base_dir);
let mut namespaces = HashSet::new();
let mut seen = HashSet::new();
for entry in snapshot.entries.values() {
for module_path in &entry.modules {
if !seen.insert(module_path.clone()) {
continue;
}
let module = calcit_core::load_module(module_path, base_dir, &module_folder).ok()?;
namespaces.extend(module.files.keys().cloned());
}
}
Some(namespaces)
}
fn handle_format(opts: &EditFormatCommand, snapshot_file: &str) -> Result<(), String> {
let original_content = fs::read_to_string(snapshot_file).map_err(|e| format!("Failed to read {snapshot_file}: {e}"))?;
let mut original_edn = cirru_edn::parse(&original_content).map_err(|e| format!("Failed to parse EDN: {e}"))?;
let dropped_fields = snapshot::drop_legacy_entry_fields(&mut original_edn, &opts.drop_legacy_entry_fields)?;
let (mut snapshot, legacy_migration) =
snapshot::load_snapshot_data_for_format(&original_edn, snapshot_file).map_err(|e| format!("Failed to load snapshot: {e}"))?;
let advisories = collect_format_advisories(snapshot_file, &snapshot);
let stripped_require_lists = snapshot::canonicalize_snapshot_require_lists(&mut snapshot);
let canonicalized_type_forms = snapshot::canonicalize_snapshot_type_syntax(&mut snapshot);
let shortened_options = snapshot::shorten_snapshot_option_constructors(&mut snapshot);
let dependency_namespaces = load_dependency_namespaces(&snapshot, snapshot_file);
let shortened_type_names = snapshot::shorten_snapshot_type_names(&mut snapshot, dependency_namespaces.as_ref());
let formatted_content = render_snapshot_content(&snapshot)?;
if formatted_content == original_content {
println!("{} No formatting changes for '{}'", "·".dimmed(), snapshot_file.dimmed());
} else {
calcit_core::util::atomic_write::write_snapshot(snapshot_file, formatted_content.as_bytes())?;
println!("{} Formatted snapshot file '{}'", "✓".green(), snapshot_file.cyan());
}
if stripped_require_lists > 0 {
println!(
"{} Stripped legacy `[]` marker(s) from {stripped_require_lists} `:require` rule(s)",
"✓".green()
);
}
if canonicalized_type_forms > 0 {
println!(
"{} Rewrote {canonicalized_type_forms} type form(s) to the current type syntax",
"✓".green()
);
}
if shortened_options > 0 {
println!(
"{} Rewrote {shortened_options} `Option :some` / `Option :none` form(s) to `Some` / `None`",
"✓".green()
);
}
if shortened_type_names > 0 {
println!(
"{} Shortened {shortened_type_names} fully qualified type name(s) in schemas to the name the namespace resolves",
"✓".green()
);
}
for (field, value) in &dropped_fields {
println!("{} Dropped legacy entry field `{field}`: {value}", "✓".green());
}
if legacy_migration.happened() {
println!(
"{} Migrated legacy Snapshot data: {} namespace quote(s), {} definition quote(s), configs={}",
"✓".green(),
legacy_migration.direct_quote_namespaces,
legacy_migration.direct_quote_definitions,
legacy_migration.legacy_configs
);
}
for advisory in advisories {
print_cli_warning_block(&advisory);
}
Ok(())
}
fn collect_format_advisories(snapshot_file: &str, snapshot: &Snapshot) -> Vec<String> {
let mut advisories = vec![];
let snapshot_arg = shell_quote(snapshot_file);
let selected = std::collections::BTreeSet::from([
crate::type_coverage::WeakTypeKind::SchemaDynamic,
crate::type_coverage::WeakTypeKind::UnresolvedTypeSlot,
crate::type_coverage::WeakTypeKind::CodeDynamic,
]);
let mut unresolved_dynamic_occurrences = 0usize;
let mut unresolved_dynamic_definitions = 0usize;
for (namespace, file) in &snapshot.files {
if namespace.ends_with(".$meta") || !(namespace == &snapshot.package || namespace.starts_with(&format!("{}.", snapshot.package))) {
continue;
}
for (definition, entry) in &file.defs {
if let Some(row) = crate::type_coverage::analyze_weak_types_entry(namespace, definition, entry, &selected) {
let hits = row
.occurrences
.iter()
.filter(|occurrence| occurrence.intent == crate::type_coverage::WeakTypeIntent::Unresolved)
.count();
if hits > 0 {
unresolved_dynamic_definitions += 1;
unresolved_dynamic_occurrences += hits;
}
}
}
}
if unresolved_dynamic_occurrences > 0 {
advisories.push(format!(
"[W_DYNAMIC_TYPE_DEBT] Found {unresolved_dynamic_occurrences} unresolved dynamic or unbound type-slot occurrence(s) in {unresolved_dynamic_definitions} local definition(s); formatting does not guess or rewrite semantic type contracts.\n\
Next: run `calcit {snapshot_arg} analyze weak-types --only schema-dynamic,unresolved-type-slot,code-dynamic --intent unresolved --summary-only`, then rerun without `--summary-only` for paths and recommendations."
));
}
advisories
}
fn edn_key_matches(value: &Edn, expected: &str) -> bool {
match value {
Edn::Tag(tag) => tag.ref_str() == expected,
Edn::Str(text) | Edn::Symbol(text) => text.as_ref() == expected,
_ => false,
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct TransactionOperationReport {
pub(crate) index: usize,
pub(crate) args: Vec<String>,
pub(crate) stdout: String,
pub(crate) stderr: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct TransactionReport {
schema_version: u8,
command: &'static str,
dry_run: bool,
pub(crate) changed: bool,
pub(crate) original_revision: String,
pub(crate) new_revision: String,
pub(crate) scoped_revision: Option<String>,
operations: Vec<TransactionOperationReport>,
}
pub(crate) fn snapshot_content_revision(content: &str) -> String {
let mut hasher = Md5::new();
hasher.update(content.as_bytes());
format!("md5:{}", hex::encode(hasher.finalize()))
}
fn transaction_edn_arg(value: &cirru_edn::Edn) -> Result<String, String> {
match value {
cirru_edn::Edn::Str(value) | cirru_edn::Edn::Symbol(value) => Ok(value.to_string()),
cirru_edn::Edn::Tag(value) => Ok(format!(":{}", value.ref_str())),
cirru_edn::Edn::Bool(value) => Ok(value.to_string()),
cirru_edn::Edn::Number(value) => Ok(value.to_string()),
cirru_edn::Edn::Nil => Ok("nil".to_string()),
cirru_edn::Edn::Quote(code) => {
let quoted = Cirru::List(vec![Cirru::leaf("quote"), code.clone()]);
cirru_parser::format(
std::slice::from_ref("ed),
cirru_parser::CirruWriterOptions { use_inline: true },
)
.map_err(|error| format!("Failed to format quoted transaction code argument: {error}"))
}
other => Err(format!("Transaction arguments must be scalar values or quoted code, got: {other}")),
}
}
fn parse_transaction_operations(raw: &str) -> Result<Vec<Vec<String>>, String> {
let trimmed = raw.trim();
if trimmed.is_empty() {
return Err("Transaction input is empty. Provide a Cirru EDN list of command argument lists (JSON is also accepted).".to_string());
}
let operations = if trimmed.starts_with('[') && !trimmed.starts_with("[]") {
serde_json::from_str::<Vec<Vec<String>>>(trimmed)
.map_err(|error| format!("Failed to parse transaction JSON as a list of argument lists: {error}"))?
} else {
let value = cirru_edn::parse(trimmed).map_err(|error| format!("Failed to parse transaction Cirru EDN: {error}"))?;
let cirru_edn::Edn::List(outer) = value else {
return Err("Transaction Cirru EDN must be a list (`[]`) of command argument lists.".to_string());
};
outer
.0
.iter()
.enumerate()
.map(|(index, operation)| {
let cirru_edn::Edn::List(args) = operation else {
return Err(format!(
"Transaction operation {} must be a list (`[]`) of CLI arguments.",
index + 1
));
};
args.0.iter().map(transaction_edn_arg).collect::<Result<Vec<_>, _>>()
})
.collect::<Result<Vec<_>, _>>()?
};
if operations.is_empty() {
return Err("Transaction must contain at least one operation.".to_string());
}
for (index, operation) in operations.iter().enumerate() {
let Some(group) = operation.first().map(String::as_str) else {
return Err(format!("Transaction operation {} is empty.", index + 1));
};
if !matches!(group, "edit" | "tree" | "config") {
return Err(format!(
"Transaction operation {} starts with unsupported command group '{group}'. Only edit, tree, and config mutations are allowed.",
index + 1
));
}
if group == "edit" && operation.get(1).is_some_and(|subcommand| subcommand == "transaction") {
return Err(format!(
"Transaction operation {} cannot contain a nested edit transaction.",
index + 1
));
}
let Some(subcommand) = operation.get(1).map(String::as_str) else {
return Err(format!(
"Transaction operation {} is missing a subcommand after '{group}'.",
index + 1
));
};
let supported = match group {
"edit" => matches!(
subcommand,
"format"
| "def"
| "mv-def"
| "rm-def"
| "meta"
| "schema"
| "ffi"
| "add-test"
| "add-ns"
| "rm-ns"
| "ns"
| "imports"
| "add-import"
| "rm-import"
| "rename"
| "split-def"
),
"tree" => matches!(
subcommand,
"rewrite" | "search-replace" | "replace" | "replace-leaf" | "delete" | "insert" | "swap" | "unwrap" | "raise" | "wrap"
),
"config" => matches!(
subcommand,
"set" | "unset" | "add-entry" | "add-module" | "rm-module" | "set-type-slot" | "rm-type-slot"
),
_ => false,
};
if let Some(error) = super::normalize::removed_transaction_operation_error(index, group, subcommand) {
return Err(error);
}
if !supported {
return Err(format!(
"Transaction operation {} uses unsupported staged mutation '{group} {subcommand}'. Read-only commands and unsupported edits must run outside the transaction.",
index + 1
));
}
}
Ok(operations)
}
#[cfg(test)]
fn run_staged_transaction_with<F>(
snapshot_file: &Path,
operations: &[Vec<String>],
expected_revision: Option<&str>,
dry_run: bool,
run_operation: F,
) -> Result<TransactionReport, String>
where
F: FnMut(&Path, usize, &[String]) -> Result<TransactionOperationReport, String>,
{
run_staged_transaction_with_options(snapshot_file, operations, expected_revision, dry_run, false, run_operation)
}
fn run_staged_transaction_with_preserving_schemas<F>(
snapshot_file: &Path,
operations: &[Vec<String>],
expected_revision: Option<&str>,
dry_run: bool,
run_operation: F,
) -> Result<TransactionReport, String>
where
F: FnMut(&Path, usize, &[String]) -> Result<TransactionOperationReport, String>,
{
run_staged_transaction_with_options(snapshot_file, operations, expected_revision, dry_run, true, run_operation)
}
pub(crate) fn run_staged_transaction_with_options<F>(
snapshot_file: &Path,
operations: &[Vec<String>],
expected_revision: Option<&str>,
dry_run: bool,
preserve_untouched_schemas: bool,
mut run_operation: F,
) -> Result<TransactionReport, String>
where
F: FnMut(&Path, usize, &[String]) -> Result<TransactionOperationReport, String>,
{
let original_content =
fs::read_to_string(snapshot_file).map_err(|error| format!("Failed to read snapshot '{}': {error}", snapshot_file.display()))?;
let original_revision = snapshot_content_revision(&original_content);
let original_units = load_snapshot_for_metadata(&snapshot_file.to_string_lossy())
.ok()
.map(|snapshot| super::snapshot_scope::snapshot_units(&snapshot))
.transpose()?;
let guarded_units = match expected_revision {
Some(expected) if super::snapshot_scope::is_scoped_revision(expected) => {
let units = original_units
.as_ref()
.ok_or("A scoped revision needs a Snapshot the current CLI can load; use the full revision instead.")?;
Some(super::snapshot_scope::check_scoped_revision(expected, units)?)
}
Some(expected) if expected != original_revision => {
return Err(format!(
"Snapshot revision mismatch: expected '{expected}', current revision is '{original_revision}'. Re-run the query and rebuild the transaction."
));
}
_ => None,
};
let staged = stage_atomic_file(snapshot_file, original_content.as_bytes(), "transaction snapshot")?;
let mut operation_reports = Vec::with_capacity(operations.len());
for (index, operation) in operations.iter().enumerate() {
operation_reports.push(run_operation(staged.path(), index, operation)?);
}
let staged_path = staged.path().to_string_lossy();
let staged_snapshot = load_snapshot(&staged_path)?;
let staged_units = super::snapshot_scope::snapshot_units(&staged_snapshot)?;
let unchanged_namespace_views = operations
.iter()
.all(|operation| operation.first().is_some_and(|group| group == "edit") && operation.get(1).is_some_and(|name| name == "ns"))
&& original_units.as_ref().is_some_and(|units| units == &staged_units);
let staged_content = if unchanged_namespace_views {
original_content.clone()
} else {
let rendered_content = render_snapshot_content(&staged_snapshot)?;
if preserve_untouched_schemas
&& !operations.iter().any(|operation| {
operation.first().is_some_and(|group| group == "edit") && operation.get(1).is_some_and(|name| name == "format")
})
{
restore_untouched_schema_forms(&original_content, &rendered_content, &staged_snapshot, &staged_path, operations)?
} else {
rendered_content
}
};
staged.write_and_sync(staged_content.as_bytes(), "transaction snapshot")?;
let new_revision = snapshot_content_revision(&staged_content);
let changed = original_content != staged_content;
let touched = original_units
.as_ref()
.map(|units| (units, super::snapshot_scope::changed_units(units, &staged_units)));
if let (Some(guarded), Some((_, touched))) = (&guarded_units, &touched) {
let unguarded = touched.iter().filter(|unit| !guarded.contains(*unit)).cloned().collect::<Vec<_>>();
if !unguarded.is_empty() {
return Err(format!(
"Definition conflict: the transaction now also changes {}, which the scoped revision does not cover. Re-run the dry-run and review the new plan.",
unguarded.join(", ")
));
}
}
let scoped_revision = touched.map(|(units, touched)| super::snapshot_scope::scoped_revision(units, &touched));
let current_content =
fs::read_to_string(snapshot_file).map_err(|error| format!("Failed to re-read snapshot '{}': {error}", snapshot_file.display()))?;
let current_revision = snapshot_content_revision(¤t_content);
if current_revision != original_revision {
return Err(format!(
"Snapshot changed while transaction was running: started at '{original_revision}', now '{current_revision}'. No transaction changes were written."
));
}
if !dry_run && changed {
staged.commit()?;
}
Ok(TransactionReport {
schema_version: 1,
command: "edit.transaction",
dry_run,
changed,
original_revision,
new_revision,
scoped_revision,
operations: operation_reports,
})
}
fn run_transaction_child(stage_path: &Path, index: usize, args: &[String]) -> Result<TransactionOperationReport, String> {
let executable = std::env::current_exe().map_err(|error| format!("Failed to locate current calcit executable: {error}"))?;
let output = Command::new(&executable)
.arg("--tips-level")
.arg("none")
.env("CALCIT_CURSOR_MAINTENANCE", "disabled")
.arg(stage_path)
.args(args)
.output()
.map_err(|error| format!("Failed to run transaction operation {} ({args:?}): {error}", index + 1))?;
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
if !output.status.success() {
return Err(format!(
"Transaction operation {} failed: {}\nstdout:\n{}\nstderr:\n{}",
index + 1,
args.join(" "),
stdout.trim_end(),
stderr.trim_end()
));
}
Ok(TransactionOperationReport {
index,
args: args.to_vec(),
stdout,
stderr,
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct StagedFixReport {
pub(crate) changed: bool,
pub(crate) original_revision: String,
pub(crate) new_revision: String,
}
pub(crate) fn run_staged_fix_transaction(
snapshot_file: &Path,
operations: &[Vec<String>],
expected_revision: Option<&str>,
dry_run: bool,
validation_entry: &str,
validation_args: &[String],
allowed_warning_identities: Option<&[String]>,
) -> Result<StagedFixReport, String> {
if operations.is_empty() {
let content =
fs::read_to_string(snapshot_file).map_err(|error| format!("Failed to read snapshot '{}': {error}", snapshot_file.display()))?;
let revision = snapshot_content_revision(&content);
if let Some(expected) = expected_revision
&& expected != revision
{
return Err(format!(
"Snapshot revision mismatch: expected '{expected}', current revision is '{revision}'. Re-run `calcit fix` and review the new plan."
));
}
return Ok(StagedFixReport {
changed: false,
original_revision: revision.clone(),
new_revision: revision,
});
}
guard_snapshot_mutation_toolchain(&snapshot_file.to_string_lossy())?;
let operation_count = operations.len();
let report = run_staged_transaction_with_preserving_schemas(
snapshot_file,
operations,
expected_revision,
dry_run,
|stage_path, index, args| {
let operation = run_transaction_child(stage_path, index, args)?;
if index + 1 == operation_count {
validate_staged_fix(stage_path, validation_entry, validation_args, allowed_warning_identities)?;
}
Ok(operation)
},
)?;
Ok(StagedFixReport {
changed: report.changed,
original_revision: report.original_revision,
new_revision: report.new_revision,
})
}
fn validate_staged_fix(
stage_path: &Path,
validation_entry: &str,
validation_args: &[String],
allowed_warning_identities: Option<&[String]>,
) -> Result<(), String> {
let executable = std::env::current_exe().map_err(|error| format!("Failed to locate current calcit executable: {error}"))?;
let output = Command::new(&executable)
.args(staged_fix_validation_args(stage_path, validation_entry, validation_args))
.env("CALCIT_FIX_VALIDATE_ONLY", "1")
.output()
.map_err(|error| format!("Failed to validate staged fixes: {error}"))?;
if output.status.success() {
if let Some(allowed) = allowed_warning_identities {
let current = serde_json::from_slice::<Vec<String>>(&output.stdout).map_err(|error| {
format!(
"Staged fix validation returned invalid warning evidence: {error}\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout).trim_end(),
String::from_utf8_lossy(&output.stderr).trim_end()
)
})?;
let unexpected = staged_warning_difference(allowed, ¤t);
if !unexpected.is_empty() {
return Err(format!(
"Staged fix introduced compiler warnings; no changes were written:\n{}",
unexpected.join("\n")
));
}
}
Ok(())
} else {
Err(format!(
"Staged fixes failed preprocessing; no changes were written.\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout).trim_end(),
String::from_utf8_lossy(&output.stderr).trim_end()
))
}
}
fn staged_fix_validation_args(stage_path: &Path, validation_entry: &str, validation_args: &[String]) -> Vec<OsString> {
let mut args = vec![
OsString::from("--tips-level"),
OsString::from("none"),
OsString::from("--entry"),
OsString::from(validation_entry),
stage_path.as_os_str().to_owned(),
OsString::from("fix"),
];
args.extend(validation_args.iter().map(OsString::from));
args
}
fn staged_warning_difference(allowed: &[String], current: &[String]) -> Vec<String> {
let mut remaining = BTreeMap::<&str, usize>::new();
for warning in allowed {
*remaining.entry(warning).or_default() += 1;
}
let mut unexpected = Vec::new();
for warning in current {
match remaining.get_mut(warning.as_str()) {
Some(count) if *count > 0 => *count -= 1,
_ => unexpected.push(warning.clone()),
}
}
unexpected
}
fn handle_transaction(opts: &EditTransactionCommand, snapshot_file: &str) -> Result<(), String> {
let output_format = StructuredOutputFormat::parse(&opts.format, "transaction")?;
let _structured_guard = super::common::StructuredMutationOutputGuard::new(output_format != StructuredOutputFormat::Human);
let raw = read_code_input(&opts.file, &opts.code)?.ok_or(
"Transaction input required: use --file, --code, or pipe a Cirru EDN list of argument lists via stdin (JSON is also accepted)",
)?;
let operations = parse_transaction_operations(&raw)?;
let report = run_staged_transaction_with_preserving_schemas(
Path::new(snapshot_file),
&operations,
opts.expect_revision.as_deref(),
opts.dry_run,
run_transaction_child,
)?;
match output_format {
StructuredOutputFormat::Json => println!(
"{}",
serde_json::to_string(&report).map_err(|error| format!("Failed to serialize transaction result: {error}"))?
),
StructuredOutputFormat::Edn => {
let value = serde_json::to_value(&report).map_err(|error| format!("Failed to encode transaction result: {error}"))?;
println!("{}", format_json_value_as_edn(&value)?);
}
StructuredOutputFormat::Human => {
println!("# Edit transaction\n");
println!("- mode: `{}`", if opts.dry_run { "preview" } else { "apply" });
println!("- original revision: `{}`", report.original_revision);
println!("- new revision: `{}`", report.new_revision);
if let Some(scoped) = &report.scoped_revision {
println!("- scoped revision: `{scoped}`");
}
println!("- changed: `{}`", report.changed);
println!("- operations: `{}`", report.operations.len());
for operation in &report.operations {
println!("\n## Operation {}\n", operation.index + 1);
println!("```text");
println!("{}", operation.args.join(" "));
println!("```");
}
}
}
Ok(())
}
pub(crate) fn load_snapshot(snapshot_file: &str) -> Result<Snapshot, String> {
let edn = read_snapshot_edn(snapshot_file)?;
snapshot::load_snapshot_data(&edn, snapshot_file).map_err(|e| format!("Failed to load snapshot: {e}"))
}
fn load_snapshot_for_metadata(snapshot_file: &str) -> Result<Snapshot, String> {
let edn = read_snapshot_edn(snapshot_file)?;
snapshot::load_snapshot_data_for_metadata(&edn, snapshot_file, None)
}
fn read_snapshot_edn(snapshot_file: &str) -> Result<Edn, String> {
let mut content = fs::read_to_string(snapshot_file).map_err(|e| format!("Failed to read {snapshot_file}: {e}"))?;
strip_shebang(&mut content);
cirru_edn::parse(&content).map_err(|e| format!("Failed to parse EDN: {e}"))
}
pub(crate) fn save_snapshot(snapshot: &Snapshot, snapshot_file: &str) -> Result<(), String> {
save_snapshot_to_file(snapshot_file, snapshot)
}
pub(crate) fn check_ns_editable(snapshot: &Snapshot, namespace: &str) -> Result<(), String> {
let pkg = &snapshot.package;
if namespace == pkg || namespace.starts_with(&format!("{pkg}.")) {
Ok(())
} else {
Err(format!(
"Cannot modify namespace '{namespace}': only namespaces under package '{pkg}' can be edited.\nThis namespace belongs to a dependency or core library."
))
}
}
fn source_declares_macro(entry: &CodeEntry) -> bool {
matches!(&entry.code, Cirru::List(items) if items.first().is_some_and(|head| head.eq_leaf("defmacro")))
}
pub(crate) fn definition_head_is_macro(snapshot_file: &str, snapshot: &Snapshot, namespace: &str, head: &str) -> Result<bool, String> {
definition_head_macro_code(snapshot_file, snapshot, namespace, head).map(|found| found.is_some())
}
pub(crate) fn definition_head_macro_code(
snapshot_file: &str,
snapshot: &Snapshot,
namespace: &str,
head: &str,
) -> Result<Option<(Cirru, FileInSnapShot)>, String> {
let macro_code = |file: &FileInSnapShot, name: &str| {
file
.defs
.get(name)
.filter(|entry| source_declares_macro(entry))
.map(|entry| (entry.code.clone(), file.clone()))
};
let file = &snapshot.files[namespace];
let imports = calcit_core::program::extract_import_map(&file.ns.code, namespace)?;
let (source_ns, source_def) = if let Some((prefix, name)) = head.split_once('/') {
let source_ns = match imports.get(prefix).map(|rule| rule.as_ref()) {
Some(calcit_core::program::ImportRule::NsAs(target)) => target.as_ref(),
Some(_) => return Ok(None),
None => prefix,
};
(source_ns, name)
} else if file.defs.contains_key(head) {
(namespace, head)
} else if let Some(rule) = imports.get(head) {
match rule.as_ref() {
calcit_core::program::ImportRule::NsReferDef(target, name) => (target.as_ref(), name.as_ref()),
_ => return Ok(None),
}
} else {
(calcit_core::calcit::CORE_NS, head)
};
if let Some(file) = snapshot.files.get(source_ns) {
return Ok(macro_code(file, source_def));
}
if source_ns == calcit_core::calcit::CORE_NS {
let core = calcit_core::load_core_snapshot()?;
return Ok(macro_code(&core.files[source_ns], source_def));
}
let base_dir = Path::new(snapshot_file).parent().unwrap_or_else(|| Path::new("."));
let module_folder = calcit_core::project_module_folder(base_dir);
let modules = snapshot
.entries
.values()
.flat_map(|entry| entry.modules.iter())
.collect::<std::collections::BTreeSet<_>>();
let mut load_errors = Vec::new();
for module in modules {
match super::load_module_with_sources_silent(module, base_dir, &module_folder) {
Ok(loaded) => {
if let Some(file) = loaded.snapshot.files.get(source_ns) {
return Ok(macro_code(file, source_def));
}
}
Err(error) => load_errors.push(format!("{module}: {error}")),
}
}
if !load_errors.is_empty() {
return Err(format!(
"Unrecognized definition head '{head}': cannot resolve namespace '{source_ns}'; module load failures:\n{}\nRepair the dependency sources and retry this edit.",
load_errors.join("\n")
));
}
Ok(None)
}
fn replace_definition_code(entry: &mut CodeEntry, code: Cirru, derived_macro_schema: Option<Arc<CalcitTypeAnnotation>>) {
entry.code = code;
if snapshot::code_declares_defexternal(&entry.code) {
entry.ffi = None;
}
if let Some(schema) = derived_macro_schema
&& !matches!(entry.schema.as_ref(), CalcitTypeAnnotation::Macro(_))
{
entry.schema = schema;
}
}
fn is_core_defimpl(snapshot_file: &str, snapshot: &Snapshot, namespace: &str, head: &str) -> Result<bool, String> {
if head != "defimpl" && !head.ends_with("/defimpl") {
return Ok(false);
}
Ok(
definition_head_macro_code(snapshot_file, snapshot, namespace, head)?.is_some_and(|(_, source)| {
matches!(&source.ns.code, Cirru::List(items)
if items.get(1).is_some_and(|name| name.eq_leaf(calcit_core::calcit::CORE_NS)))
}),
)
}
pub(crate) fn validate_definition_shape(
snapshot_file: &str,
snapshot: &Snapshot,
namespace: &str,
definition: &str,
code: &Cirru,
allow_unknown_head: bool,
) -> Result<(), String> {
snapshot::validate_definition_root(code, &format!("{namespace}/{definition}"))?;
let Cirru::List(items) = code else {
return Err(format!(
"Definition '{namespace}/{definition}' must be a named definition expression, not a leaf."
));
};
if items.first().is_some_and(|head| head.eq_leaf("fn")) {
return if matches!(items.get(1), Some(Cirru::List(_))) && items.len() >= 3 {
Ok(())
} else {
Err(format!(
"Definition '{namespace}/{definition}': fn requires a parameter list and a body."
))
};
}
if items.first().is_some_and(|head| head.eq_leaf("deftype-slot")) {
return if items.len() == 2 && matches!(&items[1], Cirru::Leaf(name) if name.starts_with(':') || name.starts_with('|')) {
Ok(())
} else {
Err(format!(
"Definition '{namespace}/{definition}': deftype-slot requires exactly one tag or string slot name."
))
};
}
if let Some(Cirru::Leaf(head)) = items.first()
&& is_core_defimpl(snapshot_file, snapshot, namespace, head)?
{
let is_symbol = |index| {
matches!(items.get(index), Some(node @ Cirru::Leaf(_))
if matches!(calcit_core::data::cirru::code_to_calcit(node, namespace, definition, vec![]), Ok(calcit_core::Calcit::Symbol { .. })))
};
return if is_symbol(1) && is_symbol(2) {
Ok(())
} else {
Err(format!(
"Definition '{namespace}/{definition}': defimpl requires a receiver type symbol and a trait symbol."
))
};
}
let (Some(Cirru::Leaf(head)), Some(Cirru::Leaf(name))) = (items.first(), items.get(1)) else {
return Err(format!(
"Definition '{namespace}/{definition}' requires a definition head and a symbol name."
));
};
let unchanged = snapshot.files[namespace]
.defs
.get(definition)
.is_some_and(|entry| &entry.code == code);
if name.as_ref() != definition && !unchanged {
return Err(format!(
"Definition name mismatch: expected '{definition}', got '{name}' in '{namespace}/{definition}'."
));
}
if !allow_unknown_head
&& !snapshot::DEFINITION_HEADS.contains(&head.as_ref())
&& !definition_head_is_macro(snapshot_file, snapshot, namespace, head)?
{
return Err(format!(
"Unrecognized definition head '{head}' for '{namespace}/{definition}'. Expected {}, or a source-declared macro from this namespace, imports or core. Use --allow-unknown-head only for an intentional custom definition form.",
snapshot::DEFINITION_HEADS.join(", ")
));
}
Ok(())
}
fn handle_def(opts: &EditDefCommand, snapshot_file: &str) -> Result<(), String> {
let (namespace, definition) = parse_target(&opts.target)?;
let raw = read_code_input(&opts.file, &opts.code)?.ok_or(ERR_CODE_INPUT_REQUIRED)?;
let syntax_tree = decode_mutation_syntax_input(&raw, opts.input_format)?;
let derived_macro_schema = snapshot::conservative_macro_schema(&syntax_tree, &format!("definition '{namespace}/{definition}'"))?;
snapshot::validate_defexternal_shorthand(&syntax_tree, &format!("{namespace}/{definition}"))?;
let mut snapshot = load_snapshot(snapshot_file)?;
check_ns_editable(&snapshot, namespace)?;
let file_data = snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
let resolved_definition = definition;
let exists = file_data.defs.contains_key(resolved_definition);
let previous_entry = if exists {
file_data.defs.get(resolved_definition).cloned()
} else {
None
};
validate_definition_shape(
snapshot_file,
&snapshot,
namespace,
resolved_definition,
&syntax_tree,
opts.allow_unknown_head,
)?;
let existing_edit_advice = previous_entry
.as_ref()
.and_then(|entry| format_existing_definition_advice(namespace, resolved_definition, &entry.code, &syntax_tree));
if opts.overwrite
&& let Some(advice) = existing_edit_advice.as_deref()
{
print_cli_warning_block(advice);
}
if exists && !opts.overwrite {
if let Some(advice) = existing_edit_advice.as_deref() {
print_cli_warning_block(advice);
}
return Err(format!(
"Definition '{resolved_definition}' already exists in namespace '{namespace}'.\n\
Use --overwrite to replace it. For full-definition rewrites, prefer: calcit edit def {namespace}/{resolved_definition} --overwrite --file <file>"
));
}
let mut code_entry = previous_entry.unwrap_or_else(|| CodeEntry::from_code(syntax_tree.clone()));
replace_definition_code(&mut code_entry, syntax_tree, derived_macro_schema);
snapshot
.files
.get_mut(namespace)
.expect("validated local namespace")
.defs
.insert(resolved_definition.to_string(), code_entry);
save_snapshot(&snapshot, snapshot_file)?;
let action_label = if exists { "Updated" } else { "Created" };
println!(
"{} {} definition '{}' in namespace '{}'",
"✓".green(),
action_label,
resolved_definition.cyan(),
namespace
);
if command_guidance_enabled() {
println!();
println!("{}", "Next steps:".blue().bold());
println!(
" • View definition: {} '{}/{}'",
"calcit query def".cyan(),
namespace,
resolved_definition
);
println!(" • Check errors: {}", "calcit query error".cyan());
println!(
" • Find usages: {} '{}/{}'",
"calcit query usages".cyan(),
namespace,
resolved_definition
);
println!(
" • Add to imports: {} <target-ns> '{}' --refer '{}'",
"calcit edit add-import".cyan(),
namespace,
resolved_definition
);
println!();
let mut tips = Tips::new();
tips.add(format!(
"Use single quotes around '{namespace}/{resolved_definition}' to avoid shell escaping issues."
));
tips.add(format!("Example: calcit tree show '{namespace}/{resolved_definition}'"));
tips.print();
}
Ok(())
}
fn format_existing_definition_advice(namespace: &str, definition: &str, existing: &Cirru, incoming: &Cirru) -> Option<String> {
let advice = analyze_cirru_edit_advice(existing, incoming)?;
let changed_nodes = advice.stats.added + advice.stats.removed + advice.stats.modified;
let target = format!("{namespace}/{definition}");
let mut lines = vec![format!(
"Incoming code is {:.0}% structurally similar to the existing definition (changed nodes: ~{} +{} -{}).",
advice.similarity * 100.0,
advice.stats.modified,
advice.stats.added,
advice.stats.removed,
)];
match advice.strategy {
CirruEditStrategy::Identical => {
lines.push("The incoming definition is identical. Prefer skipping the write and inspect the current code first.".to_string());
lines.push(format!("Inspect: calcit query def '{target}'"));
}
CirruEditStrategy::Replace => {
lines.push("Most differences are replacements. Prefer a local tree edit instead of a full overwrite.".to_string());
lines.push(format!(
"Try: calcit tree search-replace '{target}' --pattern '<leaf>' --code '(quote |<new-leaf>')"
));
lines.push(format!(
"Or: calcit tree replace '{target}' --path '<path>' --code '(quote |<code>)'"
));
}
CirruEditStrategy::Insert => {
lines.push("Most differences are additive. Prefer inserting nodes into the existing tree.".to_string());
lines.push(format!(
"Try: calcit tree insert '{target}' --at before --path '<path>' --code '<node>'"
));
lines.push(format!(
"Or: calcit tree insert '{target}' --at after --path '<path>' --code '<node>' / calcit tree insert '{target}' --at append-child --path '<path>' --code '<node>'"
));
}
CirruEditStrategy::Delete => {
lines.push("Most differences are removals. Prefer deleting or lifting nodes from the existing tree.".to_string());
lines.push(format!("Try: calcit tree delete '{target}' --path '<path>'"));
lines.push(format!("Or: calcit tree raise '{target}' --path '<child-path>'"));
}
CirruEditStrategy::Rewrite => {
lines.push("The trees are still close, but the change mixes insert/remove/replace. Prefer a structural rewrite over a blind full overwrite.".to_string());
lines.push(format!(
"Try: calcit tree rewrite '{target}' --path '<path>' --with self=. --code '<code>'"
));
lines.push(format!("Or: calcit tree replace '{target}' --path '<path>' --code '<code>'"));
}
}
if advice.strategy != CirruEditStrategy::Identical || changed_nodes > 0 {
lines.push(format!(
"Locate the smallest path first: calcit query search '<keyword>' --filter '{target}' && calcit tree show '{target}' --path '<path>'"
));
}
Some(lines.join("\n"))
}
fn map_at_to_operation(at: &str) -> Result<TreeOperation, String> {
TreeOperation::from_insert_position(at)
.ok_or_else(|| format!("Unsupported position '{at}'. Use: before, after, prepend-child, append-child, replace"))
}
pub(super) fn move_node(target: &str, from: &str, path: &str, at: &str, snapshot_file: &str) -> Result<(), String> {
guard_snapshot_mutation_toolchain(snapshot_file)?;
let (namespace, definition) = parse_target(target)?;
let from_path = parse_path(from)?;
let to_path = parse_path(path)?;
if from_path.is_empty() {
return Err("Cannot move root node".to_string());
}
if from_path == to_path {
return Err("Source and destination paths are identical; nothing to move.".to_string());
}
if path_is_strict_descendant(&from_path, &to_path) {
return Err(format!("Cannot move node at [{from}] into its own subtree at [{path}]"));
}
let operation = map_at_to_operation(at)?;
let mut snapshot = load_snapshot(snapshot_file)?;
check_ns_editable(&snapshot, namespace)?;
let file_data = snapshot
.files
.get_mut(namespace)
.ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
let resolved_definition =
resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), false)?.resolved;
let code_entry = file_data
.defs
.get_mut(resolved_definition.as_str())
.expect("resolved definition exists");
let source_node = navigate_to_path(&code_entry.code, &from_path)?;
let append_index = if operation == TreeOperation::AppendChild {
match navigate_to_path(&code_entry.code, &to_path)? {
Cirru::List(children) => children.len(),
Cirru::Leaf(_) => 0,
}
} else {
0
};
let after_insert = apply_operation_at_path(&code_entry.code, &to_path, operation, Some(&source_node))?;
let adjusted_from = adjusted_source_path_after_insertion(&from_path, &to_path, operation);
let final_code = apply_operation_at_path(&after_insert, &adjusted_from, TreeOperation::Delete, None)?;
code_entry.code = final_code;
save_snapshot(&snapshot, snapshot_file)?;
maintain_cursor_after_node_move(
snapshot_file,
&format!("{namespace}/{resolved_definition}"),
&from_path,
&to_path,
operation,
append_index,
)?;
println!(
"{} Moved node from [{}] to [{}] ({}) in '{}/{}'",
"✓".green(),
from,
path,
at,
namespace,
resolved_definition
);
Ok(())
}
pub(crate) fn rename_definition_declaration(
snapshot_file: &str,
snapshot: &Snapshot,
namespace: &str,
code: &Cirru,
old_name: &str,
new_name: &str,
) -> Result<(Cirru, bool), String> {
let Cirru::List(items) = code else {
return Ok((code.clone(), false));
};
let Some(Cirru::Leaf(head)) = items.first() else {
return Ok((code.clone(), false));
};
if is_core_defimpl(snapshot_file, snapshot, namespace, head)? {
return Ok((code.clone(), false));
}
if !head.starts_with("def") {
return Ok((code.clone(), false));
}
let Some(name_node) = items.get(1) else {
return Err(format!("Definition form `{head}` has no declaration name"));
};
let Cirru::Leaf(declared_name) = name_node else {
return Err(format!("Definition form `{head}` has a non-leaf declaration name"));
};
if declared_name.as_ref() != old_name {
return Err(format!(
"Definition key `{old_name}` does not match declaration name `{declared_name}`. Repair the mismatch before renaming."
));
}
let mut next_items = items.clone();
next_items[1] = Cirru::Leaf(Arc::from(new_name));
Ok((Cirru::List(next_items), true))
}
fn handle_rename(opts: &EditRenameCommand, snapshot_file: &str) -> Result<(), String> {
let (namespace, definition) = parse_target(&opts.source)?;
let mut snapshot = load_snapshot(snapshot_file)?;
check_ns_editable(&snapshot, namespace)?;
let file_data = snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
let resolved_definition =
resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), false)?.resolved;
if file_data.defs.contains_key(&opts.new_name) {
return Err(format!(
"Definition '{}' already exists in namespace '{}'. Use 'calcit edit mv-def' to move to a different namespace.",
opts.new_name, namespace
));
}
let (renamed_code, _) = rename_definition_declaration(
snapshot_file,
&snapshot,
namespace,
&file_data.defs[resolved_definition.as_str()].code,
&resolved_definition,
&opts.new_name,
)?;
let before = defimpl_edit_baseline(
snapshot_file,
&snapshot,
namespace,
&file_data.defs[resolved_definition.as_str()].code,
)?;
let file_data = snapshot.files.get_mut(namespace).expect("resolved namespace exists");
let mut entry = file_data
.defs
.remove(resolved_definition.as_str())
.expect("resolved definition exists");
entry.code = renamed_code;
file_data.defs.insert(opts.new_name.clone(), entry);
if let Some(before) = before {
check_defimpl_destination(
snapshot_file,
&before,
&snapshot,
namespace,
namespace,
&snapshot.files[namespace].defs[&opts.new_name].code,
)?;
}
save_snapshot(&snapshot, snapshot_file)?;
println!(
"{} Renamed '{}' to '{}' in namespace '{}'",
"✓".green(),
resolved_definition.cyan(),
opts.new_name.cyan(),
namespace
);
Ok(())
}
fn handle_split_def(opts: &EditSplitDefCommand, snapshot_file: &str) -> Result<(), String> {
let (namespace, definition) = parse_target(&opts.target)?;
let path = parse_path(&opts.path)?;
let new_name = opts.new_name.trim();
if path.is_empty() {
return Err(
"Cannot split at the root path: the root IS the definition. Use 'calcit edit def' to create a new definition from scratch."
.to_string(),
);
}
if new_name.is_empty() {
return Err("New definition name cannot be empty".to_string());
}
let mut snapshot = load_snapshot(snapshot_file)?;
check_ns_editable(&snapshot, namespace)?;
let file_data = snapshot
.files
.get_mut(namespace)
.ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
let resolved_definition =
resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), false)?.resolved;
if file_data.defs.contains_key(new_name) {
return Err(format!(
"Definition '{new_name}' already exists in namespace '{namespace}'. Choose a different name or remove the existing one first."
));
}
let extracted = navigate_to_path(&file_data.defs[resolved_definition.as_str()].code, &path)?;
let new_ref = Cirru::Leaf(Arc::from(new_name));
let updated_code = apply_operation_at_path(
&file_data.defs[resolved_definition.as_str()].code,
&path,
TreeOperation::Replace,
Some(&new_ref),
)?;
file_data
.defs
.get_mut(resolved_definition.as_str())
.expect("resolved definition exists")
.code = updated_code;
let new_entry = CodeEntry::from_code(extracted);
file_data.defs.insert(new_name.to_string(), new_entry);
save_snapshot(&snapshot, snapshot_file)?;
println!(
"{} Extracted node at [{}] from '{}/{}' → new definition '{}'",
"✓".green(),
opts.path,
namespace,
resolved_definition.cyan(),
new_name.cyan()
);
if command_guidance_enabled() {
println!();
println!("{}", "Next steps:".blue().bold());
println!(" • Inspect new def: {} '{}/{}'", "calcit query def".cyan(), namespace, new_name);
println!(
" • Inspect source: {} '{}/{}'",
"calcit query def".cyan(),
namespace,
resolved_definition
);
println!(
" • Wrap in defn: {} '{}/{}' --path '' --code 'quote (defn {} ...)'",
"calcit tree replace".cyan(),
namespace,
new_name,
new_name
);
}
Ok(())
}
fn handle_rm_def(opts: &EditRmDefCommand, snapshot_file: &str) -> Result<(), String> {
let (namespace, definition) = parse_target(&opts.target)?;
let mut snapshot = load_snapshot(snapshot_file)?;
check_ns_editable(&snapshot, namespace)?;
let file_data = snapshot
.files
.get_mut(namespace)
.ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
let resolved_definition =
resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), false)?.resolved;
file_data
.defs
.remove(resolved_definition.as_str())
.expect("resolved definition exists");
save_snapshot(&snapshot, snapshot_file)?;
println!(
"{} Deleted definition '{}' from namespace '{}'",
"✓".green(),
resolved_definition.cyan(),
namespace
);
Ok(())
}
fn check_defimpl_destination(
snapshot_file: &str,
before: &Snapshot,
staged: &Snapshot,
source_ns: &str,
target_ns: &str,
code: &Cirru,
) -> Result<(), String> {
let Cirru::List(items) = code else { return Ok(()) };
let Some(Cirru::Leaf(head)) = items.first() else { return Ok(()) };
if !is_core_defimpl(snapshot_file, before, source_ns, head)? {
return Ok(());
}
let (Some(Cirru::Leaf(receiver)), Some(Cirru::Leaf(trait_name))) = (items.get(1), items.get(2)) else {
return Err("A core defimpl must name its receiver and trait before it can be moved.".to_owned());
};
let source_file = &before.files[source_ns];
let target_file = &staged.files[target_ns];
let source_imports = calcit_core::program::extract_import_map(&source_file.ns.code, source_ns)?;
let target_imports = calcit_core::program::extract_import_map(&target_file.ns.code, target_ns)?;
let resolve =
|file: &FileInSnapShot, imports: &_, namespace: &str, symbol: &str| resolve_defimpl_symbol(file, imports, namespace, symbol);
let receiver_key = resolve(source_file, &source_imports, source_ns, receiver);
let trait_key = resolve(source_file, &source_imports, source_ns, trait_name);
if source_ns != target_ns && target_ns != receiver_key.0 && target_ns != trait_key.0 {
return Err(format!(
"Cannot move this defimpl to '{target_ns}': its receiver and trait are declared in '{}' and '{}'.",
receiver_key.0, trait_key.0
));
}
if !is_core_defimpl(snapshot_file, staged, target_ns, head)? {
return Err(format!(
"Cannot change the definition key: '{head}' would no longer resolve to the core defimpl in '{target_ns}'."
));
}
for node in items.iter().skip(1) {
let expression = calcit_core::data::cirru::code_to_calcit(node, source_ns, "", vec![])?;
check_defimpl_references(&expression, &|sym| {
if resolve(source_file, &source_imports, source_ns, sym) != resolve(target_file, &target_imports, target_ns, sym) {
return Err(format!(
"Cannot move or rename this defimpl in '{target_ns}': symbol '{sym}' would resolve differently. Qualify the reference before editing."
));
}
Ok(())
})?;
}
Ok(())
}
fn check_defimpl_references(expression: &calcit_core::Calcit, check: &impl Fn(&str) -> Result<(), String>) -> Result<(), String> {
match expression {
calcit_core::Calcit::Symbol { sym, .. } => check(sym),
calcit_core::Calcit::List(items) => items.traverse_result(&mut |item| check_defimpl_references(item, check)),
_ => Ok(()),
}
}
fn resolve_defimpl_symbol(
file: &FileInSnapShot,
imports: &std::collections::HashMap<Arc<str>, Arc<calcit_core::program::ImportRule>>,
namespace: &str,
symbol: &str,
) -> (String, String) {
use calcit_core::program::ImportRule;
if let Some((prefix, name)) = symbol.split_once('/') {
let owner = match imports.get(prefix).map(AsRef::as_ref) {
Some(ImportRule::NsAs(target)) => target.as_ref(),
_ => prefix,
};
return (owner.to_owned(), name.to_owned());
}
if file.defs.contains_key(symbol) {
return (namespace.to_owned(), symbol.to_owned());
}
match imports.get(symbol).map(AsRef::as_ref) {
Some(ImportRule::NsReferDef(owner, name)) => (owner.to_string(), name.to_string()),
Some(ImportRule::NsDefault(module)) => (module.to_string(), "default".to_owned()),
_ => (calcit_core::calcit::CORE_NS.to_owned(), symbol.to_owned()),
}
}
fn defimpl_edit_baseline(snapshot_file: &str, snapshot: &Snapshot, namespace: &str, code: &Cirru) -> Result<Option<Snapshot>, String> {
if let Cirru::List(items) = code
&& let Some(Cirru::Leaf(head)) = items.first()
&& is_core_defimpl(snapshot_file, snapshot, namespace, head)?
{
return Ok(Some(snapshot.clone()));
}
Ok(None)
}
fn handle_mv_def(opts: &EditMvDefCommand, snapshot_file: &str) -> Result<(), String> {
let (source_ns, source_def) = parse_target(&opts.source)?;
let (target_ns, target_def) = parse_target(&opts.target)?;
let mut snapshot = load_snapshot(snapshot_file)?;
check_ns_editable(&snapshot, source_ns)?;
check_ns_editable(&snapshot, target_ns)?;
let source_file = snapshot
.files
.get(source_ns)
.ok_or_else(|| format!("Namespace '{source_ns}' not found"))?;
let resolved_source_def =
resolve_definition_lookup(source_ns, source_def, source_file.defs.keys().map(|name| name.as_str()), false)?.resolved;
if source_ns == target_ns && resolved_source_def == target_def {
return Err("Source and target are identical; nothing to move.".to_string());
}
let target_file = snapshot
.files
.get(target_ns)
.ok_or_else(|| format!("Namespace '{target_ns}' not found"))?;
if target_file.defs.contains_key(target_def) {
return Err(format!("Definition '{target_def}' already exists in namespace '{target_ns}'"));
}
let code = &source_file.defs[resolved_source_def.as_str()].code;
let before = defimpl_edit_baseline(snapshot_file, &snapshot, source_ns, code)?;
let (renamed_code, _) = rename_definition_declaration(snapshot_file, &snapshot, source_ns, code, &resolved_source_def, target_def)?;
let mut entry = snapshot
.files
.get_mut(source_ns)
.expect("resolved namespace exists")
.defs
.remove(resolved_source_def.as_str())
.expect("resolved definition exists");
entry.code = renamed_code;
snapshot
.files
.get_mut(target_ns)
.expect("resolved namespace exists")
.defs
.insert(target_def.to_string(), entry);
if let Some(before) = before {
check_defimpl_destination(
snapshot_file,
&before,
&snapshot,
source_ns,
target_ns,
&snapshot.files[target_ns].defs[target_def].code,
)?;
}
save_snapshot(&snapshot, snapshot_file)?;
println!(
"{} Moved definition '{}' from '{}' to '{}'",
"✓".green(),
resolved_source_def.cyan(),
source_ns.cyan(),
format!("{target_ns}/{target_def}").cyan()
);
Ok(())
}
#[derive(Serialize)]
struct MetaReport {
schema_version: u32,
command: &'static str,
target: String,
dry_run: bool,
revision: String,
original_revision: String,
new_revision: String,
doc: String,
tags: Vec<String>,
examples_count: usize,
tests_count: usize,
#[serde(skip_serializing_if = "Vec::is_empty")]
removed_tests: Vec<String>,
}
fn sorted_tag_strings(tags: &HashSet<EdnTag>) -> Vec<String> {
let mut items: Vec<String> = tags.iter().map(|tag| format!(":{}", tag.ref_str())).collect();
items.sort();
items
}
fn handle_meta(opts: &EditMetaCommand, snapshot_file: &str) -> Result<(), String> {
let output_format = StructuredOutputFormat::parse(&opts.format, "edit meta")?;
let _structured_guard = super::common::StructuredMutationOutputGuard::new(output_format != StructuredOutputFormat::Human);
let has_doc = opts.doc.is_some();
let has_tags_replace = opts.tags.is_some();
let has_tags_delta = !opts.add_tags.is_empty() || !opts.rm_tags.is_empty();
let has_tags_clear = opts.clear_tags;
if (has_tags_replace as u8 + has_tags_delta as u8 + has_tags_clear as u8) > 1 {
return Err("Tag flags conflict: use either --tags, --clear-tags, or --add-tag/--rm-tag".to_owned());
}
let has_examples_replace = opts.examples;
let has_examples_add = opts.add_example;
let has_examples_clear = opts.clear_examples;
if (has_examples_replace as u8 + has_examples_add as u8 + has_examples_clear as u8) > 1 {
return Err("Example flags conflict: use at most one of --examples, --add-example, or --clear-examples".to_owned());
}
if opts.at.is_some() && !has_examples_add {
return Err("`--at` can only be used with `--add-example`".to_owned());
}
if (opts.file.is_some() || opts.code.is_some()) && !has_examples_replace && !has_examples_add {
return Err("`--file` and `--code` require `--examples` or `--add-example`".to_owned());
}
let has_rm_test = !opts.rm_tests.is_empty();
if !has_doc
&& !has_tags_replace
&& !has_tags_delta
&& !has_tags_clear
&& !has_examples_replace
&& !has_examples_add
&& !has_examples_clear
&& !has_rm_test
{
return Err(
"No metadata changes requested. Pass --doc, --tags/--add-tag/--rm-tag/--clear-tags, --examples/--add-example/--clear-examples, or --rm-test."
.to_owned(),
);
}
let (namespace, definition) = parse_target(&opts.target)?;
let original_content =
fs::read_to_string(snapshot_file).map_err(|error| format!("Failed to read snapshot '{snapshot_file}': {error}"))?;
let before_revision = snapshot_content_revision(&original_content);
let mut snapshot = load_snapshot(snapshot_file)?;
let mut guarded_units: Option<BTreeSet<String>> = None;
if let Some(expected) = opts.expect_revision.as_deref() {
if super::snapshot_scope::is_scoped_revision(expected) {
let units = super::snapshot_scope::snapshot_units(&snapshot)?;
guarded_units = Some(super::snapshot_scope::check_scoped_revision(expected, &units)?);
} else if expected != before_revision {
return Err(format!(
"Snapshot revision mismatch: expected '{expected}', current revision is '{before_revision}'. Re-run `query` and retry `edit meta`."
));
}
}
let code_input = if has_examples_replace || has_examples_add {
read_code_input(&opts.file, &opts.code)?
} else {
None
};
let (resolved_definition, code_entry) = get_code_entry_mut(&mut snapshot, namespace, definition)?;
let target_name = format!("{namespace}/{resolved_definition}");
if let Some(guarded) = &guarded_units {
let target_unit = format!("def:{target_name}");
if !guarded.contains(&target_unit) {
return Err(format!(
"Definition conflict: `edit meta` targets {target_unit}, which the scoped revision does not cover. Re-run the dry-run and review the new plan."
));
}
}
if let Some(doc) = &opts.doc {
code_entry.doc.clone_from(doc);
}
if has_tags_clear {
code_entry.tags.clear();
} else if let Some(raw_tags) = &opts.tags {
code_entry.tags = parse_tags_csv(raw_tags)?;
} else if has_tags_delta {
for raw in &opts.add_tags {
for tag in parse_tags_csv(raw)? {
code_entry.tags.insert(tag);
}
}
for raw in &opts.rm_tags {
for tag in parse_tags_csv(raw)? {
code_entry.tags.remove(&tag);
}
}
}
if has_examples_clear {
code_entry.examples.clear();
} else if has_examples_replace {
let raw = code_input
.as_deref()
.ok_or("Examples input required: use --file, --code, or pipe input via stdin")?;
code_entry.examples = parse_examples_input(raw)?;
} else if has_examples_add {
let raw = code_input
.as_deref()
.ok_or("Example input required: use --file, --code, or pipe via stdin")?;
let example = decode_mutation_syntax_input(raw, opts.input_format)?;
let position = opts.at.unwrap_or(code_entry.examples.len());
if position > code_entry.examples.len() {
return Err(format!("Position {} out of range (max: {})", position, code_entry.examples.len()));
}
code_entry.examples.insert(position, example);
}
let mut removed_tests = Vec::new();
for test_name in &opts.rm_tests {
let Some(index) = code_entry.tests.iter().position(|test| test.name == *test_name) else {
let mut available = code_entry.tests.iter().map(|test| test.name.as_str()).collect::<Vec<_>>();
available.sort_unstable();
return Err(format!(
"Test `{test_name}` not found on `{target_name}`{}",
if available.is_empty() {
String::new()
} else {
format!("; available tests: {}", available.join(", "))
}
));
};
code_entry.tests.remove(index);
removed_tests.push(test_name.clone());
}
let doc_snapshot = code_entry.doc.clone();
let tags_snapshot = sorted_tag_strings(&code_entry.tags);
let examples_count = code_entry.examples.len();
let tests_count = code_entry.tests.len();
let new_revision = if opts.dry_run {
before_revision.clone()
} else {
save_snapshot(&snapshot, snapshot_file)?;
let updated_content =
fs::read_to_string(snapshot_file).map_err(|error| format!("Failed to read snapshot '{snapshot_file}': {error}"))?;
snapshot_content_revision(&updated_content)
};
if let Some(doc) = &opts.doc
&& doc.starts_with('|')
{
eprintln!(
"{} Documentation is stored verbatim, so the leading `|` is kept as text; pass the plain text without the Cirru string prefix.",
"⚠".yellow()
);
}
let report = MetaReport {
schema_version: 1,
command: "edit.meta",
target: target_name,
dry_run: opts.dry_run,
revision: before_revision.clone(),
original_revision: before_revision,
new_revision,
doc: doc_snapshot,
tags: tags_snapshot.clone(),
examples_count,
tests_count,
removed_tests,
};
match output_format {
StructuredOutputFormat::Json => {
println!(
"{}",
serde_json::to_string(&report).map_err(|error| format!("Failed to serialize edit meta result: {error}"))?
);
}
StructuredOutputFormat::Edn => {
let value = serde_json::to_value(&report).map_err(|error| format!("Failed to encode edit meta result: {error}"))?;
println!("{}", format_json_value_as_edn(&value)?);
}
StructuredOutputFormat::Human => {
let tags_display = if tags_snapshot.is_empty() {
"none".to_owned()
} else {
tags_snapshot.join(",")
};
if opts.dry_run {
println!(
"{} [dry-run] Would update metadata for '{}' in namespace '{}' (tags: {}, examples: {}, tests: {})",
"✓".green(),
resolved_definition.cyan(),
namespace,
tags_display,
examples_count,
tests_count
);
} else {
println!(
"{} Updated metadata for '{}' in namespace '{}' (tags: {}, examples: {}, tests: {})",
"✓".green(),
resolved_definition.cyan(),
namespace,
tags_display,
examples_count,
tests_count
);
}
}
}
Ok(())
}
fn parse_schema_input(raw: &str, input_format: SyntaxInputFormat) -> Result<Cirru, String> {
decode_mutation_syntax_input(raw, input_format)
.map_err(|error| format!("Failed to parse schema code input: {error}\nSchema examples: `quote String` or `quote $ Ref Bool`."))
}
fn strip_name_field_from_schema(schema: Cirru) -> Cirru {
match schema {
Cirru::List(items) => {
if items.is_empty() {
return Cirru::List(items);
}
if let Some(Cirru::Leaf(head)) = items.first() {
if &**head == ":optional" && items.len() == 2 {
return Cirru::List(vec![items[0].clone(), strip_name_field_from_schema(items[1].clone())]);
}
if &**head == "::" && items.len() == 3 && matches!(items.get(1), Some(Cirru::Leaf(tag)) if &**tag == ":optional") {
return Cirru::List(vec![
items[0].clone(),
items[1].clone(),
strip_name_field_from_schema(items[2].clone()),
]);
}
if &**head == "{}" {
let mut next_items = vec![items[0].clone()];
for pair in items.iter().skip(1) {
if let Cirru::List(xs) = pair
&& xs.len() == 2
&& matches!(xs.first(), Some(Cirru::Leaf(key)) if &**key == ":name")
{
continue;
}
next_items.push(pair.clone());
}
return Cirru::List(next_items);
}
if &**head == "&{}" {
let mut next_items = vec![items[0].clone()];
let mut idx = 1usize;
while idx < items.len() {
if idx + 1 < items.len() && matches!(&items[idx], Cirru::Leaf(key) if &**key == ":name") {
idx += 2;
continue;
}
next_items.push(items[idx].clone());
idx += 1;
}
return Cirru::List(next_items);
}
}
Cirru::List(items)
}
other => other,
}
}
fn handle_ffi(opts: &EditFfiCommand, snapshot_file: &str) -> Result<(), String> {
let (namespace, definition) = parse_target(&opts.target)?;
let snapshot = load_snapshot(snapshot_file)?;
check_ns_editable(&snapshot, namespace)?;
let file_data = snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
let resolved_definition =
resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), false)?.resolved;
let ffi = if opts.clear {
None
} else {
let raw = read_code_input(&opts.file, &opts.code)?.ok_or(ERR_CODE_INPUT_REQUIRED)?;
let value = cirru_edn::parse(&raw).map_err(|error| format!("FFI metadata must be valid Cirru EDN: {error}"))?;
if !matches!(value, Edn::Map(_) | Edn::Struct(_)) {
return Err("FFI metadata must be an EDN map (for example `{}` with :backend/:kind entries)".to_owned());
}
Some(value)
};
save_ffi_preserving_snapshot(snapshot_file, namespace, &resolved_definition, ffi)?;
if opts.clear {
println!(
"{} Cleared FFI metadata for '{}' in namespace '{}'",
"✓".green(),
resolved_definition.cyan(),
namespace
);
} else {
println!(
"{} Updated FFI metadata for '{}' in namespace '{}'",
"✓".green(),
resolved_definition.cyan(),
namespace
);
}
Ok(())
}
fn reject_unresolved_bare_value_schema(
snapshot: &snapshot::Snapshot,
namespace: &str,
schema: &CalcitTypeAnnotation,
) -> Result<(), String> {
let CalcitTypeAnnotation::TypeRef(name, args) = schema else {
return Ok(());
};
let bare = name.trim_start_matches('\'');
if !args.is_empty() || bare.contains('/') {
return Ok(());
}
let Some(file) = snapshot.files.get(namespace) else {
return Ok(());
};
if file.defs.contains_key(bare) {
return Ok(());
}
let referred = calcit_core::program::extract_import_map(&file.ns.code, namespace)
.ok()
.and_then(|imports| imports.get(bare).cloned())
.is_some_and(|rule| matches!(rule.as_ref(), calcit_core::program::ImportRule::NsReferDef(..)));
let in_core = calcit_core::load_core_snapshot()
.ok()
.and_then(|core| {
core
.files
.get(calcit_core::calcit::CORE_NS)
.map(|file| file.defs.contains_key(bare))
})
.unwrap_or(false);
if referred || in_core {
return Ok(());
}
Err(format!(
"Schema validation failed: `{bare}` is not defined in `{namespace}` and not brought in with `:refer`; define it, add `(target.ns :refer $ {bare})` to the ns form, or write `alias/{bare}` / `target.ns/{bare}`"
))
}
fn handle_schema(opts: &EditSchemaCommand, snapshot_file: &str) -> Result<(), String> {
let (namespace, definition) = parse_target(&opts.target)?;
let snapshot = load_snapshot_for_metadata(snapshot_file)?;
check_ns_editable(&snapshot, namespace)?;
let file_data = snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
let resolved_definition =
resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), false)?.resolved;
if let Some(feature) = &opts.add_feature {
if opts.clear || opts.file.is_some() || opts.code.is_some() {
return Err("`edit schema --add-feature` cannot be combined with --clear, --file, or --code".to_owned());
}
if !matches!(feature.as_str(), "js-ffi" | "erased-cache" | "state" | "io") {
return Err(format!(
"Unsupported schema feature `{feature}`; --add-feature supports `js-ffi`, `erased-cache`, `state` and `io`"
));
}
let existing = &file_data.defs[&resolved_definition].schema;
let CalcitTypeAnnotation::Fn(signature) = existing.as_ref() else {
return Err(format!(
"`{namespace}/{resolved_definition}` needs a structured Fn schema before `--add-feature {feature}`; declare its arguments and return type with `calcit edit schema`, then add the feature. `calcit edit ffi` changes export metadata, not lexical feature permission."
));
};
if signature.features.iter().any(|item| item.ref_str() == feature) {
println!(
"{} Schema feature :{feature} is already present for '{namespace}/{resolved_definition}'",
"✓".green()
);
return Ok(());
}
let mut updated = signature.as_ref().clone();
let mut features = updated.features.as_ref().clone();
features.insert(EdnTag::new(feature.as_str()));
updated.features = Arc::new(features);
save_schema_preserving_snapshot(
snapshot_file,
namespace,
&resolved_definition,
Some(&CalcitTypeAnnotation::Fn(Arc::new(updated))),
)?;
println!(
"{} Added schema feature :{feature} to '{namespace}/{resolved_definition}'",
"✓".green()
);
return Ok(());
}
let schema = if opts.clear {
DYNAMIC_TYPE.clone()
} else {
let raw = read_code_input(&opts.file, &opts.code)?.ok_or(ERR_CODE_INPUT_REQUIRED)?;
let schema_payload = strip_name_field_from_schema(parse_schema_input(&raw, opts.input_format)?);
if let Err(note) = snapshot::reject_legacy_schema_input(&schema_payload) {
eprintln!(
"⚠️ {}",
note.replace(snapshot::LEGACY_TYPE_SYNTAX_CODE, snapshot::LEGACY_TYPE_SYNTAX_WARNING)
);
}
let schema = snapshot::parse_schema_annotation_for_write(&schema_payload).map_err(|e| format!("Schema validation failed: {e}"))?;
reject_unresolved_bare_value_schema(&snapshot, namespace, &schema)?;
if !calcit_core::calcit::is_bundled_core_ns(namespace) && snapshot::schema_uses_intrinsic_reason(&schema) {
let hit = snapshot::OpenWithoutReasonHit {
ns: namespace.to_owned(),
def: resolved_definition,
families: vec![],
reserved_intrinsic: true,
};
return Err(format!(
"Schema validation failed ({}): {}",
snapshot::OPEN_WITHOUT_REASON_ERROR,
hit.message()
));
}
schema
};
save_schema_preserving_snapshot(
snapshot_file,
namespace,
&resolved_definition,
(!opts.clear).then_some(schema.as_ref()),
)?;
if opts.clear {
println!(
"{} Cleared schema for '{}' in namespace '{}'",
"✓".green(),
resolved_definition.cyan(),
namespace
);
return Ok(());
}
println!(
"{} Updated schema for '{}' in namespace '{}'",
"✓".green(),
resolved_definition.cyan(),
namespace
);
Ok(())
}
pub(crate) fn find_edn_map_value_mut<'a>(map: &'a mut EdnMapView, expected: &str) -> Option<&'a mut Edn> {
map
.0
.iter_mut()
.find_map(|(key, value)| edn_key_matches(key, expected).then_some(value))
}
fn find_edn_struct_value_mut<'a>(struct_value: &'a mut EdnStructView, expected: &str) -> Option<&'a mut Edn> {
struct_value
.pairs
.iter_mut()
.find_map(|(key, value)| (key.ref_str() == expected).then_some(value))
}
fn snapshot_file_form<'a>(root: &'a mut Edn, namespace: &str) -> Option<&'a mut Edn> {
let Edn::Map(root) = root else { return None };
let Edn::Map(files) = find_edn_map_value_mut(root, "files")? else {
return None;
};
find_edn_map_value_mut(files, namespace)
}
fn snapshot_schema_form(root: &mut Edn, namespace: &str, definition: &str) -> Option<Option<Edn>> {
let Edn::Struct(file) = snapshot_file_form(root, namespace)? else {
return None;
};
let Edn::Map(defs) = find_edn_struct_value_mut(file, "defs")? else {
return None;
};
let Edn::Struct(entry) = find_edn_map_value_mut(defs, definition)? else {
return None;
};
Some(find_edn_struct_value_mut(entry, "schema").cloned())
}
fn replace_snapshot_schema_form(root: &mut Edn, namespace: &str, definition: &str, schema: Option<Edn>) -> Result<(), String> {
let Edn::Map(root) = root else {
return Err("Staged Snapshot root must be an EDN map".to_owned());
};
let Edn::Map(files) = find_edn_map_value_mut(root, "files").ok_or("Staged Snapshot is missing :files")? else {
return Err("Staged Snapshot :files must be an EDN map".to_owned());
};
let Edn::Struct(file) =
find_edn_map_value_mut(files, namespace).ok_or_else(|| format!("Staged namespace '{namespace}' not found"))?
else {
return Err(format!("Staged namespace '{namespace}' must be a FileEntry struct"));
};
let Edn::Map(defs) =
find_edn_struct_value_mut(file, "defs").ok_or_else(|| format!("Staged namespace '{namespace}' is missing :defs"))?
else {
return Err(format!("Staged namespace '{namespace}' :defs must be an EDN map"));
};
let Edn::Struct(entry) =
find_edn_map_value_mut(defs, definition).ok_or_else(|| format!("Staged definition '{namespace}/{definition}' not found"))?
else {
return Err(format!("Staged definition '{namespace}/{definition}' must be a CodeEntry struct"));
};
if let Some(schema) = schema {
if let Some(value) = find_edn_struct_value_mut(entry, "schema") {
*value = schema;
} else {
entry.pairs.push((EdnTag::new("schema"), schema));
}
} else {
entry.pairs.retain(|(key, _)| key.ref_str() != "schema");
}
Ok(())
}
fn restore_untouched_schema_forms(
original_content: &str,
rendered_content: &str,
staged_snapshot: &Snapshot,
staged_path: &str,
operations: &[Vec<String>],
) -> Result<String, String> {
let mut original_source = original_content.to_owned();
strip_shebang(&mut original_source);
let mut original_edn =
cirru_edn::parse(&original_source).map_err(|error| format!("Failed to parse original Snapshot EDN: {error}"))?;
let original_snapshot = snapshot::load_snapshot_data_for_metadata(&original_edn, "staged original", None)
.map_err(|error| format!("Failed to load original Snapshot for schema preservation: {error}"))?;
let mut rendered_source = rendered_content.to_owned();
let shebang = original_content
.lines()
.next()
.filter(|line| line.starts_with("#!"))
.map(str::to_owned);
strip_shebang(&mut rendered_source);
let mut rendered_edn = cirru_edn::parse(&rendered_source).map_err(|error| format!("Failed to parse staged Snapshot EDN: {error}"))?;
if let Edn::Map(root) = &mut rendered_edn {
root.0.retain(|key, _| !edn_key_matches(key, "about"));
if let Some(about) = &staged_snapshot.about {
root.insert_key("about", Edn::Str(about.as_str().into()));
}
}
for (namespace, file) in &original_snapshot.files {
let Some(staged_file) = staged_snapshot.files.get(namespace) else {
continue;
};
if file.ns != staged_file.ns {
continue;
}
if file == staged_file
&& !operations.iter().any(|operation| {
operation.first().is_some_and(|group| group == "edit")
&& operation.get(1).is_some_and(|name| name == "schema")
&& operation
.get(2)
.is_some_and(|target| target.split_once('/').is_some_and(|(ns, _)| ns == namespace))
})
{
if let (Edn::Map(original_root), Edn::Map(rendered_root)) = (&mut original_edn, &mut rendered_edn)
&& let Some(Edn::Map(original_files)) = find_edn_map_value_mut(original_root, "files")
&& let Some(Edn::Map(rendered_files)) = find_edn_map_value_mut(rendered_root, "files")
&& let Some((key, value)) = original_files.0.iter().find(|(key, _)| edn_key_matches(key, namespace))
{
rendered_files.0.retain(|key, _| !edn_key_matches(key, namespace));
rendered_files.insert(key.clone(), value.clone());
}
continue;
}
for (definition, entry) in &file.defs {
let Some(staged_entry) = staged_file.defs.get(definition) else {
continue;
};
if entry.schema != staged_entry.schema
|| operations.iter().any(|operation| {
operation.first().is_some_and(|group| group == "edit")
&& operation.get(1).is_some_and(|name| name == "schema")
&& operation
.get(2)
.is_some_and(|target| target == &format!("{namespace}/{definition}"))
})
{
continue;
}
if let Some(original_schema) = snapshot_schema_form(&mut original_edn, namespace, definition) {
replace_snapshot_schema_form(&mut rendered_edn, namespace, definition, original_schema)?;
}
}
}
let restored_snapshot = snapshot::load_snapshot_data(&rendered_edn, staged_path)
.map_err(|error| format!("Failed to reload schema-preserving staged Snapshot: {error}"))?;
if &restored_snapshot != staged_snapshot {
return Err("Restoring unselected schema forms changed the staged Snapshot semantics; no changes were written.".to_owned());
}
let formatted = cirru_edn::format(&rendered_edn, true).map_err(|error| format!("Failed to format staged Snapshot EDN: {error}"))?;
Ok(match shebang {
Some(line) => format!("{line}\n{formatted}"),
None => formatted,
})
}
fn save_schema_preserving_snapshot(
snapshot_file: &str,
namespace: &str,
definition: &str,
schema: Option<&calcit_core::calcit::CalcitTypeAnnotation>,
) -> Result<(), String> {
let original = fs::read_to_string(snapshot_file).map_err(|e| format!("Failed to read {snapshot_file}: {e}"))?;
let shebang = original.lines().next().filter(|line| line.starts_with("#!")).map(str::to_owned);
let mut content = original;
strip_shebang(&mut content);
let mut data = cirru_edn::parse(&content).map_err(|e| format!("Failed to parse EDN: {e}"))?;
let Edn::Map(root) = &mut data else {
return Err("Snapshot root must be an EDN map".to_owned());
};
let files_value = find_edn_map_value_mut(root, "files").ok_or_else(|| "Snapshot is missing :files".to_owned())?;
let Edn::Map(files) = files_value else {
return Err("Snapshot :files must be an EDN map".to_owned());
};
let file_value = find_edn_map_value_mut(files, namespace).ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
let Edn::Struct(file) = file_value else {
return Err(format!("Namespace '{namespace}' must be a FileEntry struct"));
};
let defs_value = find_edn_struct_value_mut(file, "defs").ok_or_else(|| format!("Namespace '{namespace}' is missing :defs"))?;
let Edn::Map(defs) = defs_value else {
return Err(format!("Namespace '{namespace}' :defs must be an EDN map"));
};
let definition_value =
find_edn_map_value_mut(&mut *defs, definition).ok_or_else(|| format!("Definition '{namespace}/{definition}' not found"))?;
let Edn::Struct(entry) = definition_value else {
return Err(format!("Definition '{namespace}/{definition}' must be a CodeEntry struct"));
};
if let Some(schema) = schema {
let schema_edn = snapshot::schema_annotation_to_storage_edn(schema);
if let Some(value) = find_edn_struct_value_mut(entry, "schema") {
*value = schema_edn;
} else {
entry.pairs.push((EdnTag::new("schema"), schema_edn));
}
} else {
entry.pairs.retain(|(key, _)| key.ref_str() != "schema");
}
let checked = snapshot::load_snapshot_data_for_metadata(&data, snapshot_file, Some((namespace, definition))).map_err(|e| {
format!("Schema validation failed: `{namespace}/{definition}` would make the snapshot unloadable, nothing was written: {e}")
})?;
validate_selected_js_ffi(&checked, snapshot_file, namespace, definition)?;
let formatted = cirru_edn::format(&data, true).map_err(|e| format!("Failed to format snapshot EDN: {e}"))?;
let output = match shebang {
Some(line) => format!("{line}\n{formatted}"),
None => formatted,
};
calcit_core::util::atomic_write::write_snapshot(snapshot_file, output.as_bytes())
}
fn save_ffi_preserving_snapshot(snapshot_file: &str, namespace: &str, definition: &str, ffi: Option<Edn>) -> Result<(), String> {
let original = fs::read_to_string(snapshot_file).map_err(|e| format!("Failed to read {snapshot_file}: {e}"))?;
let shebang = original.lines().next().filter(|line| line.starts_with("#!")).map(str::to_owned);
let mut content = original;
strip_shebang(&mut content);
let mut data = cirru_edn::parse(&content).map_err(|e| format!("Failed to parse EDN: {e}"))?;
let Edn::Map(root) = &mut data else {
return Err("Snapshot root must be an EDN map".to_owned());
};
let files_value = find_edn_map_value_mut(root, "files").ok_or_else(|| "Snapshot is missing :files".to_owned())?;
let Edn::Map(files) = files_value else {
return Err("Snapshot :files must be an EDN map".to_owned());
};
let file_value = find_edn_map_value_mut(files, namespace).ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
let Edn::Struct(file) = file_value else {
return Err(format!("Namespace '{namespace}' must be a FileEntry struct"));
};
let defs_value = find_edn_struct_value_mut(file, "defs").ok_or_else(|| format!("Namespace '{namespace}' is missing :defs"))?;
let Edn::Map(defs) = defs_value else {
return Err(format!("Namespace '{namespace}' :defs must be an EDN map"));
};
let definition_value =
find_edn_map_value_mut(&mut *defs, definition).ok_or_else(|| format!("Definition '{namespace}/{definition}' not found"))?;
let Edn::Struct(entry) = definition_value else {
return Err(format!("Definition '{namespace}/{definition}' must be a CodeEntry struct"));
};
if let Some(value) = ffi {
if let Some(existing) = find_edn_struct_value_mut(entry, "ffi") {
*existing = value;
} else {
entry.pairs.push((EdnTag::new("ffi"), value));
}
} else {
entry.pairs.retain(|(key, _)| key.ref_str() != "ffi");
}
let checked = snapshot::load_snapshot_data_for_metadata(&data, snapshot_file, Some((namespace, definition)))?;
validate_selected_js_ffi(&checked, snapshot_file, namespace, definition)?;
let formatted = cirru_edn::format(&data, true).map_err(|e| format!("Failed to format snapshot EDN: {e}"))?;
let output = match shebang {
Some(line) => format!("{line}\n{formatted}"),
None => formatted,
};
calcit_core::util::atomic_write::write_snapshot(snapshot_file, output.as_bytes())
}
fn validate_selected_js_ffi(snapshot: &Snapshot, snapshot_file: &str, namespace: &str, definition: &str) -> Result<(), String> {
let base_dir = Path::new(snapshot_file).parent().unwrap_or_else(|| Path::new("."));
let dependencies = std::cell::OnceCell::new();
let entry = &snapshot.files[namespace].defs[definition];
if entry.ffi.is_none() {
return Ok(());
}
let imports = calcit_core::program::extract_import_map(&snapshot.files[namespace].ns.code, namespace)?;
let load = || {
dependencies.get_or_init(|| {
let folder = calcit_core::project_module_folder(base_dir);
let mut modules = Vec::new();
let mut errors = Vec::new();
for path in snapshot
.entries
.values()
.flat_map(|entry| &entry.modules)
.collect::<std::collections::BTreeSet<_>>()
{
match super::load_module_with_sources_silent(path, base_dir, &folder) {
Ok(module) => modules.push(module),
Err(error) => errors.push(format!("{path}: {error}")),
}
}
(modules, errors)
})
};
let resolve = |ty: &calcit_core::calcit::CalcitTypeAnnotation, target| {
let Some((ns, def)) = calcit_core::js_ffi_source::ffi_host_type_path(ty, namespace, &imports, |ns, def| {
if let Some(file) = snapshot.files.get(ns) {
return file.defs.contains_key(def);
}
load()
.0
.iter()
.any(|module| module.snapshot.files.get(ns).is_some_and(|file| file.defs.contains_key(def)))
}) else {
return false;
};
let is_host = |file: &snapshot::FileInSnapShot| {
file
.defs
.get(def)
.is_some_and(|host| calcit_core::js_ffi_source::is_ffi_host_entry(host, target))
};
if let Some(file) = snapshot.files.get(ns) {
return is_host(file);
}
let loaded = load();
let mut owners = loaded.0.iter().filter_map(|module| module.snapshot.files.get(ns));
owners
.next()
.is_some_and(|first| is_host(first) && owners.all(|other| other == first))
};
calcit_core::js_ffi_source::validate_js_definition_with(&snapshot.files[namespace].defs[definition], &resolve).map_err(|error| {
match dependencies.get() {
Some((_, errors)) if !errors.is_empty() => {
let detail = errors.join("\n");
format!("{namespace}/{definition}: {error}; failed to resolve declared modules: {detail}; no changes were written")
}
_ => format!("{namespace}/{definition}: {error}; no changes were written"),
}
})?;
Ok(())
}
fn parse_examples_input(raw: &str) -> Result<Vec<Cirru>, String> {
parse_quoted_cirru_nodes(raw).map_err(|error| {
format!(
"Failed to parse examples: {error}\nEach top-level example needs its own `quote`, so both leaves and expressions remain representable."
)
})
}
fn parse_tag_token(raw: &str) -> Result<EdnTag, String> {
let trimmed = raw.trim();
if trimmed.is_empty() {
return Err("empty tag".to_string());
}
let name = trimmed.strip_prefix(':').unwrap_or(trimmed);
if name.is_empty() {
return Err(format!("invalid tag: {raw}"));
}
Ok(EdnTag::new(name))
}
fn parse_tags_csv(raw: &str) -> Result<HashSet<EdnTag>, String> {
let trimmed = raw.trim();
if trimmed.is_empty() {
return Ok(HashSet::new());
}
let mut tags = HashSet::new();
for token in trimmed.split(',') {
let piece = token.trim();
if piece.is_empty() {
return Err("tags must be comma-separated without empty items".to_string());
}
tags.insert(parse_tag_token(piece)?);
}
Ok(tags)
}
fn get_code_entry_mut<'a>(
snapshot: &'a mut Snapshot,
namespace: &str,
definition: &str,
) -> Result<(String, &'a mut CodeEntry), String> {
check_ns_editable(snapshot, namespace)?;
let file_data = snapshot
.files
.get_mut(namespace)
.ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
let resolved_definition =
resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), false)?.resolved;
let code_entry = file_data
.defs
.get_mut(resolved_definition.as_str())
.ok_or_else(|| format!("Definition '{resolved_definition}' not found in namespace '{namespace}'"))?;
Ok((resolved_definition, code_entry))
}
fn handle_add_test(opts: &EditAddTestCommand, snapshot_file: &str) -> Result<(), String> {
let (namespace, definition) = parse_target(&opts.target)?;
snapshot::validate_test_names([opts.name.as_str()], "Test")?;
let code_input = read_code_input(&opts.file, &opts.code)?;
let raw = code_input
.as_deref()
.ok_or("Test input required: use --file, --code, or pipe via stdin")?;
let code = decode_mutation_syntax_input(raw, opts.input_format)?;
let tags = parse_tags_csv(opts.tags.as_deref().unwrap_or(""))?;
let mut snapshot = load_snapshot(snapshot_file)?;
let (resolved_definition, entry) = get_code_entry_mut(&mut snapshot, namespace, definition)?;
let new_test = TestEntry {
name: opts.name.clone(),
code,
tags,
};
if let Some(index) = entry.tests.iter().position(|test| test.name == opts.name) {
if !opts.overwrite {
return Err(format!(
"Test `{}` already exists on `{namespace}/{resolved_definition}`; pass --overwrite to replace it explicitly",
opts.name
));
}
entry.tests[index] = new_test;
} else {
entry.tests.push(new_test);
}
save_snapshot(&snapshot, snapshot_file)?;
println!(
"{} Added test '{}' to '{}/{}'",
"✓".green(),
opts.name.cyan(),
namespace,
resolved_definition
);
Ok(())
}
pub(crate) fn apply_operation_at_path(
code: &Cirru,
path: &[usize],
operation: TreeOperation,
new_node: Option<&Cirru>,
) -> Result<Cirru, String> {
if path.is_empty() {
return match operation {
TreeOperation::Replace => {
let node = new_node.ok_or("Code input required for replace operation")?;
Ok(node.clone())
}
TreeOperation::Delete => Err("Cannot delete root node".to_string()),
_ => Err(format!(
"`{}` is not supported at the definition root; use a non-empty --path",
operation.command_form()
)),
};
}
apply_operation_recursive(code, path, 0, operation, new_node)
}
fn apply_operation_recursive(
code: &Cirru,
path: &[usize],
depth: usize,
operation: TreeOperation,
new_node: Option<&Cirru>,
) -> Result<Cirru, String> {
match code {
Cirru::Leaf(_) => Err(format!("Cannot navigate into leaf node at depth {depth}")),
Cirru::List(items) => {
let idx = path[depth];
if idx >= items.len() {
return Err(format!("Path index {} out of bounds (list has {} items)", idx, items.len()));
}
if depth == path.len() - 1 {
let mut new_items = items.clone();
match operation {
TreeOperation::Delete => {
new_items.remove(idx);
}
TreeOperation::Replace => {
let newn = new_node.ok_or("Code input required for replace operation")?;
new_items[idx] = newn.clone();
}
TreeOperation::InsertBefore => {
let newn = new_node.ok_or_else(|| format!("Code input required for `{}`", TreeOperation::InsertBefore.command_form()))?;
new_items.insert(idx, newn.clone());
}
TreeOperation::InsertAfter => {
let newn = new_node.ok_or_else(|| format!("Code input required for `{}`", TreeOperation::InsertAfter.command_form()))?;
new_items.insert(idx + 1, newn.clone());
}
TreeOperation::InsertChild => {
let newn = new_node.ok_or_else(|| format!("Code input required for `{}`", TreeOperation::InsertChild.command_form()))?;
match &new_items[idx] {
Cirru::List(children) => {
let mut new_children = vec![newn.clone()];
new_children.extend(children.clone());
new_items[idx] = Cirru::List(new_children);
}
Cirru::Leaf(_) => {
return Err("Cannot insert child into leaf node".to_string());
}
}
}
TreeOperation::AppendChild => {
let newn = new_node.ok_or_else(|| format!("Code input required for `{}`", TreeOperation::AppendChild.command_form()))?;
match &new_items[idx] {
Cirru::List(children) => {
let mut new_children = children.clone();
new_children.push(newn.clone());
new_items[idx] = Cirru::List(new_children);
}
Cirru::Leaf(_) => {
return Err("Cannot append child to leaf node".to_string());
}
}
}
TreeOperation::SwapNextSibling => {
if idx + 1 >= new_items.len() {
return Err(format!("Cannot swap: no next sibling at index {idx}"));
}
new_items.swap(idx, idx + 1);
}
TreeOperation::SwapPrevSibling => {
if idx == 0 {
return Err("Cannot swap: no previous sibling at index 0".to_string());
}
new_items.swap(idx - 1, idx);
}
}
Ok(Cirru::List(new_items))
} else {
let mut new_items = items.clone();
new_items[idx] = apply_operation_recursive(&items[idx], path, depth + 1, operation, new_node)?;
Ok(Cirru::List(new_items))
}
}
}
}
pub(crate) fn navigate_to_path(code: &Cirru, path: &[usize]) -> Result<Cirru, String> {
if path.is_empty() {
return Ok(code.clone());
}
let mut current = code;
for (depth, &idx) in path.iter().enumerate() {
match current {
Cirru::Leaf(_) => {
let partial = format_path(&path[..depth]);
return Err(format!(
"Cannot navigate into leaf node at depth {depth}\n Valid path stops at: {}\n Tip: Use 'calcit tree show --path {}' to explore the tree structure (use dot-separated indices, e.g. '@2.1.0')",
format_path(&path[..depth]),
partial,
));
}
Cirru::List(items) => {
if idx >= items.len() {
let partial = format_path(&path[..depth]);
return Err(format!(
"Path index {} out of bounds at depth {} (list has {} items)\n Attempted path: {}\n Valid path up to: {}\n Valid index range at this level: 0-{}\n Tip: Use 'calcit tree show --path {}' to see available children",
idx,
depth,
items.len(),
format_path(path),
format_path(&path[..depth]),
items.len().saturating_sub(1),
partial,
));
}
current = &items[idx];
}
}
}
Ok(current.clone())
}
fn handle_add_ns(opts: &EditAddNsCommand, snapshot_file: &str) -> Result<(), String> {
let mut snapshot = load_snapshot(snapshot_file)?;
check_ns_editable(&snapshot, &opts.namespace)?;
if snapshot.files.contains_key(&opts.namespace) {
return Err(format!("Namespace '{}' already exists", opts.namespace));
}
let ns_code = if let Some(raw) = read_code_input(&opts.file, &opts.code)? {
let code = decode_mutation_syntax_input(&raw, opts.input_format)?;
if let Cirru::List(ref items) = code
&& let Some(Cirru::Leaf(kw)) = items.first()
&& kw.as_ref() == "ns"
&& let Some(Cirru::Leaf(ns_in_expr)) = items.get(1)
&& ns_in_expr.as_ref() != opts.namespace.as_str()
{
return Err(format!(
"Namespace name mismatch: positional argument is '{}' but ns expression contains '{}'. They must be identical.",
opts.namespace, ns_in_expr
));
}
code
} else {
Cirru::List(vec![Cirru::Leaf(Arc::from("ns")), Cirru::Leaf(Arc::from(opts.namespace.as_str()))])
};
let file_entry = FileInSnapShot {
ns: NsEntry {
doc: String::new(),
code: ns_code,
},
defs: HashMap::new(),
};
snapshot.files.insert(opts.namespace.clone(), file_entry);
save_snapshot(&snapshot, snapshot_file)?;
println!("{} Created namespace '{}'", "✓".green(), opts.namespace.cyan());
Ok(())
}
fn handle_rm_ns(opts: &EditRmNsCommand, snapshot_file: &str) -> Result<(), String> {
let mut snapshot = load_snapshot(snapshot_file)?;
check_ns_editable(&snapshot, &opts.namespace)?;
if snapshot.files.remove(&opts.namespace).is_none() {
return Err(format!("Namespace '{}' not found", opts.namespace));
}
save_snapshot(&snapshot, snapshot_file)?;
println!("{} Deleted namespace '{}'", "✓".green(), opts.namespace.cyan());
Ok(())
}
fn handle_imports(opts: &EditImportsCommand, snapshot_file: &str) -> Result<(), String> {
let raw = read_code_input(&opts.file, &opts.code)?.ok_or("Imports input required: use --file, --code, or pipe via stdin")?;
let mut snapshot = load_snapshot(snapshot_file)?;
check_ns_editable(&snapshot, &opts.namespace)?;
let file_data = snapshot
.files
.get_mut(&opts.namespace)
.ok_or_else(|| format!("Namespace '{}' not found", opts.namespace))?;
let ns_name = &opts.namespace;
let rules = parse_import_rules_input(&raw, opts.input_format)?;
for warning in validate_import_rules(&rules)? {
eprintln!("{} in namespace '{}': {warning}", "Warning:".yellow(), opts.namespace);
}
let old_imports = extract_require_list(&file_data.ns.code);
file_data.ns.code = build_ns_code(ns_name, &rules);
let new_imports = extract_require_list(&file_data.ns.code);
save_snapshot(&snapshot, snapshot_file)?;
println!("{} Updated imports for namespace '{}'", "✓".green(), opts.namespace.cyan());
let removed: Vec<_> = old_imports.iter().filter(|old| !new_imports.contains(old)).collect();
if !removed.is_empty() {
println!(" {} Removed:", "-".red());
for import in removed {
println!(" {}", import.dimmed());
}
}
let added: Vec<_> = new_imports.iter().filter(|new| !old_imports.contains(new)).collect();
let mut added_namespaces = Vec::new();
if !added.is_empty() {
println!(" {} Added:", "+".green());
for import in &added {
println!(" {import}");
if let Some(first_token) = import.split_whitespace().next() {
let ns = first_token.strip_prefix('(').unwrap_or(first_token);
added_namespaces.push(ns.to_owned());
}
}
}
let unchanged_count = old_imports.iter().filter(|old| new_imports.contains(old)).count();
if unchanged_count > 0 {
println!(" {} {} unchanged", "·".dimmed(), format!("{unchanged_count}").dimmed());
}
if !added.is_empty() {
println!();
println!("{}", "Usage tips for new imports:".dimmed());
for added_str in &added {
if let Ok(parsed) = cirru_parser::parse(added_str)
&& let Some(rule) = parsed.first()
&& let Some(source_ns) = get_require_source_ns(rule)
{
print_import_usage_tips(rule, &source_ns);
}
}
}
Ok(())
}
fn import_rules_from_json(value: &serde_json::Value) -> Result<Vec<Cirru>, String> {
use super::common::json_value_to_cirru;
let serde_json::Value::Array(elems) = value else {
return Err("Imports must be a Cirru EDN list or JSON array of import rules.".to_string());
};
if elems.is_empty() {
return Ok(vec![]);
}
if elems.first().is_some_and(serde_json::Value::is_array) {
return elems.iter().map(json_value_to_cirru).collect::<Result<Vec<_>, _>>();
}
if let Some(serde_json::Value::String(first_str)) = elems.first()
&& first_str == ":require"
{
return Err(
"Do not include ':require' as a prefix in the imports input. \
Pass rules directly, e.g. --code 'src-ns :refer $ sym' or use --file for multiple rules."
.to_string(),
);
}
Ok(vec![json_value_to_cirru(value)?])
}
fn import_rules_from_syntax_node(node: &Cirru, selected_format: SyntaxInputFormat) -> Result<Vec<Cirru>, String> {
let Cirru::List(items) = node else {
return Err(format!(
"Imports input format `{selected_format}` expected an imports vector node headed by `[]`, received a leaf."
));
};
if !matches!(items.first(), Some(Cirru::Leaf(head)) if &**head == "[]") {
return Err(format!(
"Imports input format `{selected_format}` expected an imports vector node headed by `[]`."
));
}
items
.iter()
.skip(1)
.enumerate()
.map(|(index, rule)| {
if !matches!(rule, Cirru::List(_)) {
return Err(format!("Import rule {} inside the `[]` node must be an expression.", index + 1));
}
Ok(rule.clone())
})
.collect()
}
fn parse_import_rules_input(raw: &str, requested_format: SyntaxInputFormat) -> Result<Vec<Cirru>, String> {
let trimmed = raw.trim();
if trimmed.is_empty() {
return Err(
"Imports input is empty. Provide one imports vector node as quoted Cirru or JSON AST; use --input-format to select the transport."
.to_string(),
);
}
if requested_format != SyntaxInputFormat::Auto {
let node = super::common::decode_mutation_syntax_input(trimmed, requested_format)?;
return import_rules_from_syntax_node(&node, requested_format);
}
if trimmed.starts_with('[') {
let value = serde_json::from_str(trimmed).map_err(|error| format!("Failed to parse imports JSON: {error}"))?;
return import_rules_from_json(&value);
}
let cirru_node = parse_input_to_cirru(trimmed)?;
import_rules_from_syntax_node(&cirru_node, SyntaxInputFormat::Cirru)
}
fn extract_require_list(ns_code: &Cirru) -> Vec<String> {
let mut imports = Vec::new();
if let Cirru::List(items) = ns_code {
let mut in_require = false;
for item in items {
if let Cirru::Leaf(s) = item
&& s.as_ref() == ":require"
{
in_require = true;
continue;
}
if in_require {
if let Ok(formatted) = item.format_one_liner() {
imports.push(formatted);
}
}
}
}
imports
}
fn get_require_source_ns(rule: &Cirru) -> Option<String> {
match rule {
Cirru::List(items) => {
let items = match items.first() {
Some(head) if head.eq_leaf("[]") => &items[1..],
_ => items.as_slice(),
};
match items.first() {
Some(Cirru::Leaf(source)) => Some(source.to_string()),
_ => None,
}
}
_ => None,
}
}
pub(crate) fn extract_require_rules(ns_code: &Cirru) -> Vec<Cirru> {
let mut rules = vec![];
if let Cirru::List(items) = ns_code {
for item in items.iter().skip(2) {
if let Cirru::List(inner) = item
&& let Some(Cirru::Leaf(first)) = inner.first()
&& first.as_ref() == ":require"
{
rules.extend(inner.iter().skip(1).cloned());
break;
}
}
}
rules
}
fn build_ns_code(ns_name: &str, rules: &[Cirru]) -> Cirru {
let mut items = vec![Cirru::Leaf(Arc::from("ns")), Cirru::Leaf(Arc::from(ns_name))];
if !rules.is_empty() {
let mut require_list = vec![Cirru::Leaf(Arc::from(":require"))];
require_list.extend(rules.iter().cloned());
items.push(Cirru::List(require_list));
}
Cirru::List(items)
}
fn handle_add_import(opts: &EditAddImportCommand, snapshot_file: &str) -> Result<(), String> {
let raw = read_code_input(&opts.file, &opts.code)?.ok_or("Import rule input required: use --file, --code, or pipe via stdin")?;
let new_rule = decode_mutation_syntax_input(&raw, opts.input_format)?;
let _ = validate_import_rules(std::slice::from_ref(&new_rule))?;
let new_source_ns =
get_require_source_ns(&new_rule).ok_or("Invalid require rule: first element must be a namespace name (e.g. 'calcit.core')")?;
let mut snapshot = load_snapshot(snapshot_file)?;
check_ns_editable(&snapshot, &opts.namespace)?;
let file_data = snapshot
.files
.get_mut(&opts.namespace)
.ok_or_else(|| format!("Namespace '{}' not found", opts.namespace))?;
let mut rules = extract_require_rules(&file_data.ns.code);
let existing_idx = rules
.iter()
.position(|r| get_require_source_ns(r).as_deref() == Some(&new_source_ns));
let replaced = if let Some(idx) = existing_idx {
if opts.overwrite {
rules[idx] = new_rule.clone();
true
} else {
return Err(format!(
"Require rule for '{}' already exists in namespace '{}'. Use --overwrite to replace.",
new_source_ns, opts.namespace
));
}
} else {
rules.push(new_rule.clone());
false
};
for warning in validate_import_rules(&rules)? {
eprintln!("{} in namespace '{}': {warning}", "Warning:".yellow(), opts.namespace);
}
if replaced {
println!(
"{} Replaced require rule for '{}' in namespace '{}'",
"✓".green(),
new_source_ns.cyan(),
opts.namespace
);
} else {
println!(
"{} Added require rule for '{}' in namespace '{}'",
"✓".green(),
new_source_ns.cyan(),
opts.namespace
);
}
file_data.ns.code = build_ns_code(&opts.namespace, &rules);
save_snapshot(&snapshot, snapshot_file)?;
print_import_usage_tips(&new_rule, &new_source_ns);
Ok(())
}
fn handle_rm_import(opts: &EditRmImportCommand, snapshot_file: &str) -> Result<(), String> {
let mut snapshot = load_snapshot(snapshot_file)?;
check_ns_editable(&snapshot, &opts.namespace)?;
let file_data = snapshot
.files
.get_mut(&opts.namespace)
.ok_or_else(|| format!("Namespace '{}' not found", opts.namespace))?;
let mut rules = extract_require_rules(&file_data.ns.code);
let original_len = rules.len();
rules.retain(|r| get_require_source_ns(r).as_deref() != Some(&opts.source_ns));
if rules.len() == original_len {
return Err(format!(
"No require rule found for '{}' in namespace '{}'",
opts.source_ns, opts.namespace
));
}
file_data.ns.code = build_ns_code(&opts.namespace, &rules);
save_snapshot(&snapshot, snapshot_file)?;
println!(
"{} Removed require rule for '{}' from namespace '{}'",
"✓".green(),
opts.source_ns.cyan(),
opts.namespace
);
Ok(())
}
#[cfg(test)]
fn parse_semver_value(v: &str) -> Result<Version, String> {
if v.starts_with('|') {
return Err(format!(
"Invalid version '{v}': do not include the '|' Cirru string prefix; use bare semver, e.g. '0.0.17'"
));
}
Version::parse(v).map_err(|_| format!("Invalid version '{v}': expected semver format, e.g. '0.0.17'"))
}
#[cfg(test)]
fn bump_semver_value(current: &str, level: &str) -> Result<String, String> {
let mut version = parse_semver_value(current)?;
match level {
"patch" => {
version.patch += 1;
}
"minor" => {
version.minor += 1;
version.patch = 0;
}
"major" => {
version.major += 1;
version.minor = 0;
version.patch = 0;
}
_ => {
return Err(format!("Unknown bump level '{level}'. Valid levels: patch, minor, major"));
}
}
version.pre = semver::Prerelease::EMPTY;
version.build = semver::BuildMetadata::EMPTY;
Ok(version.to_string())
}
fn print_import_usage_tips(rule: &Cirru, source_ns: &str) {
if let Cirru::List(items) = rule {
let mut import_type = None;
let mut symbols = Vec::new();
let mut alias = None;
let mut i = 1; while i < items.len() {
if let Cirru::Leaf(tag) = &items[i] {
match tag.as_ref() {
":refer" => {
import_type = Some("refer");
if i + 1 < items.len() {
match &items[i + 1] {
Cirru::List(syms) => {
for sym in syms {
if let Cirru::Leaf(s) = sym {
symbols.push(s.to_string());
}
}
}
Cirru::Leaf(s) => symbols.push(s.to_string()),
}
}
break;
}
":as" => {
import_type = Some("as");
if i + 1 < items.len()
&& let Cirru::Leaf(a) = &items[i + 1]
{
alias = Some(a.to_string());
}
break;
}
":default" => {
import_type = Some("default");
if i + 1 < items.len()
&& let Cirru::Leaf(s) = &items[i + 1]
{
symbols.push(s.to_string());
}
break;
}
_ => {}
}
}
i += 1;
}
println!();
println!("{}", "Usage tips:".dimmed());
match import_type {
Some("refer") => {
if symbols.is_empty() {
println!(
" {} Use imported symbols directly: {}",
"·".dimmed(),
"(symbol-name ...)".to_string().cyan()
);
} else {
println!(" {} Use imported symbols directly:", "·".dimmed());
for symbol in symbols.iter().take(3) {
println!(" {}", format!("({symbol} ...)").cyan());
}
if symbols.len() > 3 {
println!(" {}", format!("... and {} more", symbols.len() - 3).dimmed());
}
}
}
Some("as") => {
if let Some(a) = alias {
println!(" {} Use with alias: {}", "·".dimmed(), format!("({a}/symbol-name ...)").cyan());
println!(
" {} List definitions: {}",
"·".dimmed(),
format!("calcit query defs {source_ns}").cyan()
);
}
}
Some("default") => {
if !symbols.is_empty() {
println!(
" {} Default import available as: {}",
"·".dimmed(),
format!("({} ...)", symbols[0]).cyan()
);
}
}
None => {
println!(
" {} Use with full namespace: {}",
"·".dimmed(),
format!("({source_ns}/symbol-name ...)").cyan()
);
println!(
" {} List definitions: {}",
"·".dimmed(),
format!("calcit query defs {source_ns}").cyan()
);
}
_ => {
println!(
" {} Use with full namespace: {}",
"·".dimmed(),
format!("({source_ns}/symbol-name ...)").cyan()
);
}
}
}
}
#[cfg(test)]
mod tests {
use super::{
TransactionOperationReport, bump_semver_value, collect_format_advisories, handle_add_import, handle_add_test, handle_format,
handle_imports, handle_meta, handle_schema, load_snapshot, parse_examples_input, parse_import_rules_input, parse_input_to_cirru,
parse_schema_input, parse_transaction_operations, rename_definition_declaration, run_staged_fix_transaction,
run_staged_transaction_with, save_schema_preserving_snapshot, save_snapshot, staged_fix_validation_args, staged_warning_difference,
};
use crate::cli_args::{
EditAddImportCommand, EditAddTestCommand, EditFormatCommand, EditImportsCommand, EditMetaCommand, EditSchemaCommand,
SyntaxInputFormat,
};
use crate::cli_handlers::test_support::TestProject;
use calcit_core::calcit::CalcitTypeAnnotation;
use cirru_edn::Edn;
use cirru_parser::Cirru;
use std::ffi::OsString;
use std::fs;
use std::path::Path;
use std::sync::Arc;
type TestSnapshot = TestProject;
#[test]
fn defimpl_uses_a_separate_storage_key() {
let project = TestSnapshot::from_fixture();
let path = project.snapshot_string();
let mut snapshot = load_snapshot(&path).expect("load fixture");
let validate = |snapshot: &calcit_core::snapshot::Snapshot, source: &str| {
let code = parse_input_to_cirru(source).expect("read quoted definition");
super::validate_definition_shape(&path, snapshot, "app.main", "PointLabelImpl", &code, false)
};
validate(&snapshot, "quote $ defimpl model/Point Label (.label label-point)").expect("receiver and storage key can differ");
validate(&snapshot, "quote $ calcit.core/defimpl Point Label (.label label-point)").expect("qualified core macro");
for source in [
"quote $ defimpl Point",
"quote $ defimpl :Point Label",
"quote $ defimpl Point |Label",
] {
let error = validate(&snapshot, source).expect_err("reject malformed implementation");
assert!(error.contains("requires a receiver type symbol and a trait symbol"), "{error}");
}
assert!(
validate(&snapshot, "quote $ defn Point () 1")
.expect_err("ordinary definitions still declare their key")
.contains("Definition name mismatch")
);
let core = calcit_core::load_core_snapshot().expect("load bundled core");
let local_macro = core.files[calcit_core::calcit::CORE_NS].defs["defimpl"].clone();
snapshot
.files
.get_mut("app.main")
.expect("fixture namespace")
.defs
.insert("defimpl".into(), local_macro);
assert!(
validate(&snapshot, "quote $ defimpl Point Label (.label label-point)")
.expect_err("a shadowing macro retains ordinary shape validation")
.contains("Definition name mismatch")
);
let code = parse_input_to_cirru("quote $ defimpl Point Label (.label label-point)").expect("read shadowed macro call");
let error = rename_definition_declaration(&path, &snapshot, "app.main", &code, "PointLabelImpl", "RenamedImpl")
.expect_err("a shadowing macro retains declaration-name validation");
assert!(error.contains("does not match declaration name"), "{error}");
}
fn fake_package_operation(stage_path: &Path, index: usize, args: &[String]) -> Result<TransactionOperationReport, String> {
let package = args.get(2).ok_or_else(|| "fake operation needs package at index 2".to_string())?;
let mut snapshot = load_snapshot(&stage_path.to_string_lossy())?;
snapshot.package = package.to_string();
save_snapshot(&snapshot, &stage_path.to_string_lossy())?;
Ok(TransactionOperationReport {
index,
args: args.to_vec(),
stdout: String::new(),
stderr: String::new(),
})
}
fn leaf(value: &str) -> Cirru {
Cirru::Leaf(value.into())
}
fn list(items: Vec<Cirru>) -> Cirru {
Cirru::List(items)
}
#[test]
fn format_advisories_cover_dynamic_debt() {
let snapshot =
load_snapshot(concat!(env!("CARGO_MANIFEST_DIR"), "/../../calcit/test.cirru")).expect("fixture snapshot should load");
let advisories = collect_format_advisories("calcit.cirru", &snapshot).join("\n");
assert!(!advisories.contains("W_LEGACY_ANY"), "advisories: {advisories}");
assert!(advisories.contains("W_DYNAMIC_TYPE_DEBT"), "advisories: {advisories}");
assert!(advisories.contains("analyze weak-types"), "advisories: {advisories}");
}
#[test]
fn canonical_typed_snapshot_has_no_format_advisories() {
let original_edn = cirru_edn::parse(
"{} (:package |mini) (:version |0.0.1)\n :entries $ {}\n :default $ {} (:description |) (:init-fn 'mini/main!) (:mode :native) (:reload-fn 'mini/reload!)\n :modules $ []\n :type-slots $ {}\n :files $ {}",
)
.expect("canonical fixture should parse");
let snapshot = calcit_core::snapshot::load_snapshot_data(&original_edn, "calcit.cirru").expect("canonical fixture should load");
assert!(collect_format_advisories("calcit.cirru", &snapshot).is_empty());
}
#[test]
fn format_loader_rejects_retired_any_in_schema_but_allows_any_tag_data() {
let retired = cirru_edn::parse(
"{} (:package |mini) (:version |0.0.1)\n :entries $ {}\n :default $ {} (:description |) (:init-fn 'mini/main!) (:mode :native) (:reload-fn 'mini/reload!)\n :modules $ []\n :type-slots $ {}\n :files $ {}\n |mini $ %{} :FileEntry\n :ns $ %{} :CodeEntry (:doc |) (:code $ quote (ns mini)) (:examples $ []) (:schema nil)\n :defs $ {}\n |main! $ %{} :CodeEntry (:doc |) (:code $ quote (def main! 1)) (:examples $ []) (:schema :any)",
)
.expect("fixture should parse");
let err = calcit_core::snapshot::load_snapshot_data_for_format(&retired, "calcit.cirru")
.expect_err("format loader must reject retired :any schema");
assert!(err.contains("E_LEGACY_TYPE_SYNTAX"), "err: {err}");
let data_tag = cirru_edn::parse(
"{} (:package |mini) (:version |0.0.1)\n :entries $ {}\n :default $ {} (:description |) (:init-fn 'mini/main!) (:mode :native) (:reload-fn 'mini/reload!)\n :modules $ []\n :type-slots $ {}\n :files $ {}\n |mini $ %{} :FileEntry\n :ns $ %{} :CodeEntry (:doc |) (:code $ quote (ns mini)) (:examples $ []) (:schema nil)\n :defs $ {}\n |main! $ %{} :CodeEntry (:doc |) (:code $ quote (def main! $ {} (:any :dynamic))) (:examples $ []) (:schema $ quote $ Map Tag Tag)",
)
.expect("data tag fixture should parse");
calcit_core::snapshot::load_snapshot_data_for_format(&data_tag, "calcit.cirru")
.expect("ordinary :any tag in data literal stays valid");
}
#[test]
fn imports_rejects_malformed_rule_without_writing_snapshot() {
let fixture = TestSnapshot::from_fixture();
let original = fs::read(&fixture.path).expect("fixture should read");
let opts = EditImportsCommand {
namespace: "app.main".to_string(),
file: None,
code: Some("quote $ []\n audit.invalid :as".to_string()),
input_format: SyntaxInputFormat::Auto,
};
let error = handle_imports(&opts, &fixture.snapshot_string()).expect_err("malformed import rule should fail");
assert!(error.contains("import rule 1"), "error: {error}");
assert!(error.contains("exactly 3 items"), "error: {error}");
assert_eq!(fs::read(&fixture.path).expect("fixture should remain"), original);
}
#[test]
fn imports_parse_quoted_rule_list_and_keep_json_compatibility() {
let cirru = "quote $ []\n respo.core :refer $ div span\n respo-ui.core :as ui";
let json = r#"[["respo.core",":refer",["div","span"]],["respo-ui.core",":as","ui"]]"#;
let expected = vec![
list(vec![leaf("respo.core"), leaf(":refer"), list(vec![leaf("div"), leaf("span")])]),
list(vec![leaf("respo-ui.core"), leaf(":as"), leaf("ui")]),
];
assert_eq!(
parse_import_rules_input(cirru, SyntaxInputFormat::Auto).expect("quoted Cirru imports should parse"),
expected
);
assert_eq!(
parse_import_rules_input(json, SyntaxInputFormat::Auto).expect("JSON imports should remain supported"),
expected
);
}
#[test]
fn imports_explicit_formats_decode_one_imports_vector_node() {
let cirru = "quote $ []\n respo.core :refer $ div span";
let json_ast = r#"["[]",["respo.core",":refer",["div","span"]]]"#;
let expected = vec![list(vec![
leaf("respo.core"),
leaf(":refer"),
list(vec![leaf("div"), leaf("span")]),
])];
assert_eq!(
parse_import_rules_input(cirru, SyntaxInputFormat::Cirru).expect("explicit Cirru imports should parse"),
expected
);
assert_eq!(
parse_import_rules_input(json_ast, SyntaxInputFormat::JsonAst).expect("explicit JSON AST imports should parse"),
expected
);
}
#[test]
fn imports_explicit_json_ast_rejects_legacy_rule_array_shape() {
let error = parse_import_rules_input(r#"[["respo.core",":refer",["div"]]]"#, SyntaxInputFormat::JsonAst)
.expect_err("explicit JSON AST should require the full imports vector node");
assert!(error.contains("expected an imports vector node headed by `[]`"), "error: {error}");
}
#[test]
fn imports_quoted_list_requires_each_rule_to_be_an_expression() {
let error =
parse_import_rules_input("quote $ [] respo.core", SyntaxInputFormat::Auto).expect_err("flat quoted imports should fail");
assert!(error.contains("rule 1"), "error: {error}");
assert!(error.contains("must be an expression"), "error: {error}");
}
#[test]
fn add_import_rejects_malformed_rule_without_writing_snapshot() {
let fixture = TestSnapshot::from_fixture();
let original = fs::read(&fixture.path).expect("fixture should read");
let opts = EditAddImportCommand {
namespace: "app.main".to_string(),
file: None,
code: Some("quote (audit.invalid :as)".to_string()),
input_format: SyntaxInputFormat::Auto,
overwrite: false,
};
let error = handle_add_import(&opts, &fixture.snapshot_string()).expect_err("malformed import rule should fail");
assert!(error.contains("import rule 1"), "error: {error}");
assert!(error.contains("exactly 3 items"), "error: {error}");
assert_eq!(fs::read(&fixture.path).expect("fixture should remain"), original);
}
#[test]
fn defimpl_move_stays_in_an_owner_namespace() {
let project = TestSnapshot::from_fixture();
let path = project.snapshot_string();
let mut snapshot = load_snapshot(&path).expect("load fixture");
for namespace in ["app.model", "app.traits", "app.other"] {
let mut file = snapshot.files["app.main"].clone();
file.ns.code = list(vec![leaf("ns"), leaf(namespace)]);
file.defs.clear();
snapshot.files.insert(namespace.to_owned(), file);
}
let code = parse_input_to_cirru("quote $ defimpl app.model/Point app.traits/Label").expect("read definition");
for target in ["app.model", "app.traits"] {
super::check_defimpl_destination(&path, &snapshot, &snapshot, "app.main", target, &code).expect("allow an owner namespace");
}
let error = super::check_defimpl_destination(&path, &snapshot, &snapshot, "app.main", "app.other", &code)
.expect_err("implementation discovery cannot find a third namespace");
assert!(error.contains("receiver and trait are declared"), "{error}");
let entry = |code: &Cirru| {
let mut entry = snapshot.files["app.main"].defs.values().next().expect("fixture definition").clone();
entry.code = code.clone();
entry
};
let mut staged = snapshot.clone();
staged
.files
.get_mut("app.model")
.unwrap()
.defs
.insert("defimpl".to_owned(), entry(&code));
let error = super::check_defimpl_destination(&path, &snapshot, &staged, "app.main", "app.model", &code)
.expect_err("inserting the destination key shadows the core macro");
assert!(error.contains("no longer resolve to the core defimpl"), "{error}");
let code = parse_input_to_cirru("quote $ defimpl app.model/Point app.traits/Label (.label helper)").unwrap();
let helper = entry(&parse_input_to_cirru("quote $ defn helper (self) |label").unwrap());
let mut original = snapshot.clone();
original.files.get_mut("app.main").unwrap().defs.insert("helper".to_owned(), helper);
let error = super::check_defimpl_destination(&path, &original, &original, "app.main", "app.model", &code)
.expect_err("unqualified method function would change resolution");
assert!(error.contains("symbol 'helper' would resolve differently"), "{error}");
let qualified = parse_input_to_cirru("quote $ defimpl app.model/Point app.traits/Label (.label app.main/helper)").unwrap();
super::check_defimpl_destination(&path, &original, &original, "app.main", "app.model", &qualified)
.expect("qualified method function keeps its resolution");
let reference = entry(&parse_input_to_cirru("quote $ defref *label |label").unwrap());
for namespace in ["app.main", "app.model"] {
original
.files
.get_mut(namespace)
.unwrap()
.defs
.insert("*label".to_owned(), reference.clone());
}
let deref = parse_input_to_cirru("quote $ defimpl app.model/Point app.traits/Label (.label $ fn (self) , @*label)").unwrap();
let error = super::check_defimpl_destination(&path, &original, &original, "app.main", "app.model", &deref)
.expect_err("a dereferenced symbol would bind to the destination state");
assert!(error.contains("symbol '*label' would resolve differently"), "{error}");
let qualified =
parse_input_to_cirru("quote $ defimpl app.model/Point app.traits/Label (.label $ fn (self) , @app.main/*label)").unwrap();
super::check_defimpl_destination(&path, &original, &original, "app.main", "app.model", &qualified)
.expect("qualified dereference keeps its resolution");
let ns_with_default = |namespace, module| {
list(vec![
leaf("ns"),
leaf(namespace),
list(vec![
leaf(":require"),
list(vec![leaf(module), leaf(":default"), leaf("formatter")]),
]),
])
};
original.files.get_mut("app.main").unwrap().ns.code = ns_with_default("app.main", "|module-a");
original.files.get_mut("app.model").unwrap().ns.code = ns_with_default("app.model", "|module-b");
let default_import =
parse_input_to_cirru("quote $ defimpl app.model/Point app.traits/Label (.label $ fn (self) formatter self)").unwrap();
let error = super::check_defimpl_destination(&path, &original, &original, "app.main", "app.model", &default_import)
.expect_err("a default import from another module changes the binding");
assert!(error.contains("symbol 'formatter' would resolve differently"), "{error}");
original.files.get_mut("app.model").unwrap().ns.code = ns_with_default("app.model", "|module-a");
super::check_defimpl_destination(&path, &original, &original, "app.main", "app.model", &default_import)
.expect("the same module's default export keeps its resolution");
}
fn rename_fixture_declaration(code: &Cirru, old_name: &str, new_name: &str) -> Result<(Cirru, bool), String> {
let project = TestSnapshot::from_fixture();
let path = project.snapshot_string();
let snapshot = load_snapshot(&path).expect("load fixture");
rename_definition_declaration(&path, &snapshot, "app.main", code, old_name, new_name)
}
#[test]
fn rename_preserves_core_defimpl_receiver_and_trait() {
for source in [
"quote $ defimpl model/Point Label (.label label-point)",
"quote $ calcit.core/defimpl model/Point Label (.label label-point)",
] {
let code = parse_input_to_cirru(source).expect("read quoted definition");
let (renamed, changed) = rename_fixture_declaration(&code, "PointLabelImpl", "RenamedImpl").expect("rename storage key");
assert_eq!(renamed, code);
assert!(!changed);
}
}
#[test]
fn rename_updates_definition_declaration_name() {
let code = list(vec![leaf("defref"), leaf("*old"), list(vec![leaf("{}")])]);
let (renamed, changed) = rename_fixture_declaration(&code, "*old", "*next").expect("rename should work");
assert!(changed);
assert_eq!(renamed, list(vec![leaf("defref"), leaf("*next"), list(vec![leaf("{}")])]));
}
#[test]
fn transaction_parses_json_and_cirru_argument_lists() {
let expected = vec![
vec![
"edit".to_string(),
"meta".to_string(),
"app.main/main!".to_string(),
"--doc".to_string(),
"hello".to_string(),
],
vec![
"tree".to_string(),
"delete".to_string(),
"app.main/main!".to_string(),
"--path".to_string(),
"@3".to_string(),
],
];
let json = r#"[["edit","meta","app.main/main!","--doc","hello"],["tree","delete","app.main/main!","--path","@3"]]"#;
let cirru = "[]\n [] |edit |meta |app.main/main! |--doc |hello\n [] |tree |delete |app.main/main! |--path |@3";
assert_eq!(parse_transaction_operations(json).expect("JSON transaction should parse"), expected);
assert_eq!(
parse_transaction_operations(cirru).expect("Cirru transaction should parse"),
expected
);
}
#[test]
fn transaction_cirru_embeds_quoted_code_without_string_escaping() {
let cirru = "[]\n []\n , |tree\n , |replace\n , |app.main/main!\n , |--path\n , |@3.2\n , |--code\n quote $ println |done";
let operations = parse_transaction_operations(cirru).expect("Cirru transaction with quoted code should parse");
let code = operations[0].get(6).expect("formatted --code argument should exist");
assert_eq!(
parse_input_to_cirru(code).expect("embedded quoted code should remain valid edit input"),
list(vec![leaf("println"), leaf("|done")])
);
}
#[test]
fn transaction_cirru_round_trips_quoted_empty_list() {
let cirru = "[]\n []\n , |tree\n , |insert\n , |app.main/main!\n , |--at\n , |after\n , |--path\n , |@1\n , |--code\n quote ()";
let operations = parse_transaction_operations(cirru).expect("Cirru transaction with an empty quoted list should parse");
let code = operations[0].get(8).expect("formatted --code argument should exist");
assert_eq!(
parse_input_to_cirru(code).expect("quoted empty list should remain valid edit input"),
list(vec![])
);
}
#[test]
fn transaction_rejects_unsupported_and_nested_commands() {
let unsupported =
parse_transaction_operations(r#"[["query","def","app.main/main!"]]"#).expect_err("read-only command should be rejected");
assert!(unsupported.contains("Only edit, tree, and config"), "error: {unsupported}");
let nested = parse_transaction_operations(r#"[["edit","transaction","--file","again.cirru"]]"#)
.expect_err("nested transaction should be rejected");
assert!(nested.contains("nested edit transaction"), "error: {nested}");
let unsupported_edit = parse_transaction_operations(r#"[["edit","merge","--source","other.cirru"]]"#)
.expect_err("non-transactional edit should be rejected");
assert!(
unsupported_edit.contains("unsupported staged mutation"),
"error: {unsupported_edit}"
);
let removed_edit = parse_transaction_operations(r#"[["edit","inc","--changed","app.main/main!"]]"#)
.expect_err("removed edit subcommand should be rejected");
assert!(removed_edit.contains("removed in 0.53.0"), "error: {removed_edit}");
let read_only =
parse_transaction_operations(r#"[["tree","show","app.main/main!"]]"#).expect_err("read-only command should be rejected");
assert!(read_only.contains("unsupported staged mutation"), "error: {read_only}");
}
#[test]
fn transaction_rejects_stale_revision_without_running_operations() {
let fixture = TestSnapshot::from_fixture();
let original = fs::read_to_string(&fixture.path).expect("fixture should read");
let operations = vec![vec!["config".to_string(), "package".to_string(), "transaction-test".to_string()]];
let mut called = false;
let error = run_staged_transaction_with(&fixture.path, &operations, Some("md5:stale"), false, |_, _, _| {
called = true;
Err("must not run".to_string())
})
.expect_err("stale transaction should fail");
assert!(!called);
assert!(error.contains("revision mismatch"), "error: {error}");
assert_eq!(fs::read_to_string(&fixture.path).expect("fixture should remain"), original);
}
#[test]
fn empty_fix_plan_still_rejects_a_stale_planning_revision() {
let fixture = TestSnapshot::from_fixture();
let error = run_staged_fix_transaction(&fixture.path, &[], Some("md5:stale"), true, "browser", &[], None)
.expect_err("an empty fix plan should still be bound to its planning revision");
assert!(error.contains("revision mismatch"), "error: {error}");
}
#[test]
fn staged_fix_validation_preserves_selected_entry_before_snapshot_path() {
let args = staged_fix_validation_args(
Path::new("/tmp/project/calcit.cirru.staged"),
"browser",
&[
"--ns".to_owned(),
"app.browser".to_owned(),
"--preset".to_owned(),
"surface-latest-v2".to_owned(),
],
);
assert_eq!(
args,
vec![
"--tips-level",
"none",
"--entry",
"browser",
"/tmp/project/calcit.cirru.staged",
"fix",
"--ns",
"app.browser",
"--preset",
"surface-latest-v2",
]
.into_iter()
.map(OsString::from)
.collect::<Vec<_>>()
);
}
#[test]
fn staged_warning_difference_allows_baseline_warnings_but_rejects_new_multiplicity() {
let baseline = vec!["warning-a".to_owned(), "warning-b".to_owned()];
assert!(staged_warning_difference(&baseline, &["warning-a".to_owned()]).is_empty());
assert_eq!(
staged_warning_difference(&baseline, &["warning-a".to_owned(), "warning-a".to_owned()]),
vec!["warning-a".to_owned()]
);
assert_eq!(
staged_warning_difference(&baseline, &["warning-c".to_owned()]),
vec!["warning-c".to_owned()]
);
}
#[test]
fn transaction_dry_run_validates_but_keeps_original_snapshot() {
let fixture = TestSnapshot::from_fixture();
let original = fs::read_to_string(&fixture.path).expect("fixture should read");
let operations = vec![vec!["config".to_string(), "package".to_string(), "transaction-test".to_string()]];
let report = run_staged_transaction_with(&fixture.path, &operations, None, true, fake_package_operation)
.expect("dry-run transaction should validate");
assert!(report.dry_run);
assert!(report.changed);
assert_ne!(report.original_revision, report.new_revision);
assert_eq!(fs::read_to_string(&fixture.path).expect("fixture should remain"), original);
}
#[test]
fn transaction_failure_discards_prior_staged_operations() {
let fixture = TestSnapshot::from_fixture();
let original = fs::read_to_string(&fixture.path).expect("fixture should read");
let operations = vec![
vec!["config".to_string(), "package".to_string(), "transaction-test".to_string()],
vec!["config".to_string(), "package".to_string(), "transaction-test-2".to_string()],
];
let error = run_staged_transaction_with(&fixture.path, &operations, None, false, |path, index, args| {
if index == 0 {
fake_package_operation(path, index, args)
} else {
Err("simulated second operation failure".to_string())
}
})
.expect_err("failed operation should abort transaction");
assert!(error.contains("simulated second operation failure"), "error: {error}");
assert_eq!(fs::read_to_string(&fixture.path).expect("fixture should remain"), original);
}
#[test]
fn successful_transaction_replaces_snapshot_once() {
let fixture = TestSnapshot::from_fixture();
let operations = vec![vec!["config".to_string(), "package".to_string(), "transaction-test".to_string()]];
let report =
run_staged_transaction_with(&fixture.path, &operations, None, false, fake_package_operation).expect("transaction should commit");
assert!(!report.dry_run);
assert!(report.changed);
assert_eq!(
load_snapshot(&fixture.path.to_string_lossy())
.expect("committed snapshot should load")
.package,
"transaction-test"
);
assert!(
!fs::read_to_string(&fixture.path)
.expect("committed snapshot should read")
.contains(":version")
);
}
#[test]
fn rename_rejects_mismatched_definition_key_and_declaration() {
let code = list(vec![leaf("defn"), leaf("actual"), list(vec![]), leaf("nil")]);
let error = rename_fixture_declaration(&code, "stored-key", "next").expect_err("mismatch should fail");
assert!(error.contains("does not match declaration name"), "error: {error}");
}
#[test]
fn rename_keeps_anonymous_payloads_unchanged() {
let code = list(vec![leaf("fn"), list(vec![]), leaf("nil")]);
let (renamed, changed) = rename_fixture_declaration(&code, "old", "next").expect("anonymous value should be movable");
assert!(!changed);
assert_eq!(renamed, code);
}
#[test]
fn examples_require_one_quote_per_ast_node() {
let error = parse_examples_input("inc 1").expect_err("bare examples should fail");
assert!(error.contains("needs its own `quote`"), "error: {error}");
}
#[test]
fn examples_preserve_quoted_expressions_and_leaves() {
let examples = parse_examples_input("quote $ inc 1\nquote |literal").expect("examples should parse");
assert_eq!(examples, vec![list(vec![leaf("inc"), leaf("1")]), leaf("|literal")]);
}
#[test]
fn named_tests_can_be_added_and_removed_without_indexing() {
let fixture = TestSnapshot::from_fixture();
let path = fixture.snapshot_string();
let add = EditAddTestCommand {
target: "app.main/test-fn".to_owned(),
name: "empty-call".to_owned(),
tags: Some("unit,fast".to_owned()),
file: None,
code: Some("quote $ assert= nil (fn)".to_owned()),
input_format: SyntaxInputFormat::Auto,
overwrite: false,
};
handle_add_test(&add, &path).expect("named test should be added");
let snapshot = load_snapshot(&path).expect("edited snapshot should load");
let test = &snapshot.files["app.main"].defs["test-fn"].tests[0];
assert_eq!(test.name, "empty-call");
assert_eq!(test.tags.len(), 2);
let duplicate = handle_add_test(&add, &path).expect_err("duplicate test name should fail");
assert!(duplicate.contains("already exists"), "unexpected error: {duplicate}");
let mut replacement = add.clone();
replacement.overwrite = true;
replacement.code = Some("quote $ assert= true true".to_owned());
handle_add_test(&replacement, &path).expect("explicit overwrite should replace named test");
let snapshot = load_snapshot(&path).expect("overwritten snapshot should load");
assert_ne!(snapshot.files["app.main"].defs["test-fn"].tests[0].code, test.code);
handle_meta(
&EditMetaCommand {
target: add.target,
doc: None,
tags: None,
add_tags: Vec::new(),
rm_tags: Vec::new(),
clear_tags: false,
examples: false,
add_example: false,
at: None,
clear_examples: false,
file: None,
code: None,
input_format: SyntaxInputFormat::Auto,
rm_tests: vec![add.name],
expect_revision: None,
dry_run: false,
format: "human".to_owned(),
},
&path,
)
.expect("named test should be removed");
let snapshot = load_snapshot(&path).expect("edited snapshot should load");
assert!(snapshot.files["app.main"].defs["test-fn"].tests.is_empty());
}
#[test]
fn schema_input_requires_quote_for_leaf_and_expression() {
let expected = list(vec![leaf("::"), leaf(":ref"), leaf(":bool")]);
assert_eq!(
parse_schema_input("quote $ :: :ref :bool", SyntaxInputFormat::Auto).expect("quoted schema should parse"),
expected
);
assert_eq!(
parse_schema_input("quote :string", SyntaxInputFormat::Auto).expect("primitive schema should parse"),
leaf(":string")
);
let error = parse_schema_input(":: :ref :bool", SyntaxInputFormat::Auto).expect_err("bare schema should fail");
assert!(error.contains("Schema examples: `quote String`"), "error: {error}");
}
#[test]
fn schema_edit_preserves_explicit_dynamic_container_arguments() {
let fixture = TestSnapshot::from_fixture();
let path = fixture.snapshot_string();
let opts = EditSchemaCommand {
target: "app.main/test-fn".to_owned(),
file: None,
code: Some("quote $ Fn (List Dynamic) (-> $ List Dynamic)".to_owned()),
input_format: SyntaxInputFormat::Auto,
clear: false,
add_feature: None,
};
handle_schema(&opts, &path).expect("explicit List<Dynamic> schema should be written");
let snapshot = load_snapshot(&path).expect("edited snapshot should load");
let schema = &snapshot.files["app.main"].defs["test-fn"].schema;
let CalcitTypeAnnotation::Fn(signature) = schema.as_ref() else {
panic!("expected Fn schema, got {schema:?}")
};
let explicit_list = Edn::enum_value("List", vec![Edn::Symbol(Arc::from("Dynamic"))]);
assert_eq!(signature.arg_types[0].to_type_edn(), explicit_list);
assert_eq!(signature.return_type.to_type_edn(), explicit_list);
}
#[test]
fn schema_edit_stores_retired_input_in_the_compact_spelling() {
let fixture = TestSnapshot::from_fixture();
let path = fixture.snapshot_string();
let opts = EditSchemaCommand {
target: "app.main/test-fn".to_owned(),
file: None,
code: Some("quote $ :: 'Fn $ {} (:args $ [] 'Number) (:return 'Number)".to_owned()),
input_format: SyntaxInputFormat::Auto,
clear: false,
add_feature: None,
};
handle_schema(&opts, &path).expect("retired schema input is still accepted");
let written = fs::read_to_string(&fixture.path).expect("read snapshot");
assert!(written.contains(":schema $ quote $ Fn Number (-> Number)"), "snapshot:\n{written}");
assert!(!written.contains(":: 'Fn"), "snapshot:\n{written}");
}
#[test]
fn schema_add_js_ffi_feature_preserves_signature_and_rejects_unstructured_schema() {
let fixture = TestSnapshot::from_fixture();
let path = fixture.snapshot_string();
let target = "app.main/test-fn".to_owned();
let declared = EditSchemaCommand {
target: target.clone(),
file: None,
code: Some("quote $ Fn T (-> T) (:generics T) (:features :async)".to_owned()),
input_format: SyntaxInputFormat::Auto,
clear: false,
add_feature: None,
};
handle_schema(&declared, &path).expect("generic Fn schema should be accepted");
let before = load_snapshot(&path).expect("original schema should load");
let original = &before.files["app.main"].defs["test-fn"];
let feature = EditSchemaCommand {
target: target.clone(),
file: None,
code: None,
input_format: SyntaxInputFormat::Auto,
clear: false,
add_feature: Some("js-ffi".to_owned()),
};
handle_schema(&feature, &path).expect("feature should be added locally");
let after = load_snapshot(&path).expect("updated schema should load");
let updated = &after.files["app.main"].defs["test-fn"];
let (CalcitTypeAnnotation::Fn(old_signature), CalcitTypeAnnotation::Fn(new_signature)) =
(original.schema.as_ref(), updated.schema.as_ref())
else {
panic!("both schemas should be Fn annotations");
};
assert_eq!(new_signature.generics, old_signature.generics);
assert_eq!(new_signature.arg_types, old_signature.arg_types);
assert_eq!(new_signature.return_type, old_signature.return_type);
assert_eq!(new_signature.where_bounds, old_signature.where_bounds);
assert_eq!(new_signature.rest_type, old_signature.rest_type);
assert!(new_signature.features.iter().any(|item| item.ref_str() == "async"));
assert!(new_signature.features.iter().any(|item| item.ref_str() == "js-ffi"));
assert_eq!(updated.code, original.code);
assert_eq!(updated.doc, original.doc);
assert_eq!(updated.examples, original.examples);
assert_eq!(updated.tests, original.tests);
assert_eq!(updated.tags, original.tags);
assert_eq!(updated.ffi, original.ffi);
let erased_cache = EditSchemaCommand {
add_feature: Some("erased-cache".to_owned()),
..feature.clone()
};
handle_schema(&erased_cache, &path).expect("erased-cache feature should be added locally");
let after_cache = load_snapshot(&path).expect("updated schema should load");
let CalcitTypeAnnotation::Fn(cache_signature) = after_cache.files["app.main"].defs["test-fn"].schema.as_ref() else {
panic!("schema should stay an Fn annotation");
};
assert!(cache_signature.features.iter().any(|item| item.ref_str() == "erased-cache"));
assert!(cache_signature.features.iter().any(|item| item.ref_str() == "js-ffi"));
let unsupported = EditSchemaCommand {
add_feature: Some("host-io".to_owned()),
..erased_cache
};
assert!(
handle_schema(&unsupported, &path)
.unwrap_err()
.contains("Unsupported schema feature")
);
let clear = EditSchemaCommand {
target,
clear: true,
add_feature: None,
..feature.clone()
};
handle_schema(&clear, &path).expect("schema should clear");
let error = handle_schema(&feature, &path).expect_err("dynamic schema must not gain a lexical capability");
assert!(error.contains("needs a structured Fn schema"), "error: {error}");
assert!(error.contains("`calcit edit ffi` changes export metadata"), "error: {error}");
}
#[test]
fn schema_edit_tag_value_survives_canonical_snapshot_formatting() {
let fixture = TestSnapshot::from_fixture();
let path = fixture.snapshot_string();
let opts = EditSchemaCommand {
target: "app.main/test-fn".to_owned(),
file: None,
code: Some("quote 'Tag".to_owned()),
input_format: SyntaxInputFormat::Auto,
clear: false,
add_feature: None,
};
handle_schema(&opts, &path).expect("Tag value schema should be written");
let snapshot = load_snapshot(&path).expect("edited snapshot should load");
assert!(matches!(
snapshot.files["app.main"].defs["test-fn"].schema.as_ref(),
CalcitTypeAnnotation::Tag
));
handle_format(
&EditFormatCommand {
drop_legacy_entry_fields: vec![],
},
&path,
)
.expect("edit format should preserve the Tag schema");
let formatted = load_snapshot(&path).expect("canonically formatted snapshot should reload");
assert!(matches!(
formatted.files["app.main"].defs["test-fn"].schema.as_ref(),
CalcitTypeAnnotation::Tag
));
}
#[test]
fn schema_edit_preserves_unrelated_legacy_schema_serialization() {
let fixture = TestSnapshot::from_fixture();
let source = r#"#! /usr/bin/env calcit
{} (:package |demo) (:version |0.0.1)
:entries $ {}
:default $ {} (:description |) (:init-fn 'app.main/target) (:mode :native) (:reload-fn 'app.main/target)
:modules $ []
:type-slots $ {}
:files $ {}
|app.main $ %{} :FileEntry
:defs $ {}
|legacy $ %{} :CodeEntry
:code $ quote $ defn legacy (x) x
:schema $ quote $ Fn (JsNullish String) (-> Dynamic)
|target $ %{} :CodeEntry
:code $ quote $ defn target () nil
:schema $ quote Dynamic
:ns $ %{} :CodeEntry (:code $ quote $ ns app.main)
"#;
fs::write(&fixture.path, source).expect("write snapshot");
let before = cirru_edn::parse(source.strip_prefix("#! /usr/bin/env calcit\n").expect("shebang")).expect("parse source");
let schema = calcit_core::snapshot::parse_schema_annotation_for_write(&leaf(":string")).expect("parse schema");
save_schema_preserving_snapshot(&fixture.snapshot_string(), "app.main", "target", Some(schema.as_ref()))
.expect("save target schema");
let output = fs::read_to_string(&fixture.path).expect("read snapshot");
assert!(output.starts_with("#! /usr/bin/env calcit\n"));
let after = cirru_edn::parse(output.strip_prefix("#! /usr/bin/env calcit\n").expect("shebang")).expect("parse output");
let schema_for = |snapshot: &cirru_edn::Edn, definition_name: &str| {
let cirru_edn::Edn::Map(root) = snapshot else { panic!("root") };
let cirru_edn::Edn::Map(files) = root.get_or_nil("files") else {
panic!("files")
};
let cirru_edn::Edn::Struct(file) = files.get_or_nil("app.main") else {
panic!("namespace")
};
let cirru_edn::Edn::Map(defs) = file["defs"].clone() else {
panic!("defs")
};
let cirru_edn::Edn::Struct(definition) = defs.get_or_nil(definition_name) else {
panic!("definition")
};
definition
.pairs
.iter()
.find(|(key, _)| key.ref_str() == "schema")
.map(|(_, value)| value.clone())
};
assert_eq!(schema_for(&before, "legacy"), schema_for(&after, "legacy"));
assert_ne!(schema_for(&before, "target"), schema_for(&after, "target"));
save_schema_preserving_snapshot(&fixture.snapshot_string(), "app.main", "target", None).expect("clear target schema");
let cleared_text = fs::read_to_string(&fixture.path).expect("read cleared snapshot");
let cleared = cirru_edn::parse(cleared_text.strip_prefix("#! /usr/bin/env calcit\n").expect("shebang")).expect("parse cleared");
assert_eq!(schema_for(&before, "legacy"), schema_for(&cleared, "legacy"));
assert_eq!(schema_for(&cleared, "target"), None);
}
#[test]
fn bumps_patch_version() {
assert_eq!(bump_semver_value("0.0.0", "patch"), Ok("0.0.1".to_string()));
}
#[test]
fn bumps_minor_version() {
assert_eq!(bump_semver_value("1.2.3", "minor"), Ok("1.3.0".to_string()));
}
#[test]
fn bumps_major_version() {
assert_eq!(bump_semver_value("1.2.3", "major"), Ok("2.0.0".to_string()));
}
#[test]
fn rejects_unknown_bump_level() {
assert_eq!(
bump_semver_value("1.2.3", "build"),
Err("Unknown bump level 'build'. Valid levels: patch, minor, major".to_string())
);
}
#[test]
fn clears_prerelease_and_build_metadata_when_bumping() {
assert_eq!(bump_semver_value("1.2.3-alpha.1+build.2", "patch"), Ok("1.2.4".to_string()));
}
}