codebank 0.4.5

A powerful code documentation generator that creates structured markdown documentation from your codebase. Supports multiple languages including Rust, Python, TypeScript, C, and Go with intelligent parsing and formatting. Features test code filtering, summary generation, and customizable documentation strategies.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
use crate::{
    Error, FieldUnit, FileUnit, FunctionUnit, LanguageParser, ModuleUnit, PythonParser, Result,
    StructUnit, Visibility,
};
use std::fs;
use std::ops::{Deref, DerefMut};
use std::path::Path;
use tree_sitter::{Node, Parser};

// Helper function to get the text of a node
fn get_node_text(node: Node, source_code: &str) -> Option<String> {
    node.utf8_text(source_code.as_bytes())
        .ok()
        .map(String::from)
}

// Helper function to get the text of the first child node of a specific kind
fn get_child_node_text<'a>(node: Node<'a>, kind: &str, source_code: &'a str) -> Option<String> {
    node.children(&mut node.walk())
        .find(|child| child.kind() == kind)
        .and_then(|child| child.utf8_text(source_code.as_bytes()).ok())
        .map(String::from)
}

impl PythonParser {
    pub fn try_new() -> Result<Self> {
        let mut parser = Parser::new();
        let language = tree_sitter_python::LANGUAGE;
        parser
            .set_language(&language.into())
            .map_err(|e| Error::TreeSitter(e.to_string()))?;
        Ok(Self { parser })
    }

    // Extract docstring from a node
    fn extract_documentation(&self, node: Node, source_code: &str) -> Option<String> {
        let mut cursor = node.walk();
        let mut children = node.children(&mut cursor);

        // For function/class nodes, we need to skip the definition line
        if node.kind() == "function_definition" || node.kind() == "class_definition" {
            children.next(); // Skip the function/class definition line
        }

        // Look for the docstring
        for child in children {
            match child.kind() {
                "block" => {
                    // For function/class bodies, look in the block
                    let mut body_cursor = child.walk();
                    let mut body_children = child.children(&mut body_cursor);
                    if let Some(first_expr) = body_children.next() {
                        if first_expr.kind() == "expression_statement" {
                            if let Some(string) = first_expr
                                .children(&mut first_expr.walk())
                                .find(|c| c.kind() == "string")
                            {
                                return self.clean_docstring(string, source_code);
                            }
                        }
                    }
                }
                "expression_statement" => {
                    // For module level docstrings
                    if let Some(string) = child
                        .children(&mut child.walk())
                        .find(|c| c.kind() == "string")
                    {
                        return self.clean_docstring(string, source_code);
                    }
                }
                "ERROR" => {
                    // For ERROR nodes, try to get the string content directly
                    let mut error_cursor = child.walk();
                    let error_children = child.children(&mut error_cursor);
                    for error_child in error_children {
                        if error_child.kind() == "string" {
                            if let Some(string_content) = error_child
                                .children(&mut error_child.walk())
                                .find(|c| c.kind() == "string_content")
                            {
                                if let Some(content) = get_node_text(string_content, source_code) {
                                    return Some(content.trim().to_string());
                                }
                            }
                        }
                    }
                }
                _ => continue,
            }
        }
        None
    }

    // Helper to clean up docstring content
    fn clean_docstring(&self, node: Node, source_code: &str) -> Option<String> {
        let doc = get_node_text(node, source_code)?;
        // Clean up the docstring - handle both single and triple quotes
        let doc = if doc.starts_with("\"\"\"") && doc.ends_with("\"\"\"") {
            // Handle triple quotes
            doc[3..doc.len() - 3].trim()
        } else if doc.starts_with("'''") && doc.ends_with("'''") {
            // Handle triple single quotes
            doc[3..doc.len() - 3].trim()
        } else {
            // Handle single quotes
            doc.trim_matches('"').trim_matches('\'').trim()
        };
        Some(doc.to_string())
    }

    // Extract decorators from a node
    fn extract_decorators(&self, node: Node, source_code: &str) -> Vec<String> {
        let mut decorators = Vec::new();
        let mut cursor = node.walk();

        // Look for decorators before the function/class definition
        for child in node.children(&mut cursor) {
            if child.kind() == "decorator" {
                if let Some(text) = get_node_text(child, source_code) {
                    decorators.push(text);
                }
            }
        }
        decorators
    }

