1use lsp_types::{Location, Position};
2use serde_json::Value;
3
4use crate::lsp::client::uri_to_file_path;
5
6pub fn handle(args: &Value, project_root: &str, abs_path: &str) -> String {
7 let action = args
8 .get("action")
9 .and_then(Value::as_str)
10 .unwrap_or("references");
11
12 if matches!(
13 action,
14 "replace_symbol_body" | "insert_before_symbol" | "insert_after_symbol"
15 ) {
16 return handle_symbol_edit(action, args, project_root);
17 }
18
19 if matches!(action, "rename_preview" | "rename_apply") {
20 return handle_rename_refactor(action, args, project_root);
21 }
22
23 if matches!(action, "safe_delete_preview" | "safe_delete_apply") {
24 return handle_safe_delete_refactor(action, args, project_root);
25 }
26
27 if matches!(action, "move_preview" | "move_apply") {
28 return handle_move_refactor(action, args, project_root);
29 }
30
31 if matches!(action, "inline_preview" | "inline_apply") {
32 return handle_inline_refactor(action, args, project_root);
33 }
34
35 if action == "reformat" {
36 return handle_reformat_refactor(args, project_root);
37 }
38
39 let line = args.get("line").and_then(Value::as_u64).unwrap_or(1) as u32;
40 let column = args.get("column").and_then(Value::as_u64).unwrap_or(0) as u32;
41 let scope = args
42 .get("scope")
43 .and_then(Value::as_str)
44 .unwrap_or("project");
45
46 let uri = match crate::lsp::router::open_file(abs_path, project_root) {
47 Ok(u) => u,
48 Err(e) => return format!("ERROR: {e}"),
49 };
50
51 let position = Position::new(line.saturating_sub(1), column);
52
53 if action == "rename"
56 && let Some(e) = deny_if_read_only(abs_path)
57 {
58 return e;
59 }
60
61 match action {
62 "rename" => handle_rename(args, abs_path, project_root, &uri, position),
63 "references" => handle_references(abs_path, project_root, &uri, position, scope),
64 "definition" => handle_definition(abs_path, project_root, &uri, position),
65 "implementations" => handle_implementations(abs_path, project_root, &uri, position, scope),
66 "declaration" => handle_declaration(abs_path, project_root, &uri, position),
67 "type_hierarchy" => handle_type_hierarchy(args, abs_path, project_root, &uri, position),
68 "symbols_overview" => handle_symbols_overview(abs_path, project_root, &uri),
69 "inspections" => handle_inspections(args, abs_path, project_root, &uri),
70 _ => format!(
71 "ERROR: Unknown action '{action}'. Available: rename, references, definition, \
72 implementations, declaration, type_hierarchy, symbols_overview, inspections, \
73 replace_symbol_body, insert_before_symbol, insert_after_symbol, \
74 rename_preview, rename_apply, safe_delete_preview, safe_delete_apply, \
75 move_preview, move_apply, inline_preview, inline_apply, reformat."
76 ),
77 }
78}
79
80fn deny_if_read_only(abs_path: &str) -> Option<String> {
86 crate::core::pathjail::enforce_writable(std::path::Path::new(abs_path))
87 .err()
88 .map(|e| format!("ERROR: {e}"))
89}
90
91fn handle_rename(
92 args: &Value,
93 file_path: &str,
94 project_root: &str,
95 uri: &lsp_types::Uri,
96 position: Position,
97) -> String {
98 let Some(new_name) = args.get("new_name").and_then(Value::as_str) else {
99 return "ERROR: 'new_name' parameter is required for rename.".to_string();
100 };
101
102 let result = crate::lsp::router::with_backend(file_path, project_root, |backend, _| {
103 backend.rename(uri, position, new_name)
104 });
105
106 match result {
107 Ok(Some(edit)) => format_workspace_edit(&edit, project_root),
108 Ok(None) => "No rename edits returned by language server.".to_string(),
109 Err(e) => format!("ERROR: {e}"),
110 }
111}
112
113fn handle_references(
114 file_path: &str,
115 project_root: &str,
116 uri: &lsp_types::Uri,
117 position: Position,
118 scope: &str,
119) -> String {
120 let result = crate::lsp::router::with_backend(file_path, project_root, |backend, _| {
121 let locs = backend.references(uri, position, scope)?;
122 Ok((locs, backend.last_truncation()))
123 });
124
125 match result {
126 Ok((locations, meta)) => {
127 let mut out = format_locations(&locations, project_root);
128 out.push_str(&truncation_note(locations.len(), meta));
129 out
130 }
131 Err(e) => format!("ERROR: {e}"),
132 }
133}
134
135fn handle_definition(
136 file_path: &str,
137 project_root: &str,
138 uri: &lsp_types::Uri,
139 position: Position,
140) -> String {
141 let result = crate::lsp::router::with_backend(file_path, project_root, |backend, _| {
142 backend.definition(uri, position)
143 });
144
145 match result {
146 Ok(resp) => {
147 let locations = match resp {
148 lsp_types::GotoDefinitionResponse::Scalar(loc) => vec![loc],
149 lsp_types::GotoDefinitionResponse::Array(locs) => locs,
150 lsp_types::GotoDefinitionResponse::Link(links) => links
151 .into_iter()
152 .map(|l| Location {
153 uri: l.target_uri,
154 range: l.target_selection_range,
155 })
156 .collect(),
157 };
158 format_locations(&locations, project_root)
159 }
160 Err(e) => format!("ERROR: {e}"),
161 }
162}
163
164fn handle_implementations(
165 file_path: &str,
166 project_root: &str,
167 uri: &lsp_types::Uri,
168 position: Position,
169 scope: &str,
170) -> String {
171 let result = crate::lsp::router::with_backend(file_path, project_root, |backend, _| {
172 let locs = backend.implementations(uri, position, scope)?;
173 Ok((locs, backend.last_truncation()))
174 });
175
176 match result {
177 Ok((locations, meta)) => {
178 let mut out = format_locations(&locations, project_root);
179 out.push_str(&truncation_note(locations.len(), meta));
180 out
181 }
182 Err(e) => format!("ERROR: {e}"),
183 }
184}
185
186fn handle_declaration(
187 file_path: &str,
188 project_root: &str,
189 uri: &lsp_types::Uri,
190 position: Position,
191) -> String {
192 let result = crate::lsp::router::with_backend(file_path, project_root, |backend, _| {
193 backend.declaration(uri, position)
194 });
195
196 match result {
197 Ok(locations) => format_locations(&locations, project_root),
198 Err(e) => format!("ERROR: {e}"),
199 }
200}
201
202use crate::lsp::backend::{
203 HierarchyDirection, InspectionDiag, InspectionInfo, SymbolOverviewItem, TypeHierarchyNode,
204};
205
206#[derive(Debug)]
208pub(crate) struct Resolved {
209 pub rel_path: String,
210 pub start_line: usize,
211 pub end_line: usize,
212}
213
214pub(crate) fn apply_symbol_edit(
218 action: &str,
219 project_root: &str,
220 edit: &crate::lsp::backend::RangeEdit,
221) -> Result<crate::lsp::backend::EditResult, String> {
222 use crate::lsp::backend::LspBackend;
223 use crate::lsp::port_discovery;
224
225 let mut backend: Box<dyn LspBackend> =
226 if let Some(pf) = port_discovery::read_port_file(project_root) {
227 if port_discovery::pid_alive(pf.pid) && port_discovery::health_ok(&pf) {
228 Box::new(crate::lsp::jetbrains_backend::JetBrainsHttpBackend::new(
229 pf.port,
230 pf.token,
231 project_root.to_string(),
232 pf.pid,
233 ))
234 } else {
235 Box::new(crate::lsp::edit_apply::HeadlessBackend)
236 }
237 } else {
238 Box::new(crate::lsp::edit_apply::HeadlessBackend)
239 };
240
241 match action {
242 "replace_symbol_body" => backend.replace_symbol_body(edit),
243 "insert_before_symbol" => backend.insert_before_symbol(edit),
244 "insert_after_symbol" => backend.insert_after_symbol(edit),
245 other => Err(format!("INTERNAL: not an edit action: {other}")),
246 }
247}
248
249pub(crate) fn anchor_indent(content: &str, line: usize) -> String {
251 content
252 .lines()
253 .nth(line.saturating_sub(1))
254 .map(|l| l.chars().take_while(|c| *c == ' ' || *c == '\t').collect())
255 .unwrap_or_default()
256}
257
258pub(crate) fn reindent_first_line(text: &str, indent: &str) -> String {
262 if text.starts_with(' ') || text.starts_with('\t') || indent.is_empty() {
263 return text.to_string();
264 }
265 format!("{indent}{text}")
266}
267
268fn container_matches_ancestor(name: &str, ancestor: &str) -> bool {
275 if name == ancestor {
276 return true;
277 }
278 match name.rsplit_once(" for ") {
279 Some((_, target)) => target.split('<').next().unwrap_or(target).trim() == ancestor,
280 None => false,
281 }
282}
283
284pub(crate) fn resolve_name_path(name_path: &str, project_root: &str) -> Result<Resolved, String> {
288 use crate::core::graph_provider;
289 let open = graph_provider::open_or_build(project_root)
290 .ok_or_else(|| "NO_SYMBOL: no symbol index available".to_string())?;
291 let gp = &open.provider;
292
293 let segments: Vec<&str> = name_path.split('/').filter(|s| !s.is_empty()).collect();
294 let leaf = *segments
295 .last()
296 .ok_or_else(|| "NO_SYMBOL: empty name_path".to_string())?;
297
298 let mut leaves: Vec<_> = gp
300 .find_symbols(leaf, None, None)
301 .into_iter()
302 .filter(|s| s.name == leaf)
303 .collect();
304
305 if segments.len() >= 2 {
306 let ancestor = segments[segments.len() - 2];
307 let parents: Vec<_> = gp
308 .find_symbols(ancestor, None, None)
309 .into_iter()
310 .filter(|s| container_matches_ancestor(&s.name, ancestor))
311 .collect();
312 leaves.retain(|leaf_sym| {
313 parents.iter().any(|p| {
314 p.file == leaf_sym.file
315 && p.start_line <= leaf_sym.start_line
316 && leaf_sym.end_line <= p.end_line
317 })
318 });
319 }
320
321 match leaves.len() {
322 0 => Err(format!(
323 "NO_SYMBOL: '{name_path}' did not resolve to any indexed symbol"
324 )),
325 1 => Ok(Resolved {
326 rel_path: leaves[0].file.clone(),
327 start_line: leaves[0].start_line,
328 end_line: leaves[0].end_line,
329 }),
330 _ => {
331 let mut msg = format!(
332 "AMBIGUOUS_SYMBOL: '{name_path}' matches {} symbols; qualify it:\n",
333 leaves.len()
334 );
335 for s in leaves.iter().take(10) {
336 msg.push_str(&format!(
337 " {}:{} (L{}-{})\n",
338 s.file, s.name, s.start_line, s.end_line
339 ));
340 }
341 Err(msg)
342 }
343 }
344}
345
346pub(crate) fn usage_range_text(
350 project_root: &str,
351 u: &crate::lsp::backend::UsageSite,
352) -> Result<String, String> {
353 let abs = crate::core::path_resolve::resolve_tool_path(Some(project_root), None, &u.path)
354 .map_err(|e| format!("CONFLICT: usage path blocked by jail: {e}"))?;
355 let content =
356 std::fs::read_to_string(&abs).map_err(|e| format!("FILE_NOT_FOUND: {abs}: {e}"))?;
357 let s = crate::lsp::edit_apply::offset_of(&content, u.range.start_line, u.range.start_char)?;
358 let e = crate::lsp::edit_apply::offset_of(&content, u.range.end_line, u.range.end_char)?;
359 if e < s {
360 return Err("POSITION_OUT_OF_RANGE: end before start".to_string());
361 }
362 Ok(content[s..e].to_string())
363}
364
365pub(crate) fn plan_hash(
370 project_root: &str,
371 usages: &[crate::lsp::backend::UsageSite],
372) -> Result<String, String> {
373 use crate::lsp::backend::TextRange0Based;
374 let mut rows: Vec<(String, TextRange0Based, String)> = Vec::with_capacity(usages.len());
375 for u in usages {
376 let text = usage_range_text(project_root, u)?;
377 rows.push((u.path.clone(), u.range, text));
378 }
379 rows.sort_by(|a, b| {
380 a.0.cmp(&b.0)
381 .then(a.1.start_line.cmp(&b.1.start_line))
382 .then(a.1.start_char.cmp(&b.1.start_char))
383 .then(a.1.end_line.cmp(&b.1.end_line))
384 .then(a.1.end_char.cmp(&b.1.end_char))
385 });
386 let mut canon = String::new();
387 for (path, r, text) in &rows {
388 canon.push_str(&format!(
389 "{path}|{}:{}-{}:{}|{text}\n",
390 r.start_line, r.start_char, r.end_line, r.end_char
391 ));
392 }
393 Ok(crate::core::hasher::hash_hex(canon.as_bytes()))
394}
395
396mod ops;
397#[allow(clippy::wildcard_imports)]
398use ops::*;
399
400fn parse_direction(args: &Value) -> HierarchyDirection {
401 match args.get("direction").and_then(Value::as_str) {
402 Some("subtypes") => HierarchyDirection::Subtypes,
403 _ => HierarchyDirection::Supertypes,
404 }
405}
406
407fn handle_type_hierarchy(
408 args: &Value,
409 file_path: &str,
410 project_root: &str,
411 uri: &lsp_types::Uri,
412 position: Position,
413) -> String {
414 let direction = parse_direction(args);
415 let result = crate::lsp::router::with_backend(file_path, project_root, |backend, _| {
416 let tree = backend.type_hierarchy(uri, position, direction)?;
417 Ok((tree, backend.last_truncation()))
418 });
419 match result {
420 Ok((tree, meta)) => {
421 let mut out = format_type_hierarchy(&tree);
422 if matches!(meta, Some(m) if m.truncated) {
423 out.push_str("\n(truncated — depth/node cap reached)\n");
424 }
425 out
426 }
427 Err(e) => format!("ERROR: {e}"),
428 }
429}
430
431fn handle_symbols_overview(file_path: &str, project_root: &str, uri: &lsp_types::Uri) -> String {
432 let result = crate::lsp::router::with_backend(file_path, project_root, |backend, _| {
433 let items = backend.symbols_overview(uri)?;
434 Ok((items, backend.last_truncation()))
435 });
436 match result {
437 Ok((items, meta)) => {
438 let mut out = format_symbols_overview(&items);
439 out.push_str(&truncation_note(items.len(), meta));
440 out
441 }
442 Err(e) => format!("ERROR: {e}"),
443 }
444}
445
446fn handle_symbol_edit(action: &str, args: &Value, project_root: &str) -> String {
447 let explicit_path = args.get("path").and_then(Value::as_str);
448
449 let (rel_path, start_line, end_line) = if let Some(np) =
450 args.get("name_path").and_then(Value::as_str)
451 {
452 match resolve_name_path(np, project_root) {
453 Ok(r) => {
454 if let Some(caller_path) = explicit_path {
460 let resolved_abs = match crate::core::path_resolve::resolve_tool_path(
461 Some(project_root),
462 None,
463 &r.rel_path,
464 ) {
465 Ok(p) => p,
466 Err(e) => return format!("ERROR: path blocked by jail: {e}"),
467 };
468 let caller_abs = match crate::core::path_resolve::resolve_tool_path(
469 Some(project_root),
470 None,
471 caller_path,
472 ) {
473 Ok(p) => p,
474 Err(e) => return format!("ERROR: path blocked by jail: {e}"),
475 };
476 let resolved_real = std::fs::canonicalize(&resolved_abs)
477 .unwrap_or_else(|_| std::path::PathBuf::from(&resolved_abs));
478 let caller_real = std::fs::canonicalize(&caller_abs)
479 .unwrap_or_else(|_| std::path::PathBuf::from(&caller_abs));
480 if resolved_real != caller_real {
481 return format!(
482 "ERROR: WORKTREE_MISMATCH: symbol '{np}' resolved to '{resolved_abs}' \
483 but caller specified '{caller_abs}'. The symbol index points to a \
484 different checkout (likely a git worktree mismatch). \
485 Use op=replace_lines with explicit line range instead, \
486 or re-index from the correct root.",
487 );
488 }
489 (caller_path.to_string(), r.start_line, r.end_line)
490 } else {
491 (r.rel_path, r.start_line, r.end_line)
492 }
493 }
494 Err(e) => return format!("ERROR: {e}"),
495 }
496 } else {
497 let Some(path) = explicit_path else {
498 return "ERROR: provide 'name_path' or 'path'+'line' for symbol edits.".to_string();
499 };
500 let line = args.get("line").and_then(Value::as_u64).unwrap_or(0) as usize;
501 let end = args
502 .get("end_line")
503 .and_then(Value::as_u64)
504 .unwrap_or(line as u64) as usize;
505 if line == 0 {
506 return "ERROR: 'line' is required (1-based) when using the path fallback.".to_string();
507 }
508 (path.to_string(), line, end)
509 };
510
511 let abs_path =
513 match crate::core::path_resolve::resolve_tool_path(Some(project_root), None, &rel_path) {
514 Ok(p) => p,
515 Err(e) => return format!("ERROR: path blocked by jail: {e}"),
516 };
517 if let Some(e) = deny_if_read_only(&abs_path) {
519 return e;
520 }
521
522 let content = match std::fs::read_to_string(&abs_path) {
523 Ok(c) => c,
524 Err(e) => return format!("ERROR: FILE_NOT_FOUND: {abs_path}: {e}"),
525 };
526
527 let expected_hash = args
529 .get("expected_hash")
530 .and_then(Value::as_str)
531 .map(String::from);
532 let (range, text) = match action {
533 "replace_symbol_body" => {
534 let Some(new_body) = args.get("new_body").and_then(Value::as_str) else {
535 return "ERROR: 'new_body' is required for replace_symbol_body.".to_string();
536 };
537 let end_col = content
538 .lines()
539 .nth(end_line.saturating_sub(1))
540 .map_or(0, str::len) as u32;
541 (
542 crate::lsp::backend::TextRange0Based {
543 start_line: (start_line - 1) as u32,
544 start_char: 0,
545 end_line: (end_line - 1) as u32,
546 end_char: end_col,
547 },
548 new_body.to_string(),
549 )
550 }
551 "insert_before_symbol" | "insert_after_symbol" => {
552 let Some(t) = args.get("text").and_then(Value::as_str) else {
553 return format!("ERROR: 'text' is required for {action}.");
554 };
555 let indent = anchor_indent(&content, start_line);
556 let final_text = format!("{}\n", reindent_first_line(t, &indent));
557 let insert_line = if action == "insert_before_symbol" {
558 (start_line - 1) as u32
559 } else {
560 end_line as u32
561 };
562 (
563 crate::lsp::backend::TextRange0Based {
564 start_line: insert_line,
565 start_char: 0,
566 end_line: insert_line,
567 end_char: 0,
568 },
569 final_text,
570 )
571 }
572 other => return format!("ERROR: INTERNAL: not an edit action: {other}"),
573 };
574
575 if let Some(exp) = &expected_hash {
580 let s =
581 match crate::lsp::edit_apply::offset_of(&content, range.start_line, range.start_char) {
582 Ok(o) => o,
583 Err(e) => return format!("ERROR: {e}"),
584 };
585 let e = match crate::lsp::edit_apply::offset_of(&content, range.end_line, range.end_char) {
586 Ok(o) => o,
587 Err(e) => return format!("ERROR: {e}"),
588 };
589 if e < s {
590 return "ERROR: POSITION_OUT_OF_RANGE: end before start".to_string();
591 }
592 let actual = crate::core::hasher::hash_hex(&content.as_bytes()[s..e]);
593 if *exp != actual {
594 return format!(
595 "ERROR: CONFLICT: range hash mismatch (expected={exp}, actual={actual})"
596 );
597 }
598 }
599
600 let edit = crate::lsp::backend::RangeEdit {
601 abs_path,
602 rel_path,
603 range,
604 text,
605 expected_hash,
606 };
607
608 let ext = std::path::Path::new(&edit.abs_path)
611 .extension()
612 .and_then(std::ffi::OsStr::to_str)
613 .unwrap_or("");
614 {
615 let start_off =
616 crate::lsp::edit_apply::offset_of(&content, range.start_line, range.start_char)
617 .unwrap_or(0);
618 let end_off = crate::lsp::edit_apply::offset_of(&content, range.end_line, range.end_char)
619 .unwrap_or(content.len());
620 let mut hypothetical =
621 String::with_capacity(content.len() - (end_off - start_off) + edit.text.len());
622 hypothetical.push_str(&content[..start_off]);
623 hypothetical.push_str(&edit.text);
624 hypothetical.push_str(&content[end_off..]);
625 if let Some(reason) = crate::core::syntax_validate::gate_edit(ext, &content, &hypothetical)
626 {
627 return reason;
628 }
629 }
630
631 match apply_symbol_edit(action, project_root, &edit) {
633 Ok(res) => format_edit_result(action, &edit.abs_path, &res),
634 Err(e) => format!("ERROR: {e}"),
635 }
636}
637
638fn format_edit_result(
639 action: &str,
640 abs_path: &str,
641 res: &crate::lsp::backend::EditResult,
642) -> String {
643 if !res.applied {
644 return format!("{action}: not applied.");
645 }
646 let r = res.new_range;
647 let body = if res.diff.is_empty() {
648 res.edited_text.clone()
649 } else {
650 res.diff.clone()
651 };
652 format!(
654 "{action} applied {abs_path} (L{}:{}-L{}:{}):\n{}",
655 r.start_line + 1,
656 r.start_char,
657 r.end_line + 1,
658 r.end_char,
659 body
660 )
661}
662
663fn handle_inspections(
664 args: &Value,
665 file_path: &str,
666 project_root: &str,
667 uri: &lsp_types::Uri,
668) -> String {
669 let mode = args.get("mode").and_then(Value::as_str).unwrap_or("run");
670 match mode {
671 "run" => {
672 let result = crate::lsp::router::with_backend(file_path, project_root, |backend, _| {
673 let diags = backend.inspections(uri)?;
674 Ok((diags, backend.last_truncation()))
675 });
676 match result {
677 Ok((diags, meta)) => {
678 let mut out = format_inspections(&diags);
679 out.push_str(&truncation_note(diags.len(), meta));
680 out
681 }
682 Err(e) => format!("ERROR: {e}"),
683 }
684 }
685 "list" => {
686 let result = crate::lsp::router::with_backend(file_path, project_root, |backend, _| {
687 let items = backend.list_inspections()?;
688 Ok((items, backend.last_truncation()))
689 });
690 match result {
691 Ok((items, meta)) => {
692 let mut out = format_inspection_list(&items);
693 out.push_str(&truncation_note(items.len(), meta));
694 out
695 }
696 Err(e) => format!("ERROR: {e}"),
697 }
698 }
699 other => format!("ERROR: Unknown mode '{other}' for inspections. Available: run, list."),
700 }
701}
702
703fn format_inspections(diags: &[InspectionDiag]) -> String {
704 if diags.is_empty() {
705 return "No inspection findings.".to_string();
706 }
707 let mut out = format!("{} finding(s):\n", diags.len());
708 for d in diags {
709 out.push_str(&format!(
710 " {}:{} {} {}\n",
711 d.path, d.line, d.severity, d.message
712 ));
713 }
714 out
715}
716
717fn format_inspection_list(items: &[InspectionInfo]) -> String {
718 if items.is_empty() {
719 return "No inspections enabled.".to_string();
720 }
721 let mut out = format!("{} inspection(s):\n", items.len());
722 for i in items {
723 out.push_str(&format!(" {} {} {}\n", i.id, i.name, i.severity));
724 }
725 out
726}
727
728fn truncation_note(shown: usize, meta: Option<crate::lsp::backend::Truncation>) -> String {
729 match meta {
730 Some(m) if m.truncated => {
731 format!("\n(truncated — showing {shown} of {})\n", m.total)
732 }
733 _ => String::new(),
734 }
735}
736
737fn format_type_hierarchy(root: &TypeHierarchyNode) -> String {
738 fn walk(node: &TypeHierarchyNode, depth: usize, out: &mut String) {
739 let indent = " ".repeat(depth);
740 out.push_str(&format!(
741 "{indent}{} ({}:{})\n",
742 node.name, node.path, node.line
743 ));
744 for child in &node.children {
745 walk(child, depth + 1, out);
746 }
747 }
748 let mut out = String::new();
749 walk(root, 0, &mut out);
750 out
751}
752
753fn format_symbols_overview(items: &[SymbolOverviewItem]) -> String {
754 if items.is_empty() {
755 return "No symbols found.".to_string();
756 }
757 let mut out = format!("{} symbol(s):\n", items.len());
758 for item in items {
759 out.push_str(&format!(
760 " {} {} (line {})\n",
761 item.kind, item.name, item.line
762 ));
763 }
764 out
765}
766
767fn format_locations(locations: &[Location], project_root: &str) -> String {
768 if locations.is_empty() {
769 return "No results found.".to_string();
770 }
771
772 let mut out = format!("{} location(s):\n", locations.len());
773 for loc in locations {
774 let path = uri_to_file_path(&loc.uri).map_or_else(
775 || loc.uri.as_str().to_string(),
776 |p| {
777 p.strip_prefix(project_root)
778 .map(|s| s.strip_prefix('/').unwrap_or(s).to_string())
779 .unwrap_or(p)
780 },
781 );
782
783 let line = loc.range.start.line + 1;
784 let col = loc.range.start.character;
785 out.push_str(&format!(" {path}:{line}:{col}\n"));
786 }
787 out
788}
789
790fn format_workspace_edit(edit: &lsp_types::WorkspaceEdit, project_root: &str) -> String {
791 let mut out = String::from("Rename edits:\n");
792 let mut file_count = 0;
793 let mut edit_count = 0;
794
795 if let Some(ref changes) = edit.changes {
796 for (uri, edits) in changes {
797 let path = uri_to_file_path(uri).map_or_else(
798 || uri.as_str().to_string(),
799 |p| {
800 p.strip_prefix(project_root)
801 .map(|s| s.strip_prefix('/').unwrap_or(s).to_string())
802 .unwrap_or(p)
803 },
804 );
805
806 file_count += 1;
807 out.push_str(&format!(" {path}: {} edit(s)\n", edits.len()));
808 for e in edits {
809 edit_count += 1;
810 let line = e.range.start.line + 1;
811 out.push_str(&format!(" L{line}: -> \"{}\"\n", e.new_text));
812 }
813 }
814 }
815
816 if let Some(ref doc_changes) = edit.document_changes {
817 match doc_changes {
818 lsp_types::DocumentChanges::Edits(edits) => {
819 for text_edit in edits {
820 let path = uri_to_file_path(&text_edit.text_document.uri)
821 .unwrap_or_else(|| text_edit.text_document.uri.as_str().to_string());
822 file_count += 1;
823 let edits_len = text_edit.edits.len();
824 edit_count += edits_len;
825 out.push_str(&format!(" {path}: {edits_len} edit(s)\n"));
826 }
827 }
828 lsp_types::DocumentChanges::Operations(ops) => {
829 for op in ops {
830 if let lsp_types::DocumentChangeOperation::Edit(text_edit) = op {
831 let path = uri_to_file_path(&text_edit.text_document.uri)
832 .unwrap_or_else(|| text_edit.text_document.uri.as_str().to_string());
833 file_count += 1;
834 let edits_len = text_edit.edits.len();
835 edit_count += edits_len;
836 out.push_str(&format!(" {path}: {edits_len} edit(s)\n"));
837 }
838 }
839 }
840 }
841 }
842
843 out.push_str(&format!(
844 "\nTotal: {edit_count} edit(s) across {file_count} file(s)."
845 ));
846 out
847}
848
849#[cfg(test)]
850mod tests;
851#[cfg(test)]
852mod tests_ops;