use cirru_parser::Cirru;
use colored::Colorize;
use std::fmt::Write as _;
use super::chunk_display::{ChunkDisplayOptions, ChunkedDisplay, fragment_nesting_level, maybe_chunk_node};
use super::common::{
ERR_CODE_INPUT_REQUIRED, cirru_to_json_value, decode_mutation_syntax_input, emit_cli_output, format_path,
guard_snapshot_mutation_toolchain, markdown_cirru_section, markdown_fenced_block, parse_input_to_cirru, parse_path,
print_cli_warning_block, read_code_input, resolve_definition_lookup, shell_quote,
};
use super::cursor::{
maintain_cursor_after_tree_mutation, resolve_active_cursor_reference, resolve_cursor_path_argument, resolve_cursor_target_argument,
};
use super::structured_output::StructuredOutputFormat;
use super::tips::{TipPriority, Tips, command_guidance_enabled, tip_prefer_oneliner_json_markdown, tip_root_edit};
use crate::cli_args::SyntaxInputFormat;
use crate::cli_args::{
TreeCommand, TreeDeleteCommand, TreeInsertCommand, TreeRaiseCommand, TreeReplaceCommand, TreeReplaceLeafCommand,
TreeSearchReplaceCommand, TreeShowCommand, TreeStructuralCommand, TreeSubcommand, TreeSwapCommand, TreeUnwrapCommand,
TreeWrapCommand,
};
use super::edit::{
apply_operation_at_path, check_ns_editable, load_snapshot, navigate_to_path, parse_target, process_node_with_references,
save_snapshot,
};
use super::query::resolve_path_expression;
use super::tree_mutation::{TreeCursorMutation, TreeOperation};
fn save_definition_tree(
snapshot: &calcit_core::snapshot::Snapshot,
snapshot_file: &str,
namespace: &str,
definition: &str,
) -> Result<(), String> {
let entry = snapshot
.files
.get(namespace)
.and_then(|file| file.defs.get(definition))
.ok_or_else(|| format!("Definition '{namespace}/{definition}' not found"))?;
calcit_core::snapshot::validate_definition_root(&entry.code, &format!("{namespace}/{definition}"))?;
save_snapshot(snapshot, snapshot_file)
}
pub fn handle_tree_command(cmd: &TreeCommand, snapshot_file: &str) -> Result<(), String> {
match &cmd.subcommand {
TreeSubcommand::Insert(opts) => {
insert_operation(&opts.at)?;
}
TreeSubcommand::Swap(opts) => {
swap_operation(&opts.with)?;
}
_ => {}
}
let _writer = if !matches!(&cmd.subcommand, TreeSubcommand::Show(_)) {
Some(calcit_core::util::atomic_write::SnapshotWriteGuard::acquire(snapshot_file)?)
} else {
None
};
if !matches!(&cmd.subcommand, TreeSubcommand::Show(_)) {
guard_snapshot_mutation_toolchain(snapshot_file)?;
}
let mut resolved = cmd.clone();
resolve_tree_cursor_references(&mut resolved, snapshot_file)?;
let cursor_mutation = prepare_cursor_mutation(&resolved, snapshot_file)?;
let result = match &resolved.subcommand {
TreeSubcommand::Show(opts) => handle_show(opts, snapshot_file),
TreeSubcommand::Replace(opts) => handle_replace(opts, snapshot_file),
TreeSubcommand::ReplaceLeaf(opts) => handle_replace_leaf(opts, snapshot_file),
TreeSubcommand::Delete(opts) => handle_delete(opts, snapshot_file),
TreeSubcommand::Insert(opts) => handle_insert(opts, snapshot_file),
TreeSubcommand::Swap(opts) => handle_swap(opts, snapshot_file),
TreeSubcommand::Unwrap(opts) => handle_unwrap(opts, snapshot_file),
TreeSubcommand::Raise(opts) => handle_raise(opts, snapshot_file),
TreeSubcommand::Wrap(opts) => handle_wrap(opts, snapshot_file),
TreeSubcommand::SearchReplace(opts) => handle_search_replace(opts, snapshot_file),
TreeSubcommand::Rewrite(opts) => handle_rewrite(opts, snapshot_file),
};
if let Err(error) = result {
if error.starts_with("# Error:") {
eprintln!("{error}");
return Err("Tree mutation rejected; details were written to stderr.".to_owned());
}
return Err(error);
}
if let Some((target, mutation)) = cursor_mutation {
maintain_cursor_after_tree_mutation(snapshot_file, &target, &mutation)?;
}
Ok(())
}
fn verify_expected_node(actual: &Cirru, expected_input: Option<&str>, path: &[usize]) -> Result<(), String> {
let Some(expected_input) = expected_input else {
return Ok(());
};
let expected = parse_input_to_cirru(expected_input).map_err(|error| format!("Invalid --expect value: {error}"))?;
if actual == &expected {
return Ok(());
}
Err(format!(
"# Error: node guard failed\n\n- path: `{}`\n- changed: `false`\n\n{}\n{}\nNo changes were written. Re-run `calcit tree show ... --path {}` and update `--expect` or the path.",
format_path(path),
markdown_cirru_section(2, "Expected", &expected, 6)?,
markdown_cirru_section(2, "Actual", actual, 6)?,
format_path(path),
))
}
fn resolve_tree_cursor_references(cmd: &mut TreeCommand, snapshot_file: &str) -> Result<(), String> {
let target = match &mut cmd.subcommand {
TreeSubcommand::Show(opts) => &mut opts.target,
TreeSubcommand::Replace(opts) => &mut opts.target,
TreeSubcommand::ReplaceLeaf(opts) => &mut opts.target,
TreeSubcommand::Delete(opts) => &mut opts.target,
TreeSubcommand::Insert(opts) => &mut opts.target,
TreeSubcommand::Swap(opts) => &mut opts.target,
TreeSubcommand::Unwrap(opts) => &mut opts.target,
TreeSubcommand::Raise(opts) => &mut opts.target,
TreeSubcommand::Wrap(opts) => &mut opts.target,
TreeSubcommand::SearchReplace(opts) => &mut opts.target,
TreeSubcommand::Rewrite(opts) => &mut opts.target,
};
let active_reference = if target == "@cursor" {
Some(resolve_active_cursor_reference(snapshot_file)?)
} else {
None
};
*target = match &active_reference {
Some((active_target, _)) => active_target.clone(),
None => resolve_cursor_target_argument(snapshot_file, target)?,
};
let resolve = |target: &str, path: &mut String| -> Result<(), String> {
*path = 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}'."
));
}
active_path.clone()
} else {
resolve_cursor_path_argument(snapshot_file, target, path)?
};
Ok(())
};
match &mut cmd.subcommand {
TreeSubcommand::Show(opts) => {
if let Some(path) = &mut opts.path {
resolve(&opts.target, path)?;
}
}
TreeSubcommand::Replace(opts) => resolve(&opts.target, &mut opts.path)?,
TreeSubcommand::ReplaceLeaf(_) | TreeSubcommand::SearchReplace(_) => {}
TreeSubcommand::Delete(opts) => resolve(&opts.target, &mut opts.path)?,
TreeSubcommand::Insert(opts) => resolve(&opts.target, &mut opts.path)?,
TreeSubcommand::Swap(opts) => resolve(&opts.target, &mut opts.path)?,
TreeSubcommand::Unwrap(opts) => resolve(&opts.target, &mut opts.path)?,
TreeSubcommand::Raise(opts) => resolve(&opts.target, &mut opts.path)?,
TreeSubcommand::Wrap(opts) => resolve(&opts.target, &mut opts.path)?,
TreeSubcommand::Rewrite(opts) => resolve(&opts.target, &mut opts.path)?,
}
Ok(())
}
fn prepare_cursor_mutation(cmd: &TreeCommand, snapshot_file: &str) -> Result<Option<(String, TreeCursorMutation)>, String> {
let prepared = match &cmd.subcommand {
TreeSubcommand::Show(_) => return Ok(None),
TreeSubcommand::Replace(opts) => (
opts.target.clone(),
TreeCursorMutation::Replace {
path: parse_path(&opts.path)?,
},
),
TreeSubcommand::ReplaceLeaf(opts) => (opts.target.clone(), TreeCursorMutation::NoPathShift),
TreeSubcommand::Delete(opts) => (
opts.target.clone(),
TreeCursorMutation::Delete {
path: parse_path(&opts.path)?,
},
),
TreeSubcommand::Insert(opts) => {
let path = parse_path(&opts.path)?;
let mutation = match insert_operation(&opts.at)? {
TreeOperation::InsertBefore => TreeCursorMutation::InsertBefore { path },
TreeOperation::InsertAfter => TreeCursorMutation::InsertAfter { path },
TreeOperation::InsertChild => TreeCursorMutation::InsertChild { path },
_ => TreeCursorMutation::NoPathShift,
};
(opts.target.clone(), mutation)
}
TreeSubcommand::Swap(opts) => {
let path = parse_path(&opts.path)?;
let mutation = match swap_operation(&opts.with)? {
TreeOperation::SwapNextSibling => TreeCursorMutation::SwapNext { path },
_ => TreeCursorMutation::SwapPrev { path },
};
(opts.target.clone(), mutation)
}
TreeSubcommand::Unwrap(opts) => {
let path = parse_path(&opts.path)?;
let (namespace, definition) = parse_target(&opts.target)?;
let snapshot = load_snapshot(snapshot_file)?;
let entry = snapshot
.files
.get(namespace)
.and_then(|file| file.defs.get(definition))
.ok_or_else(|| format!("Definition '{}' not found", opts.target))?;
let child_count = match navigate_to_path(&entry.code, &path)? {
Cirru::List(children) => children.len(),
Cirru::Leaf(_) => 0,
};
(opts.target.clone(), TreeCursorMutation::Unwrap { path, child_count })
}
TreeSubcommand::Raise(opts) => (
opts.target.clone(),
TreeCursorMutation::Raise {
path: parse_path(&opts.path)?,
},
),
TreeSubcommand::Wrap(opts) => (
opts.target.clone(),
TreeCursorMutation::Wrap {
path: parse_path(&opts.path)?,
},
),
TreeSubcommand::SearchReplace(opts) => (opts.target.clone(), TreeCursorMutation::NoPathShift),
TreeSubcommand::Rewrite(opts) => (
opts.target.clone(),
TreeCursorMutation::Replace {
path: parse_path(&opts.path)?,
},
),
};
Ok(Some(prepared))
}
fn parse_with_references(with_strs: &[String], original_node: &Cirru) -> Result<std::collections::BTreeMap<String, Cirru>, String> {
let mut references = std::collections::BTreeMap::new();
for s in with_strs {
let (name, path_str) = s
.split_once('=')
.ok_or_else(|| format!("Invalid --with format '{s}'. Expected 'name=path', e.g. --with self=. --with arg=1,0"))?;
if name.trim().is_empty() {
return Err(format!("Invalid --with format '{s}': name cannot be empty"));
}
let path = if path_str.trim() == "." {
vec![]
} else {
parse_path(path_str.trim())?
};
let node = navigate_to_path(original_node, &path)?;
references.insert(name.trim().to_string(), node);
}
Ok(references)
}
fn format_preview(node: &Cirru, max_lines: usize) -> String {
let formatted = match node {
Cirru::Leaf(s) => {
format!(" {:?}", s.as_ref())
}
Cirru::List(_) => {
match cirru_parser::format(std::slice::from_ref(node), cirru_parser::CirruWriterOptions { use_inline: false }) {
Ok(cirru_str) => {
let lines: Vec<&str> = cirru_str.lines().collect();
if lines.len() > max_lines {
let mut result = String::new();
for line in lines.iter().take(max_lines) {
result.push_str(" ");
result.push_str(line);
result.push('\n');
}
result.push_str(&format!(" {}\n", format!("... ({} more lines)", lines.len() - max_lines).dimmed()));
result
} else {
lines.iter().map(|line| format!(" {line}\n")).collect()
}
}
Err(e) => format!(" {}\n", format!("(failed to format: {e})").red()),
}
}
};
formatted.trim_end().to_string()
}
fn print_preview_block(label: &str, node: &Cirru, max_lines: usize, _color: &str) {
match markdown_cirru_section(2, label, node, max_lines) {
Ok(section) => println!("{section}"),
Err(error) => println!("## {label}\n\n_Unable to render preview: {error}_"),
}
}
fn first_leaf_preview(node: &Cirru) -> Option<String> {
match node {
Cirru::Leaf(s) => Some(format!("{:?}", s.as_ref())),
Cirru::List(items) => items.iter().find_map(first_leaf_preview),
}
}
fn format_child_preview(node: &Cirru) -> String {
match node {
Cirru::Leaf(s) => format!("{:?}", s.as_ref()),
Cirru::List(items) => {
if items.is_empty() {
"(empty)".to_string()
} else {
let head = first_leaf_preview(node).unwrap_or_else(|| "<expr>".to_string());
format!("({head} ...)")
}
}
}
}
fn inline_cirru(node: &Cirru) -> Option<String> {
let text = match node {
Cirru::Leaf(leaf) => cirru_parser::generate_leaf(leaf),
Cirru::List(_) => cirru_parser::format_expr_one_liner(node).ok()?,
};
(!text.contains('\n') && text.len() <= 100).then_some(text)
}
fn show_diff_preview(old_node: &Cirru, new_node: &Cirru, operation: &str, path: &[usize]) -> String {
let mut output = String::new();
let location = if path.is_empty() { "root".to_owned() } else { format_path(path) };
let _ = writeln!(
&mut output,
"# Tree mutation `{operation}` at `{location}`
"
);
if let (Some(before), Some(after)) = (inline_cirru(old_node), inline_cirru(new_node)) {
let _ = writeln!(&mut output, "- before: `{before}`");
let _ = writeln!(&mut output, "- after: `{after}`");
return output;
}
match markdown_cirru_section(2, "Before", old_node, 10) {
Ok(section) => output.push_str(§ion),
Err(error) => output.push_str(&format!("## Before\n\n_Unable to render preview: {error}_\n")),
}
output.push('\n');
match markdown_cirru_section(2, "After", new_node, 10) {
Ok(section) => output.push_str(§ion),
Err(error) => output.push_str(&format!("## After\n\n_Unable to render preview: {error}_\n")),
}
output
}
fn render_chunked_display(display: &ChunkedDisplay, chunk_expand_depth: usize) -> (String, usize) {
let mut out = String::new();
let _ = writeln!(&mut out, "## Chunked preview\n");
let _ = writeln!(
&mut out,
"nodes: {}, branches: {}, leaves: {}, max depth: {}, fragments: {}",
display.total.nodes,
display.total.branches,
display.total.leaves,
display.total.max_depth,
display.fragments.len()
);
let _ = writeln!(&mut out);
let visible_fragments: Vec<_> = display
.fragments
.iter()
.filter(|fragment| fragment_nesting_level(fragment, &display.fragments) <= chunk_expand_depth)
.collect();
if visible_fragments.len() < display.fragments.len() {
let _ = writeln!(
&mut out,
"showing {}/{} fragments; nested chunks beyond level {} are hidden",
visible_fragments.len(),
display.fragments.len(),
chunk_expand_depth
);
let _ = writeln!(&mut out);
}
for fragment in &visible_fragments {
let _ = writeln!(&mut out, "### Fragment `{}`\n", fragment.id);
let _ = writeln!(
&mut out,
"- Coordinate: `{}`\n- Nodes: {}\n- Max depth: {}\n",
fragment.coord, fragment.nodes, fragment.depth
);
out.push_str(&markdown_fenced_block("cirru", &fragment.cirru));
let _ = writeln!(&mut out);
}
(out, visible_fragments.len())
}
fn annotate_paths(node: &mut Cirru, current_path: &[usize], annotate_root: bool) {
if let Cirru::List(children) = node {
for (i, child) in children.iter_mut().enumerate() {
let mut child_path = current_path.to_vec();
child_path.push(i);
annotate_paths(child, &child_path, true);
}
if annotate_root && !current_path.is_empty() {
let path_str = format_path(current_path);
let comment = Cirru::List(vec![
Cirru::Leaf(";".into()),
Cirru::Leaf(format!("previous node path: {path_str}").into()),
]);
children.push(comment);
}
}
}
fn handle_show(opts: &TreeShowCommand, snapshot_file: &str) -> Result<(), String> {
let output_format = StructuredOutputFormat::parse(&opts.format, "tree show")?;
let (namespace, definition) = parse_target(&opts.target)?;
let path = match &opts.path {
Some(p) => parse_path(p)?,
None => {
eprintln!(
"{}",
"[Warn] No --path specified; showing from root. Use --path '0' to start from a child node.".yellow()
);
vec![]
}
};
let snapshot = load_snapshot(snapshot_file)?;
let file_data = snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
let lookup = resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), true)?;
let render_to_stderr = lookup.warning.is_some();
if let Some(warning) = lookup.warning.as_deref() {
print_cli_warning_block(warning);
}
let resolved_definition = lookup.resolved;
let resolved_target = format!("{namespace}/{resolved_definition}");
let code_entry = file_data
.defs
.get(resolved_definition.as_str())
.expect("resolved definition exists");
let mut node = match navigate_to_path(&code_entry.code, &path) {
Ok(n) => n,
Err(original_error) => {
let mut valid_depth = 0;
let mut current = &code_entry.code;
for (depth, &idx) in path.iter().enumerate() {
match current {
Cirru::Leaf(_) => {
valid_depth = depth;
break;
}
Cirru::List(items) => {
if idx >= items.len() {
valid_depth = depth;
break;
}
current = &items[idx];
valid_depth = depth + 1;
}
}
}
let valid_path = &path[..valid_depth];
let valid_node = navigate_to_path(&code_entry.code, valid_path).unwrap();
let valid_path_display = format_path(valid_path);
let node_preview = format_preview(&valid_node, 6);
let node_kind = match &valid_node {
Cirru::Leaf(_) => "leaf".to_owned(),
Cirru::List(items) => format!("list, {} items", items.len()),
};
eprintln!("# Error: invalid path\n\n{original_error}\n");
eprintln!("- Longest valid path: `{valid_path_display}`");
eprintln!("- Node kind: `{node_kind}`\n");
eprintln!("## Node at longest valid path\n");
eprint!("{}", markdown_fenced_block("cirru", &node_preview));
match &valid_node {
Cirru::Leaf(_) => {
eprintln!("\nThis is a leaf node and cannot be navigated further.\n");
eprintln!(
"- View it with: `calcit tree show '{}' --path '{}'`",
resolved_target,
format_path(valid_path)
);
}
Cirru::List(items) => {
eprintln!(
"\nThis node has {} children (indices 0–{}).\n",
items.len(),
items.len().saturating_sub(1)
);
eprintln!(
"- View it with: `calcit tree show '{}' --path '{}'`",
resolved_target,
format_path(valid_path)
);
if !items.is_empty() {
eprintln!();
eprintln!("## First children\n");
for (i, item) in items.iter().enumerate().take(3) {
let child_preview = format_child_preview(item);
let child_path = if valid_path.is_empty() {
i.to_string()
} else {
format!("{}.{}", format_path(valid_path), i)
};
eprintln!("- [{i}] `{child_preview}` → `--path '{child_path}'`");
}
if items.len() > 3 {
eprintln!("- _... and {} more._", items.len() - 3);
}
}
}
}
return Err(String::new()); }
};
if opts.path_annotations {
annotate_paths(&mut node, &path, !path.is_empty());
}
if output_format != StructuredOutputFormat::Human {
let tree = cirru_to_json_value(&node);
return output_format.print_value(&serde_json::json!({
"schema_version": 1,
"command": "tree.show",
"target": resolved_target,
"path": format_path(&path),
"type": if matches!(node, Cirru::Leaf(_)) { "leaf" } else { "list" },
"tree": tree,
}));
}
let node_type = match &node {
Cirru::Leaf(_) => "leaf",
Cirru::List(items) => {
let chunk_options = ChunkDisplayOptions {
trigger_nodes: opts.chunk_trigger_nodes,
target_nodes: opts.chunk_target_nodes,
max_nodes: opts.chunk_max_nodes,
max_branches: 64,
};
let chunked_display = if opts.raw { None } else { maybe_chunk_node(&node, &chunk_options)? };
let mut out = String::new();
let _ = writeln!(&mut out, "# Tree node `{resolved_target}`\n");
let _ = writeln!(&mut out, "- Path: `{}`", format_path(&path));
let _ = writeln!(&mut out, "- Type: `list`");
let _ = writeln!(&mut out, "- Items: {}\n", items.len());
let shown_fragments = if let Some(display) = chunked_display {
let (chunked, shown) = render_chunked_display(&display, opts.chunk_expand_depth);
out.push_str(&chunked);
Some((shown, display.fragments.len()))
} else {
let _ = writeln!(&mut out, "## Cirru preview\n");
let cirru_str = cirru_parser::format(std::slice::from_ref(&node), cirru_parser::CirruWriterOptions { use_inline: true })
.map_err(|e| format!("Failed to format Cirru: {e}"))?;
out.push_str(&markdown_fenced_block("cirru", &cirru_str));
let _ = writeln!(&mut out);
None
};
let mut tips = Tips::new();
if items.len() > 8 && !opts.path_annotations {
tips.add_with_priority(
TipPriority::High,
format!(
"This node has {} children. Use `--path-annotations` to annotate each nested list with its path index for easier editing.",
items.len()
),
);
}
if let Some((shown_fragments, total_fragments)) = shown_fragments
&& shown_fragments < total_fragments
{
tips.add_with_priority(
TipPriority::High,
format!(
"Showing ROOT plus {} chunk layer(s). Use `--chunk-expand-depth {}` to reveal deeper nested fragments, or `--raw` to disable chunking.",
opts.chunk_expand_depth,
opts.chunk_expand_depth + 1
),
);
}
tips.append(tip_prefer_oneliner_json_markdown());
emit_cli_output(&out, render_to_stderr);
tips.print_markdown(render_to_stderr);
return Ok(());
}
};
if matches!(node_type, "leaf") {
let mut out = String::new();
let _ = writeln!(&mut out, "# Tree node `{resolved_target}`\n");
let _ = writeln!(&mut out, "- Path: `{}`", format_path(&path));
let _ = writeln!(&mut out, "- Type: `leaf`\n");
if let Cirru::Leaf(s) = &node {
let _ = writeln!(&mut out, "## Value\n");
out.push_str(&markdown_fenced_block("cirru", s.as_ref()));
let _ = writeln!(&mut out);
if command_guidance_enabled() {
let _ = writeln!(
&mut out,
"{}: Use {} for symbols, {} for strings",
"Tip".blue().bold(),
"-e 'symbol'".yellow(),
"-e '|text'".yellow()
);
}
}
emit_cli_output(&out, render_to_stderr);
}
Ok(())
}
fn handle_replace(opts: &TreeReplaceCommand, snapshot_file: &str) -> Result<(), String> {
let (namespace, definition) = parse_target(&opts.target)?;
let path = parse_path(&opts.path)?;
let code_input = read_code_input(&opts.file, &opts.code)?;
let raw = code_input.as_deref().ok_or(ERR_CODE_INPUT_REQUIRED)?;
let new_node = decode_mutation_syntax_input(raw, opts.input_format)?;
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 code_entry = file_data
.defs
.get_mut(definition)
.ok_or_else(|| format!("Definition '{definition}' not found"))?;
let old_node = navigate_to_path(&code_entry.code, &path)?;
verify_expected_node(&old_node, opts.expect.as_deref(), &path)?;
if let Some(t) = tip_root_edit(path.is_empty()) {
let mut tips = Tips::new();
tips.add_with_priority(TipPriority::High, t);
tips.print();
}
let new_code = apply_operation_at_path(&code_entry.code, &path, TreeOperation::Replace, Some(&new_node))?;
code_entry.code = new_code.clone();
save_definition_tree(&snapshot, snapshot_file, namespace, definition)?;
let replaced_node = navigate_to_path(&new_code, &path)?;
println!("# Tree mutation\n");
println!("- operation: `replace`");
println!("- target: `{}`", opts.target);
println!("- path: `{}`", format_path(&path));
println!("- changed: `true`\n");
print_preview_block("Before", &old_node, opts.depth, "yellow");
println!();
print_preview_block("After", &replaced_node, opts.depth, "green");
if !path.is_empty() {
let parent_path = &path[..path.len() - 1];
let parent_after = if parent_path.is_empty() {
new_code
} else {
navigate_to_path(&new_code, parent_path)?
};
println!();
print_preview_block("Containing expression after", &parent_after, opts.depth, "cyan");
}
Ok(())
}
fn handle_rewrite(opts: &TreeStructuralCommand, snapshot_file: &str) -> Result<(), String> {
if opts.with.is_empty() {
return Err("`tree rewrite` needs at least one `--with name=path`; for plain replacement use `tree replace`.".to_string());
}
let (namespace, definition) = parse_target(&opts.target)?;
let path = parse_path(&opts.path)?;
let code_input = read_code_input(&opts.file, &opts.code)?;
let raw = code_input.as_deref().ok_or(ERR_CODE_INPUT_REQUIRED)?;
let new_node = decode_mutation_syntax_input(raw, opts.input_format)?;
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 code_entry = file_data
.defs
.get_mut(definition)
.ok_or_else(|| format!("Definition '{definition}' not found"))?;
let original_node = navigate_to_path(&code_entry.code, &path)?;
let references = parse_with_references(&opts.with, &original_node)?;
let processed_node = process_node_with_references(&new_node, &references)?;
let old_node = navigate_to_path(&code_entry.code, &path)?;
println!("{}", show_diff_preview(&old_node, &processed_node, "rewrite", &path));
if let Some(t) = tip_root_edit(path.is_empty()) {
let mut tips = Tips::new();
tips.add_with_priority(TipPriority::High, t);
tips.print();
}
let new_code = apply_operation_at_path(&code_entry.code, &path, TreeOperation::Replace, Some(&processed_node))?;
code_entry.code = new_code;
save_definition_tree(&snapshot, snapshot_file, namespace, definition)?;
println!("\n## Result\n\n- status: `applied`");
Ok(())
}
fn handle_replace_leaf(opts: &TreeReplaceLeafCommand, snapshot_file: &str) -> Result<(), String> {
let (namespace, definition) = parse_target(&opts.target)?;
let code_input = read_code_input(&opts.file, &opts.code)?;
let raw = code_input.as_deref().ok_or(ERR_CODE_INPUT_REQUIRED)?;
let replacement_node = decode_mutation_syntax_input(raw, opts.input_format)?;
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 code_entry = file_data
.defs
.get_mut(definition)
.ok_or_else(|| format!("Definition '{definition}' not found"))?;
let matches = find_all_leaf_matches(&code_entry.code, &opts.pattern, opts.regex, &[]);
if matches.is_empty() {
println!("{}", "No matches found.".yellow());
return Ok(());
}
println!("# Tree mutation\n");
println!("- operation: `replace-leaf`");
println!("- target: `{}`", opts.target);
println!("- matches: `{}`", matches.len());
println!("- changed: `true`\n");
println!("## Matched paths\n");
for (i, (path, old_value)) in matches.iter().enumerate().take(20) {
println!("{}. `{}`: `{old_value}`", i + 1, format_path(path));
}
if matches.len() > 20 {
println!("\n_... and {} more._", matches.len() - 20);
}
println!();
let mut new_code = code_entry.code.clone();
let mut replaced_count = 0;
let mut sorted_matches = matches;
sorted_matches.sort_by(|a, b| b.0.cmp(&a.0));
for (path, _) in sorted_matches {
match apply_operation_at_path(&new_code, &path, TreeOperation::Replace, Some(&replacement_node)) {
Ok(updated_code) => {
new_code = updated_code;
replaced_count += 1;
}
Err(e) => {
eprintln!("{} Failed to replace at path {}: {}", "Warning:".yellow(), format_path(&path), e);
}
}
}
code_entry.code = new_code;
save_definition_tree(&snapshot, snapshot_file, namespace, definition)?;
println!("- replaced: `{replaced_count}`\n");
print_preview_block("Replacement", &replacement_node, 0, "green");
Ok(())
}
fn handle_search_replace(opts: &TreeSearchReplaceCommand, snapshot_file: &str) -> Result<(), String> {
let (namespace, definition) = parse_target(&opts.target)?;
let code_input = read_code_input(&opts.file, &opts.code)?;
let raw = code_input.as_deref().ok_or(ERR_CODE_INPUT_REQUIRED)?;
let replacement_node = decode_mutation_syntax_input(raw, opts.input_format)?;
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 code_entry = file_data
.defs
.get_mut(definition)
.ok_or_else(|| format!("Definition '{definition}' not found"))?;
let (search_root_path, search_root) = if let Some(selector) = &opts.selector {
let path = resolve_path_expression(&code_entry.code, selector)?;
let root = navigate_to_path(&code_entry.code, &path)?;
(path, root)
} else {
(vec![], code_entry.code.clone())
};
let matches = find_all_leaf_matches(&search_root, &opts.pattern, opts.regex, &[]);
let compose_path = |rel: &[usize]| -> Vec<usize> {
let mut full = search_root_path.clone();
full.extend_from_slice(rel);
full
};
if matches.is_empty() {
return Err(search_replace_no_match_error(opts, snapshot_file));
}
if matches.len() > 1 {
if let Some(pick_index) = opts.pick {
if pick_index >= matches.len() {
return Err(format!(
"--pick {} is out of range (found {} matches, valid indices: 0-{})",
pick_index,
matches.len(),
matches.len() - 1
));
}
let (path, old_value) = &matches[pick_index];
let full_path = compose_path(path);
let old_node = Cirru::Leaf(old_value.to_string().into());
println!("{}", show_diff_preview(&old_node, &replacement_node, "search-replace", &full_path));
let new_code = apply_operation_at_path(&code_entry.code, &full_path, TreeOperation::Replace, Some(&replacement_node))?;
code_entry.code = new_code;
save_definition_tree(&snapshot, snapshot_file, namespace, definition)?;
println!("{} Replaced occurrence [{}]", "✓".green(), pick_index);
return Ok(());
}
println!("# Search-replace candidates\n");
println!("- target: `{}`", opts.target);
println!("- pattern: `{}`", opts.pattern);
println!("- matches: `{}`", matches.len());
println!("- changed: `false`");
let replacement_arg = if let Some(c) = &opts.code {
format!("--code '{c}'")
} else if let Some(f) = &opts.file {
format!("--file '{f}'")
} else {
"--code '...'".to_string()
};
for (i, (path, value)) in matches.iter().enumerate().take(20) {
let full_path = compose_path(path);
let path_str = format_path(&full_path);
println!("\n## Candidate {i}\n");
println!("- path: `{path_str}`");
println!("- value: `{value}`");
if !full_path.is_empty() {
let parent_path = &full_path[..full_path.len() - 1];
if let Ok(parent) = navigate_to_path(&code_entry.code, parent_path) {
print_preview_block("Context", &parent, 6, "");
}
}
println!(
"\n- command: `calcit tree search-replace {} --pattern '{}' {} --pick {}`",
opts.target, opts.pattern, replacement_arg, i
);
}
if matches.len() > 20 {
println!(" ... and {} more", matches.len() - 20);
}
println!();
if command_guidance_enabled() {
println!(
"{}",
"Tip: Use --pick <index> to select a candidate, or use 'tree replace-leaf' to replace ALL occurrences.".blue()
);
}
return Err(format!(
"Found {} matches for pattern '{}'. Use --pick <index> to select one (see candidates above).",
matches.len(),
opts.pattern
));
}
let (path, old_value) = &matches[0];
let full_path = compose_path(path);
let old_node = Cirru::Leaf(old_value.to_string().into());
println!("{}", show_diff_preview(&old_node, &replacement_node, "search-replace", &full_path));
let new_code = apply_operation_at_path(&code_entry.code, &full_path, TreeOperation::Replace, Some(&replacement_node))?;
code_entry.code = new_code;
save_definition_tree(&snapshot, snapshot_file, namespace, definition)?;
println!("{} Replaced unique occurrence", "✓".green());
Ok(())
}
fn search_replace_no_match_error(opts: &TreeSearchReplaceCommand, snapshot_file: &str) -> String {
let parses_as_expression = if opts.regex {
false
} else {
cirru_parser::parse(&opts.pattern)
.map(|nodes| {
nodes.len() != 1
|| matches!(nodes.first(), Some(Cirru::List(items)) if !(items.len() == 1 && matches!(items.first(), Some(Cirru::Leaf(_)))))
})
.unwrap_or(false)
};
if !parses_as_expression {
return format!(
"[E_TREE_SEARCH_REPLACE_LEAF_NOT_FOUND] No leaf nodes matched target pattern {:?}; search-replace searches leaf nodes only. No changes were written.",
opts.pattern
);
}
let snapshot_arg = if snapshot_file == "calcit.cirru" {
String::new()
} else {
format!(" {}", shell_quote(snapshot_file))
};
let replacement_arg = match (&opts.code, &opts.file) {
(Some(code), _) => format!("--code {}", shell_quote(code)),
(_, Some(file)) => format!("--file {}", shell_quote(file)),
_ => "--code 'quote $ <replacement-expression>'".to_string(),
};
format!(
"[E_TREE_SEARCH_REPLACE_EXPRESSION_PATTERN] search-replace matches one leaf, but --pattern parses as a Cirru expression. No changes were written.\n\
Recovery: calcit{snapshot_arg} query search-expr {} --filter {} --set-cursor 0\n\
Then replace the selected expression with: calcit{snapshot_arg} cursor apply replace {replacement_arg}\n\
Or use tree replace with the returned path and an --expect guard.",
shell_quote(&opts.pattern),
shell_quote(&opts.target)
)
}
fn find_all_leaf_matches(node: &Cirru, pattern: &str, regex: bool, current_path: &[usize]) -> Vec<(Vec<usize>, String)> {
let mut results = Vec::new();
let regex_pattern = if regex {
match regex::Regex::new(pattern) {
Ok(r) => Some(r),
Err(e) => {
eprintln!("{} Invalid regex '{}': {}", "Error:".red().bold(), pattern, e);
return results;
}
}
} else {
None
};
match node {
Cirru::Leaf(s) => {
let matched = if regex {
regex_pattern.as_ref().is_some_and(|r| r.is_match(s))
} else {
s.as_ref() == pattern
};
if matched {
results.push((current_path.to_vec(), s.to_string()));
}
}
Cirru::List(items) => {
for (i, item) in items.iter().enumerate() {
let mut new_path = current_path.to_vec();
new_path.push(i);
results.extend(find_all_leaf_matches(item, pattern, regex, &new_path));
}
}
}
results
}
fn handle_delete(opts: &TreeDeleteCommand, snapshot_file: &str) -> Result<(), String> {
let (namespace, definition) = parse_target(&opts.target)?;
let path = parse_path(&opts.path)?;
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 code_entry = file_data
.defs
.get_mut(definition)
.ok_or_else(|| format!("Definition '{definition}' not found"))?;
let old_node = navigate_to_path(&code_entry.code, &path)?;
verify_expected_node(&old_node, opts.expect.as_deref(), &path)?;
let parent_path: Vec<usize> = if path.is_empty() { vec![] } else { path[..path.len() - 1].to_vec() };
if let Some(t) = tip_root_edit(path.is_empty()) {
let mut tips = Tips::new();
tips.add_with_priority(TipPriority::High, t);
tips.print();
}
let new_code = apply_operation_at_path(&code_entry.code, &path, TreeOperation::Delete, None)?;
code_entry.code = new_code.clone();
save_definition_tree(&snapshot, snapshot_file, namespace, definition)?;
println!("# Tree mutation\n");
println!("- operation: `delete`");
println!("- target: `{}`", opts.target);
println!("- path: `{}`", format_path(&path));
println!("- changed: `true`\n");
print_preview_block("Deleted node", &old_node, opts.depth, "yellow");
println!();
let new_parent = if parent_path.is_empty() {
new_code
} else {
navigate_to_path(&new_code, &parent_path)?
};
print_preview_block("Parent after deletion", &new_parent, opts.depth, "green");
if !path.is_empty() {
let deleted_index = path[path.len() - 1];
println!(
"{}: Sibling nodes after index {} have shifted down by 1",
"⚠️ Index change".yellow().bold(),
deleted_index
);
println!(
" Example: path {}.{} is now {}.{}",
format_path(&parent_path),
deleted_index + 1,
format_path(&parent_path),
deleted_index
);
println!(
" {}: Re-run {} to get updated paths",
"Tip".blue().bold(),
"calcit query search".cyan()
);
}
Ok(())
}
fn insert_operation(at: &str) -> Result<TreeOperation, String> {
match at {
"before" => Ok(TreeOperation::InsertBefore),
"after" => Ok(TreeOperation::InsertAfter),
"prepend-child" => Ok(TreeOperation::InsertChild),
"append-child" => Ok(TreeOperation::AppendChild),
other => Err(format!(
"Unsupported `tree insert --at {other}`. Use: before, after, prepend-child, append-child."
)),
}
}
fn swap_operation(with: &str) -> Result<TreeOperation, String> {
match with {
"next" => Ok(TreeOperation::SwapNextSibling),
"prev" => Ok(TreeOperation::SwapPrevSibling),
other => Err(format!("Unsupported `tree swap --with {other}`. Use: next, prev.")),
}
}
fn handle_insert(opts: &TreeInsertCommand, snapshot_file: &str) -> Result<(), String> {
let operation = insert_operation(&opts.at)?;
generic_insert_handler(&opts.target, &opts.path, operation, opts, snapshot_file, opts.depth)
}
trait InsertOperation {
fn file(&self) -> &Option<String>;
fn code(&self) -> &Option<String>;
fn input_format(&self) -> SyntaxInputFormat;
fn expect(&self) -> Option<&str>;
fn with(&self) -> &[String] {
&[]
}
}
impl InsertOperation for TreeInsertCommand {
fn file(&self) -> &Option<String> {
&self.file
}
fn code(&self) -> &Option<String> {
&self.code
}
fn input_format(&self) -> SyntaxInputFormat {
self.input_format
}
fn expect(&self) -> Option<&str> {
self.expect.as_deref()
}
}
impl InsertOperation for TreeSearchReplaceCommand {
fn file(&self) -> &Option<String> {
&self.file
}
fn code(&self) -> &Option<String> {
&self.code
}
fn input_format(&self) -> SyntaxInputFormat {
self.input_format
}
fn expect(&self) -> Option<&str> {
None
}
}
impl InsertOperation for TreeStructuralCommand {
fn file(&self) -> &Option<String> {
&self.file
}
fn code(&self) -> &Option<String> {
&self.code
}
fn input_format(&self) -> SyntaxInputFormat {
self.input_format
}
fn expect(&self) -> Option<&str> {
None
}
fn with(&self) -> &[String] {
&self.with
}
}
fn generic_insert_handler<T: InsertOperation>(
target: &str,
path_str: &str,
operation: TreeOperation,
opts: &T,
snapshot_file: &str,
depth: usize,
) -> Result<(), String> {
let (namespace, definition) = parse_target(target)?;
let path = parse_path(path_str)?;
let code_input = read_code_input(opts.file(), opts.code())?;
let raw = code_input.as_deref().ok_or(ERR_CODE_INPUT_REQUIRED)?;
let new_node = decode_mutation_syntax_input(raw, opts.input_format())?;
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 code_entry = file_data
.defs
.get_mut(definition)
.ok_or_else(|| format!("Definition '{definition}' not found"))?;
let processed_node = if opts.with().is_empty() {
new_node
} else {
let original_node = navigate_to_path(&code_entry.code, &path)?;
let references = parse_with_references(opts.with(), &original_node)?;
process_node_with_references(&new_node, &references)?
};
let anchor_node = navigate_to_path(&code_entry.code, &path)?;
verify_expected_node(&anchor_node, opts.expect(), &path)?;
let parent_path: Vec<usize> = if path.is_empty() { vec![] } else { path[..path.len() - 1].to_vec() };
let context_path = match operation {
TreeOperation::InsertChild | TreeOperation::AppendChild => &path,
TreeOperation::InsertBefore | TreeOperation::InsertAfter => &parent_path,
_ => unreachable!("generic_insert_handler only accepts insert operations"),
};
if let Some(t) = tip_root_edit(path.is_empty()) {
let mut tips = Tips::new();
tips.add_with_priority(TipPriority::High, t);
tips.print();
}
let new_code = apply_operation_at_path(&code_entry.code, &path, operation, Some(&processed_node))?;
code_entry.code = new_code.clone();
save_definition_tree(&snapshot, snapshot_file, namespace, definition)?;
println!("# Tree mutation\n");
println!("- operation: `{}`", operation.as_str());
println!("- target: `{target}`");
println!("- path: `{}`", format_path(&path));
println!("- changed: `true`\n");
print_preview_block("Inserted node", &processed_node, depth, "cyan");
println!();
let new_parent = if context_path.is_empty() {
new_code
} else {
navigate_to_path(&new_code, context_path)?
};
print_preview_block("Containing node after", &new_parent, depth, "green");
match operation {
TreeOperation::InsertBefore => {
if !path.is_empty() {
let insert_index = path[path.len() - 1];
println!(
"{}: Node inserted at index {}, original node and siblings shifted up by 1",
"Index impact".yellow().bold(),
insert_index
);
println!(
" Old path {}.{} → New path {}.{}",
format_path(&parent_path),
insert_index,
format_path(&parent_path),
insert_index + 1
);
}
}
TreeOperation::InsertAfter => {
if !path.is_empty() {
let ref_index = path[path.len() - 1];
println!(
"{}: Node inserted at index {}, nodes after reference shifted up by 1",
"Index impact".yellow().bold(),
ref_index + 1
);
}
}
TreeOperation::InsertChild => {
println!(
"{}: Node inserted as first child (index 0), all existing children shifted up by 1",
"Index impact".yellow().bold()
);
println!(" Old child [0] → New child [1], [1] → [2], etc.");
}
TreeOperation::AppendChild => {
println!(
"{}: Node appended as last child, no index changes to existing nodes",
"Index impact".green().bold()
);
println!(" {}: Use this for multiple insertions to keep paths stable", "Tip".blue().bold());
}
_ => unreachable!("generic_insert_handler only accepts insert operations"),
}
Ok(())
}
fn handle_swap(opts: &TreeSwapCommand, snapshot_file: &str) -> Result<(), String> {
let operation = swap_operation(&opts.with)?;
generic_swap_handler(&opts.target, &opts.path, operation, snapshot_file, opts.depth)
}
fn generic_swap_handler(
target: &str,
path_str: &str,
operation: TreeOperation,
snapshot_file: &str,
_depth: usize,
) -> Result<(), String> {
let (namespace, definition) = parse_target(target)?;
let path = parse_path(path_str)?;
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 code_entry = file_data
.defs
.get_mut(definition)
.ok_or_else(|| format!("Definition '{definition}' not found"))?;
let parent_path: Vec<usize> = if path.is_empty() { vec![] } else { path[..path.len() - 1].to_vec() };
let old_parent = if parent_path.is_empty() {
code_entry.code.clone()
} else {
navigate_to_path(&code_entry.code, &parent_path)?
};
let new_code = apply_operation_at_path(&code_entry.code, &path, operation, None)?;
code_entry.code = new_code.clone();
save_definition_tree(&snapshot, snapshot_file, namespace, definition)?;
println!("# Tree mutation\n");
println!("- operation: `{}`", operation.as_str());
println!("- target: `{target}`");
println!("- path: `{}`", format_path(&path));
println!("- changed: `true`\n");
if !path.is_empty() {
let current_index = path[path.len() - 1];
let parent_display = if parent_path.is_empty() {
"root".to_string()
} else {
format!("@{}", parent_path.iter().map(|i| i.to_string()).collect::<Vec<_>>().join("."))
};
match operation {
TreeOperation::SwapNextSibling => {
println!(
"{}: Swapped child [{}] with [{}] under parent {}",
"Index change".yellow().bold(),
current_index,
current_index + 1,
parent_display
);
}
TreeOperation::SwapPrevSibling => {
println!(
"{}: Swapped child [{}] with [{}] under parent {}",
"Index change".yellow().bold(),
current_index,
current_index - 1,
parent_display
);
}
_ => unreachable!("generic_swap_handler only accepts swap operations"),
}
println!();
}
print_preview_block("Parent before swap", &old_parent, 15, "yellow");
println!();
if let Some(t) = tip_root_edit(path.is_empty()) {
let mut tips = Tips::new();
tips.add_with_priority(TipPriority::High, t);
tips.print();
}
let new_parent = if parent_path.is_empty() {
new_code
} else {
navigate_to_path(&new_code, &parent_path)?
};
print_preview_block("Parent after swap", &new_parent, 15, "green");
Ok(())
}
fn splice_at_path(code: &Cirru, path: &[usize]) -> Result<Cirru, String> {
if path.is_empty() {
return Err("Cannot unwrap root node (no parent to splice into)".to_string());
}
splice_recursive(code, path, 0)
}
fn splice_recursive(code: &Cirru, path: &[usize], depth: usize) -> 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 splice_children = match &items[idx] {
Cirru::List(children) => children.clone(),
Cirru::Leaf(_) => return Err("Node at path is a leaf; cannot unwrap".to_string()),
};
let mut new_items: Vec<Cirru> = Vec::with_capacity(items.len() - 1 + splice_children.len());
new_items.extend_from_slice(&items[..idx]);
new_items.extend(splice_children);
new_items.extend_from_slice(&items[idx + 1..]);
Ok(Cirru::List(new_items))
} else {
let mut new_items = items.clone();
new_items[idx] = splice_recursive(&items[idx], path, depth + 1)?;
Ok(Cirru::List(new_items))
}
}
}
}
fn handle_unwrap(opts: &TreeUnwrapCommand, snapshot_file: &str) -> Result<(), String> {
let (namespace, definition) = parse_target(&opts.target)?;
let path = parse_path(&opts.path)?;
if path.is_empty() {
return Err("Cannot unwrap root node (no parent to splice into)".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 code_entry = file_data
.defs
.get_mut(definition)
.ok_or_else(|| format!("Definition '{definition}' not found"))?;
let node = navigate_to_path(&code_entry.code, &path)?;
let children = match &node {
Cirru::List(children) => children.clone(),
_ => return Err(format!("Node at path [{}] is a leaf; cannot unwrap", opts.path)),
};
if children.is_empty() {
return Err(format!("Node at path [{}] has no children to splice", opts.path));
}
let new_code = splice_at_path(&code_entry.code, &path)?;
let parent_path = &path[..path.len() - 1];
let parent_after = if parent_path.is_empty() {
new_code.clone()
} else {
navigate_to_path(&new_code, parent_path)?
};
code_entry.code = new_code;
save_definition_tree(&snapshot, snapshot_file, namespace, definition)?;
println!("# Tree mutation\n");
println!("- operation: `unwrap`");
println!("- target: `{}`", opts.target);
println!("- path: `{}`", format_path(&path));
println!("- changed: `true`");
println!("- spliced children: `{}`\n", children.len());
print_preview_block("Before", &node, opts.depth, "yellow");
println!();
print_preview_block("Parent after", &parent_after, opts.depth, "green");
Ok(())
}
fn handle_raise(opts: &TreeRaiseCommand, snapshot_file: &str) -> Result<(), String> {
let (namespace, definition) = parse_target(&opts.target)?;
let path = parse_path(&opts.path)?;
if path.is_empty() {
return Err("Cannot raise root node (no parent to replace). Path must have at least one element.".to_string());
}
let parent_path = &path[..path.len() - 1];
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 code_entry = file_data
.defs
.get_mut(definition)
.ok_or_else(|| format!("Definition '{definition}' not found"))?;
let child_node = navigate_to_path(&code_entry.code, &path)?;
let parent_node = navigate_to_path(&code_entry.code, parent_path)?;
let new_code = apply_operation_at_path(&code_entry.code, parent_path, TreeOperation::Replace, Some(&child_node))?;
code_entry.code = new_code;
save_definition_tree(&snapshot, snapshot_file, namespace, definition)?;
println!("# Tree mutation\n");
println!("- operation: `raise`");
println!("- target: `{}`", opts.target);
println!("- path: `{}`", format_path(&path));
println!("- changed: `true`\n");
print_preview_block("Before (parent)", &parent_node, opts.depth, "yellow");
println!();
print_preview_block("After (raised child)", &child_node, opts.depth, "green");
Ok(())
}
fn handle_wrap(opts: &TreeWrapCommand, snapshot_file: &str) -> Result<(), String> {
let (namespace, definition) = parse_target(&opts.target)?;
let path = parse_path(&opts.path)?;
let raw = read_code_input(&opts.file, &opts.code)?.ok_or(ERR_CODE_INPUT_REQUIRED)?;
let template = decode_mutation_syntax_input(&raw, opts.input_format)?;
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 code_entry = file_data
.defs
.get_mut(definition)
.ok_or_else(|| format!("Definition '{definition}' not found"))?;
let original_node = navigate_to_path(&code_entry.code, &path)?;
let mut references = std::collections::BTreeMap::new();
references.insert("self".to_string(), original_node.clone());
let new_node = process_node_with_references(&template, &references)?;
let new_code = apply_operation_at_path(&code_entry.code, &path, TreeOperation::Replace, Some(&new_node))?;
code_entry.code = new_code;
save_definition_tree(&snapshot, snapshot_file, namespace, definition)?;
println!("# Tree mutation\n");
println!("- operation: `wrap`");
println!("- target: `{}`", opts.target);
println!("- path: `{}`", format_path(&path));
println!("- changed: `true`\n");
print_preview_block("Before", &original_node, opts.depth, "yellow");
println!();
print_preview_block("After", &new_node, opts.depth, "green");
Ok(())
}
#[cfg(test)]
mod tests {
use super::{find_all_leaf_matches, search_replace_no_match_error, verify_expected_node};
use crate::cli_args::{SyntaxInputFormat, TreeSearchReplaceCommand};
use cirru_parser::Cirru;
fn leaf(text: &str) -> Cirru {
Cirru::Leaf(text.into())
}
fn list(items: Vec<Cirru>) -> Cirru {
Cirru::List(items)
}
fn search_replace(pattern: &str, regex: bool) -> TreeSearchReplaceCommand {
TreeSearchReplaceCommand {
target: "app.main/demo".to_string(),
pattern: pattern.to_string(),
regex,
file: None,
code: Some("quote replacement".to_string()),
input_format: SyntaxInputFormat::Auto,
depth: 2,
pick: None,
selector: None,
}
}
#[test]
fn expression_pattern_error_provides_structural_recovery_without_mutation_claims() {
let error = search_replace_no_match_error(&search_replace("js/document.querySelector |.app", false), "fixture.cirru");
assert!(error.contains("E_TREE_SEARCH_REPLACE_EXPRESSION_PATTERN"));
assert!(error.contains("searches one leaf") || error.contains("matches one leaf"));
assert!(error.contains("calcit 'fixture.cirru' query search-expr 'js/document.querySelector |.app'"));
assert!(error.contains("--filter 'app.main/demo' --set-cursor 0"));
assert!(error.contains("cursor apply replace --code 'quote replacement'"));
assert!(error.contains("No changes were written"));
}
#[test]
fn absent_leaf_error_names_the_leaf_only_search_scope() {
let error = search_replace_no_match_error(&search_replace("missing-leaf", false), "calcit.cirru");
assert!(error.contains("E_TREE_SEARCH_REPLACE_LEAF_NOT_FOUND"));
assert!(error.contains("search-replace searches leaf nodes only"));
assert!(error.contains("No changes were written"));
}
#[test]
fn regex_leaf_search_stays_on_the_leaf_matching_path() {
let tree = list(vec![leaf("alpha-1"), list(vec![leaf("beta"), leaf("alpha-2")])]);
let matches = find_all_leaf_matches(&tree, r"^alpha-\d$", true, &[]);
assert_eq!(matches.len(), 2);
assert_eq!(matches[0].0, vec![0]);
assert_eq!(matches[1].0, vec![1, 1]);
assert_eq!(matches[0].1, "alpha-1");
assert_eq!(matches[1].1, "alpha-2");
}
#[test]
fn expected_node_guard_accepts_exact_expression() {
let actual = list(vec![leaf("test-methods")]);
verify_expected_node(&actual, Some("quote (test-methods)"), &[4]).expect("matching guard should pass");
}
#[test]
fn expected_node_guard_rejects_wrong_path_content() {
let actual = list(vec![leaf("test-lisp-style")]);
let error = verify_expected_node(&actual, Some("quote (test-methods)"), &[8]).expect_err("mismatched guard should fail");
assert!(error.contains("# Error: node guard failed"), "error: {error}");
assert!(error.contains("- path: `@8`"), "error: {error}");
assert!(
error.contains("## Expected\n\n- node kind: `expression`\n\n```cirru"),
"error: {error}"
);
assert!(
error.contains("## Actual\n\n- node kind: `expression`\n\n```cirru"),
"error: {error}"
);
assert!(error.contains("No changes were written"), "error: {error}");
}
}