    // Parse function and extract its details
    fn parse_function(&self, node: Node, source_code: &str) -> Result<FunctionUnit> {
        // If this is a decorated function, get the actual function definition
        let function_node = if node.kind() == "decorated_definition" {
            node.children(&mut node.walk())
                .find(|child| child.kind() == "function_definition")
                .unwrap_or(node)
        } else {
            node
        };

        let name = get_child_node_text(function_node, "identifier", source_code)
            .unwrap_or_else(|| "unknown".to_string());
        let documentation = self.extract_documentation(function_node, source_code);
        let attributes = self.extract_decorators(node, source_code);
        let source = get_node_text(function_node, source_code);
        let visibility = if name.starts_with('_') {
            Visibility::Private
        } else {
            Visibility::Public
        };

        let mut signature = None;
        let mut body = None;

        if let Some(src) = &source {
            if let Some(body_start_idx) = src.find(':') {
                signature = Some(src[0..body_start_idx].trim().to_string());
                body = Some(src[body_start_idx + 1..].trim().to_string());
            }
        }

        Ok(FunctionUnit {
            name,
            visibility,
            doc: documentation,
            source,
            signature,
            body,
            attributes,
        })
    }

    // Parse class and extract its details
    fn parse_class(&self, node: Node, source_code: &str) -> Result<StructUnit> {
        // If this is a decorated class, get the actual class definition
        let class_node = if node.kind() == "decorated_definition" {
            node.children(&mut node.walk())
                .find(|child| child.kind() == "class_definition")
                .unwrap_or(node)
        } else {
            node
        };

        let name = get_child_node_text(class_node, "identifier", source_code)
            .unwrap_or_else(|| "unknown".to_string());
        let documentation = self.extract_documentation(class_node, source_code);
        let attributes = self.extract_decorators(node, source_code);
        let source = get_node_text(class_node, source_code);
        let visibility = if name.starts_with('_') {
            Visibility::Private
        } else {
            Visibility::Public
        };

        // TODO: parse class head
        let head = format!("class {}", name);

        // Extract methods from class body
        let mut methods = Vec::new();
        let mut cursor = class_node.walk();
        for child in class_node.children(&mut cursor) {
            if child.kind() == "block" {
                let mut block_cursor = child.walk();
                for method_node in child.children(&mut block_cursor) {
                    match method_node.kind() {
                        "function_definition" | "decorated_definition" => {
                            if let Ok(method) = self.parse_function(method_node, source_code) {
                                methods.push(method);
                            }
                        }
                        _ => continue,
                    }
                }
            }
        }

        let mut class_unit = StructUnit {
            name,
            head,
            visibility,
            doc: documentation,
            source,
            attributes,
            fields: Vec::new(),
            methods: methods.clone(),
        };

        // Extract fields from __init__ method if present
        if let Some(init_method) = methods.iter().find(|m| m.name == "__init__") {
            if let Some(body_text) = &init_method.body {
                // Very basic parsing: look for lines like "self.field_name = ..."
                for line in body_text.lines() {
                    let trimmed_line = line.trim();
                    if trimmed_line.starts_with("self.") {
                        if let Some(eq_pos) = trimmed_line.find('=') {
                            let potential_field = &trimmed_line[5..eq_pos].trim();
                            if !potential_field.is_empty()
                                && potential_field
                                    .chars()
                                    .all(|c| c.is_alphanumeric() || c == '_')
                            {
                                // Basic check for valid identifier
                                let field = FieldUnit {
                                    name: potential_field.to_string(),
                                    // Python docs/attrs for fields are harder to associate reliably here
                                    doc: None,
                                    attributes: Vec::new(),
                                    source: Some(trimmed_line.to_string()),
                                };
                                // Avoid duplicates if field is assigned multiple times
                                if !class_unit.fields.iter().any(|f| f.name == field.name) {
                                    class_unit.fields.push(field);
                                }
                            }
                        }
                    }
                }
            }
        }

        Ok(class_unit)
    }

    #[allow(dead_code)]
    // Parse module and extract its details
    fn parse_module(&self, node: Node, source_code: &str) -> Result<ModuleUnit> {
        let name = get_child_node_text(node, "identifier", source_code)
            .unwrap_or_else(|| "unknown".to_string());
        let document = self.extract_documentation(node, source_code);
        let source = get_node_text(node, source_code);
        let visibility = if name.starts_with('_') {
            Visibility::Private
        } else {
            Visibility::Public
        };

        Ok(ModuleUnit {
            name,
            visibility,
            doc: document,
            source,
            attributes: Vec::new(),
            declares: Vec::new(),
            functions: Vec::new(),
            structs: Vec::new(),
            traits: Vec::new(),
            impls: Vec::new(),
            submodules: Vec::new(),
        })
    }
}

