Skip to main content

gitcortex_mcp/mcp/
wiki.rs

1//! Wiki rendering — markdown summary for a single symbol assembled from
2//! the graph store. Pure formatter: no I/O beyond the store reads.
3//!
4//! Output shape (markdown):
5//!
6//! ```text
7//! # <name> (<kind>)
8//!
9//! **Defined in** `<file>:<start>-<end>` · visibility=<vis> · async=<bool> ...
10//!
11//! ## Signature
12//! ```<lang>
13//! <signature>
14//! ```
15//!
16//! ## Doc
17//! <doc_comment>
18//!
19//! ## Callers (N)
20//! - <name> (<kind>) — <file>:<line>
21//!
22//! ## Calls (N)
23//! - …
24//!
25//! ## Used by (N)
26//! - …
27//! ```
28
29use std::fmt::Write;
30
31use gitcortex_core::{
32    error::Result,
33    graph::Node,
34    store::{GraphStore, SymbolContext},
35};
36
37/// Markdown wiki rendering for `name` on `branch`.
38/// Returns an `Err` only when the store itself fails; "symbol not found" is
39/// surfaced by the upstream `symbol_context` error.
40pub fn render_symbol<S: GraphStore + ?Sized>(
41    store: &S,
42    branch: &str,
43    name: &str,
44) -> Result<String> {
45    let ctx = store.symbol_context(branch, name)?;
46    Ok(format(ctx))
47}
48
49fn format(ctx: SymbolContext) -> String {
50    let def = &ctx.definition;
51    let lang = file_lang(&def.file.to_string_lossy());
52    let mut out = String::with_capacity(1024);
53
54    let _ = writeln!(out, "# {} ({})", def.name, def.kind);
55    let _ = writeln!(out);
56    let _ = writeln!(
57        out,
58        "**Defined in** `{}:{}-{}`  ·  visibility={}  ·  async={}  ·  loc={}",
59        def.file.display(),
60        def.span.start_line,
61        def.span.end_line,
62        def.metadata.visibility,
63        def.metadata.is_async,
64        def.metadata.loc,
65    );
66    if def.qualified_name != def.name {
67        let _ = writeln!(out, "**Qualified** `{}`", def.qualified_name);
68    }
69    let _ = writeln!(out);
70
71    let sig = def.metadata.definition.signature.trim();
72    if !sig.is_empty() {
73        let _ = writeln!(out, "## Signature");
74        let _ = writeln!(out, "```{lang}");
75        let _ = writeln!(out, "{sig}");
76        let _ = writeln!(out, "```");
77        let _ = writeln!(out);
78    }
79
80    if let Some(doc) = def.metadata.definition.doc_comment.as_deref() {
81        let stripped = strip_doc_markers(doc);
82        if !stripped.trim().is_empty() {
83            let _ = writeln!(out, "## Doc");
84            let _ = writeln!(out, "{}", stripped.trim());
85            let _ = writeln!(out);
86        }
87    }
88
89    write_neighbor_list(&mut out, "Callers", &ctx.callers);
90    write_neighbor_list(&mut out, "Calls", &ctx.callees);
91    write_neighbor_list(&mut out, "Used by", &ctx.used_by);
92
93    out
94}
95
96fn write_neighbor_list(out: &mut String, label: &str, nodes: &[Node]) {
97    if nodes.is_empty() {
98        return;
99    }
100    let _ = writeln!(out, "## {label} ({})", nodes.len());
101    for n in nodes {
102        let _ = writeln!(
103            out,
104            "- `{}` ({})  — `{}:{}`",
105            n.name,
106            n.kind,
107            n.file.display(),
108            n.span.start_line
109        );
110    }
111    let _ = writeln!(out);
112}
113
114/// Strip per-line `///`, `//!`, `// `, `# `, `*` doc-comment leaders so the
115/// rendered markdown reads as prose, not as code-fence content.
116fn strip_doc_markers(doc: &str) -> String {
117    let mut out = String::with_capacity(doc.len());
118    for line in doc.lines() {
119        let trimmed = line.trim_start();
120        let cleaned = trimmed
121            .strip_prefix("///")
122            .or_else(|| trimmed.strip_prefix("//!"))
123            .or_else(|| trimmed.strip_prefix("/**"))
124            .or_else(|| trimmed.strip_prefix("*/"))
125            .or_else(|| trimmed.strip_prefix("//"))
126            .or_else(|| trimmed.strip_prefix("# "))
127            .or_else(|| trimmed.strip_prefix("#"))
128            .or_else(|| trimmed.strip_prefix("* "))
129            .or_else(|| trimmed.strip_prefix("*"))
130            .unwrap_or(trimmed);
131        // Also strip a trailing `*/` (single-line javadoc /** … */).
132        let cleaned = cleaned
133            .trim_end()
134            .strip_suffix("*/")
135            .unwrap_or(cleaned)
136            .trim_end();
137        out.push_str(cleaned.trim_start());
138        out.push('\n');
139    }
140    out
141}
142
143/// Best-effort language hint from a file path, for fenced code-block tagging.
144fn file_lang(path: &str) -> &'static str {
145    let ext = path.rsplit('.').next().unwrap_or("");
146    match ext {
147        "rs" => "rust",
148        "py" => "python",
149        "ts" | "tsx" => "typescript",
150        "js" | "jsx" | "mjs" | "cjs" => "javascript",
151        "go" => "go",
152        "java" => "java",
153        _ => "",
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    #[test]
162    fn lang_from_path() {
163        assert_eq!(file_lang("src/main.rs"), "rust");
164        assert_eq!(file_lang("app/foo.tsx"), "typescript");
165        assert_eq!(file_lang("Makefile"), "");
166    }
167
168    #[test]
169    fn strip_rust_doc_markers() {
170        let input = "/// First line\n/// Second line\n";
171        let out = strip_doc_markers(input);
172        assert!(out.contains("First line"));
173        assert!(!out.contains("///"));
174    }
175}