impl LanguageParser for PythonParser {
    fn parse_file(&mut self, file_path: &Path) -> Result<FileUnit> {
        let source_code = fs::read_to_string(file_path).map_err(Error::Io)?;
        let tree = self
            .parse(source_code.as_bytes(), None)
            .ok_or_else(|| Error::TreeSitter("Failed to parse Python file".to_string()))?;

        let mut file_unit = FileUnit {
            path: file_path.to_path_buf(),
            source: Some(source_code.clone()),
            doc: None,
            declares: Vec::new(),
            modules: Vec::new(),
            functions: Vec::new(),
            structs: Vec::new(),
            traits: Vec::new(),
            impls: Vec::new(),
        };

        let root_node = tree.root_node();

        // First look for module docstring
        {
            let mut cursor = root_node.walk();
            let mut children = root_node.children(&mut cursor);

            if let Some(first_expr) = children.next() {
                if first_expr.kind() == "expression_statement" {
                    if let Some(string) = first_expr
                        .children(&mut first_expr.walk())
                        .find(|c| c.kind() == "string")
                    {
                        if let Some(doc) = get_node_text(string, &source_code) {
                            // Clean up the docstring - handle both single and triple quotes
                            let doc = doc
                                .trim_start_matches(r#"""""#)
                                .trim_end_matches(r#"""""#)
                                .trim_start_matches(r#"'''"#)
                                .trim_end_matches(r#"'''"#)
                                .trim_start_matches('"')
                                .trim_end_matches('"')
                                .trim_start_matches('\'')
                                .trim_end_matches('\'')
                                .trim();
                            file_unit.doc = Some(doc.to_string());
                        }
                    }
                }
            }
        }

        // Process imports first
        {
            let mut cursor = root_node.walk();
            for node in root_node.children(&mut cursor) {
                if node.kind() == "import_statement" || node.kind() == "import_from_statement" {
                    if let Some(import_text) = get_node_text(node, &source_code) {
                        file_unit.declares.push(crate::DeclareStatements {
                            source: import_text,
                            kind: crate::DeclareKind::Import,
                        });
                    }
                }
            }
        }

        // Then process all top-level nodes
        let mut cursor = root_node.walk();
        for node in root_node.children(&mut cursor) {
            match node.kind() {
                "function_definition" => {
                    let func = self.parse_function(node, &source_code)?;
                    file_unit.functions.push(func);
                }
                "class_definition" => {
                    let class = self.parse_class(node, &source_code)?;
                    file_unit.structs.push(class);
                }
                "decorated_definition" => {
                    let mut node_cursor = node.walk();
                    let children: Vec<_> = node.children(&mut node_cursor).collect();
                    if let Some(def_node) = children.iter().find(|n| {
                        n.kind() == "function_definition" || n.kind() == "class_definition"
                    }) {
                        match def_node.kind() {
                            "function_definition" => {
                                let func = self.parse_function(node, &source_code)?;
                                file_unit.functions.push(func);
                            }
                            "class_definition" => {
                                let class = self.parse_class(node, &source_code)?;
                                file_unit.structs.push(class);
                            }
                            _ => {}
                        }
                    }
                }
                _ => continue,
            }
        }

        Ok(file_unit)
    }
}

impl Deref for PythonParser {
    type Target = Parser;

    fn deref(&self) -> &Self::Target {
        &self.parser
    }
}

impl DerefMut for PythonParser {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.parser
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    fn create_test_file(content: &str) -> Result<(tempfile::TempDir, PathBuf)> {
        let dir = tempfile::tempdir().map_err(Error::Io)?;
        let file_path = dir.path().join("test.py");
        fs::write(&file_path, content).map_err(Error::Io)?;
        Ok((dir, file_path))
    }

    #[test]
    fn test_parse_function() -> Result<()> {
        let content = r#"
def hello_world():
    """This is a docstring."""
    print("Hello, World!")
"#;
        let (_dir, file_path) = create_test_file(content)?;
        let mut parser = PythonParser::try_new()?;
        let file_unit = parser.parse_file(&file_path)?;

        assert_eq!(file_unit.functions.len(), 1);
        let func = &file_unit.functions[0];
        assert_eq!(func.name, "hello_world");
        assert_eq!(func.visibility, Visibility::Public);
        assert_eq!(func.doc, Some("This is a docstring.".to_string()));
        Ok(())
    }

    #[test]
    fn test_parse_class() -> Result<()> {
        let content = r#"
@dataclass
class Person:
    """A person class."""
    def __init__(self, name: str):
        self.name = name
"#;
        let (_dir, file_path) = create_test_file(content)?;
        let mut parser = PythonParser::try_new()?;
        let file_unit = parser.parse_file(&file_path)?;

        assert_eq!(file_unit.structs.len(), 1);
        let class = &file_unit.structs[0];
        assert_eq!(class.name, "Person");
        assert_eq!(class.visibility, Visibility::Public);
        assert_eq!(class.doc, Some("A person class.".to_string()));
        assert_eq!(class.attributes.len(), 1);
        assert_eq!(class.attributes[0], "@dataclass");
        Ok(())
    }

    #[test]
    fn test_parse_private_members() -> Result<()> {
        let content = r#"
def _private_function():
    """A private function."""
    pass

class _PrivateClass:
    """A private class."""
    pass
"#;
        let (_dir, file_path) = create_test_file(content)?;
        let mut parser = PythonParser::try_new()?;
        let file_unit = parser.parse_file(&file_path)?;

        assert_eq!(file_unit.functions[0].visibility, Visibility::Private);
        assert_eq!(file_unit.structs[0].visibility, Visibility::Private);
        Ok(())
    }

    #[test]
    fn test_parse_module_docstring() -> Result<()> {
        let content = r#"'''This is a module docstring.'''

def hello_world():
    pass
"#;
        let (_dir, file_path) = create_test_file(content)?;
        let mut parser = PythonParser::try_new()?;
        let file_unit = parser.parse_file(&file_path)?;

        assert_eq!(
            file_unit.doc,
            Some("This is a module docstring.".to_string())
        );
        Ok(())
    }

    #[test]
    fn test_parse_module_docstring_with_triple_quotes() -> Result<()> {
        let content = r#"'''This is a module docstring with triple quotes.'''

def hello_world():
    pass
"#;
        let (_dir, file_path) = create_test_file(content)?;
        let mut parser = PythonParser::try_new()?;
        let file_unit = parser.parse_file(&file_path)?;

        assert_eq!(
            file_unit.doc,
            Some("This is a module docstring with triple quotes.".to_string())
        );
        Ok(())
    }

    #[test]
    fn test_parse_class_with_fields() -> Result<()> {
        let content = r#"
class MyClass:
    """Class docstring."""
    class_var = 10 # Class variable, should not be parsed as field

    def __init__(self, name: str, value: int):
        """Init docstring."""
        self.name = name
        self._value = value # Private field
        # self.complex = calculate(value) # Assignment from call
        self.literal = "hello"

    def method(self):
        pass
"#;
        let (_dir, file_path) = create_test_file(content)?;
        let mut parser = PythonParser::try_new()?;
        let file_unit = parser.parse_file(&file_path)?;

        assert_eq!(file_unit.structs.len(), 1);
        let class = &file_unit.structs[0];
        assert_eq!(class.name, "MyClass");
        assert_eq!(class.methods.len(), 2);

        // Check fields parsed from __init__
        assert_eq!(class.fields.len(), 3);

        // Check name field
        let name_field = class.fields.iter().find(|f| f.name == "name").unwrap();
        assert_eq!(name_field.name, "name");
        assert!(name_field.doc.is_none()); // Currently not parsing field docs
        assert!(
            name_field
                .source
                .as_ref()
                .unwrap()
                .contains("self.name = name")
        );

        // Check _value field
        let value_field = class.fields.iter().find(|f| f.name == "_value").unwrap();
        assert_eq!(value_field.name, "_value");
        assert!(
            value_field
                .source
                .as_ref()
                .unwrap()
                .contains("self._value = value")
        );

        // Check literal field
        let literal_field = class.fields.iter().find(|f| f.name == "literal").unwrap();
        assert_eq!(literal_field.name, "literal");
        assert!(
            literal_field
                .source
                .as_ref()
                .unwrap()
                .contains("self.literal = \"hello\"")
        );

        // Ensure class_var was not parsed as a field
        assert!(!class.fields.iter().any(|f| f.name == "class_var"));

        Ok(())
    }
}