code-compass-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,734 @@
1
+ """Auto-generates documentation for the codebase."""
2
+
3
+ import os
4
+ import re
5
+ from pathlib import Path
6
+ from typing import Dict, List, Any, Optional
7
+ from datetime import datetime
8
+
9
+
10
+ class DocumentationGenerator:
11
+ """Generates comprehensive documentation for a Python project."""
12
+
13
+ def __init__(self, repo_path: str = "."):
14
+ """Initialize the documentation generator.
15
+
16
+ Args:
17
+ repo_path: Path to repository to analyze
18
+ """
19
+ self.repo_path = Path(repo_path)
20
+ self.docs_path = self.repo_path / "docs"
21
+ self.modules: Dict[str, Dict[str, Any]] = {}
22
+ self.project_name = self.repo_path.name
23
+ self._analyze_project()
24
+
25
+ def _analyze_project(self) -> None:
26
+ """Analyze the project structure and modules."""
27
+ for root, _, files in os.walk(self.repo_path):
28
+ # Skip venv and hidden directories
29
+ if "venv" in root or "/.git" in root or "/docs" in root:
30
+ continue
31
+
32
+ for file in files:
33
+ if file.endswith(".py"):
34
+ filepath = Path(root) / file
35
+ rel_path = filepath.relative_to(self.repo_path)
36
+ module_name = str(rel_path).replace(".py", "").replace("/", ".")
37
+
38
+ try:
39
+ with open(filepath, "r", encoding="utf-8", errors="ignore") as f:
40
+ content = f.read()
41
+ self.modules[module_name] = self._extract_module_info(content, file)
42
+ except (IOError, OSError):
43
+ continue
44
+
45
+ def _extract_module_info(self, content: str, filename: str) -> Dict[str, Any]:
46
+ """Extract module information from file content.
47
+
48
+ Args:
49
+ content: File content
50
+ filename: Name of the file
51
+
52
+ Returns:
53
+ Dictionary with module information
54
+ """
55
+ lines = content.split("\n")
56
+ docstring = self._extract_docstring(content)
57
+ functions = self._extract_functions(content)
58
+ classes = self._extract_classes(content)
59
+
60
+ return {
61
+ "filename": filename,
62
+ "docstring": docstring,
63
+ "functions": functions,
64
+ "classes": classes,
65
+ "lines": len(lines),
66
+ }
67
+
68
+ def _extract_docstring(self, content: str) -> str:
69
+ """Extract module docstring.
70
+
71
+ Args:
72
+ content: File content
73
+
74
+ Returns:
75
+ Docstring or empty string
76
+ """
77
+ match = re.search(r'"""(.+?)"""', content, re.DOTALL)
78
+ if match:
79
+ return match.group(1).strip()
80
+ return ""
81
+
82
+ def _extract_functions(self, content: str) -> List[Dict[str, str]]:
83
+ """Extract function definitions.
84
+
85
+ Args:
86
+ content: File content
87
+
88
+ Returns:
89
+ List of function definitions
90
+ """
91
+ functions = []
92
+ lines = content.split("\n")
93
+
94
+ for i, line in enumerate(lines):
95
+ func_match = re.match(r"^\s*def\s+(\w+)\s*\(([^)]*)\)", line)
96
+ if func_match and not line.strip().startswith("#"):
97
+ func_name = func_match.group(1)
98
+ params = func_match.group(2)
99
+ docstring = ""
100
+
101
+ # Try to extract docstring from next lines
102
+ if i + 1 < len(lines):
103
+ doc_match = re.search(r'"""(.+?)"""', "\n".join(lines[i+1:i+10]), re.DOTALL)
104
+ if doc_match:
105
+ docstring = doc_match.group(1).strip().split("\n")[0]
106
+
107
+ functions.append({
108
+ "name": func_name,
109
+ "params": params.strip(),
110
+ "docstring": docstring,
111
+ })
112
+
113
+ return functions
114
+
115
+ def _extract_classes(self, content: str) -> List[Dict[str, Any]]:
116
+ """Extract class definitions.
117
+
118
+ Args:
119
+ content: File content
120
+
121
+ Returns:
122
+ List of class definitions
123
+ """
124
+ classes = []
125
+ lines = content.split("\n")
126
+
127
+ for i, line in enumerate(lines):
128
+ class_match = re.match(r"^\s*class\s+(\w+)\s*[\(:]", line)
129
+ if class_match and not line.strip().startswith("#"):
130
+ class_name = class_match.group(1)
131
+ docstring = ""
132
+
133
+ # Try to extract docstring from next lines
134
+ if i + 1 < len(lines):
135
+ doc_match = re.search(r'"""(.+?)"""', "\n".join(lines[i+1:i+10]), re.DOTALL)
136
+ if doc_match:
137
+ docstring = doc_match.group(1).strip().split("\n")[0]
138
+
139
+ classes.append({
140
+ "name": class_name,
141
+ "docstring": docstring,
142
+ })
143
+
144
+ return classes
145
+
146
+ def generate(self) -> Dict[str, str]:
147
+ """Generate all documentation files.
148
+
149
+ Returns:
150
+ Dictionary with generated documentation content
151
+ """
152
+ # Create docs directory
153
+ self.docs_path.mkdir(exist_ok=True)
154
+
155
+ docs = {
156
+ "README.md": self._generate_readme(),
157
+ "ARCHITECTURE.md": self._generate_architecture(),
158
+ "SETUP.md": self._generate_setup(),
159
+ }
160
+
161
+ # Write files
162
+ for filename, content in docs.items():
163
+ filepath = self.docs_path / filename
164
+ try:
165
+ with open(filepath, "w", encoding="utf-8") as f:
166
+ f.write(content)
167
+ except (IOError, OSError) as e:
168
+ print(f"Error writing {filename}: {e}")
169
+
170
+ return docs
171
+
172
+ def _generate_readme(self) -> str:
173
+ """Generate README.md.
174
+
175
+ Returns:
176
+ README content
177
+ """
178
+ project_name = self.project_name.replace("-", " ").title()
179
+
180
+ content = f"""# {project_name}
181
+
182
+ A Python CLI tool for code analysis and navigation.
183
+
184
+ ## Overview
185
+
186
+ {project_name} provides intelligent code analysis, navigation, and quality checking tools for Python projects.
187
+
188
+ ### Features
189
+
190
+ - **Code Querying**: Search your codebase with natural language queries
191
+ - **Flow Tracing**: Trace execution paths through your code
192
+ - **Quality Analysis**: Detect security issues, performance problems, and code smells
193
+ - **Auto-Documentation**: Generate comprehensive project documentation
194
+
195
+ ## Quick Start
196
+
197
+ ### Installation
198
+
199
+ ```bash
200
+ pip install -r requirements.txt
201
+ ```
202
+
203
+ ### Basic Usage
204
+
205
+ ```bash
206
+ # Scan repository structure
207
+ python3 src/cli/main.py scan .
208
+
209
+ # Query codebase
210
+ python3 src/cli/main.py query "find FlowTracer" .
211
+
212
+ # Trace execution flow
213
+ python3 src/cli/main.py trace execute .
214
+
215
+ # Analyze code quality
216
+ python3 src/cli/main.py analyze .
217
+
218
+ # Generate documentation
219
+ python3 src/cli/main.py gendocs .
220
+ ```
221
+
222
+ ## Commands
223
+
224
+ ### scan
225
+ Scan a repository for code structure.
226
+ ```bash
227
+ python3 src/cli/main.py scan <path>
228
+ ```
229
+
230
+ ### query
231
+ Query code with natural language.
232
+ ```bash
233
+ python3 src/cli/main.py query "<question>" <path>
234
+ ```
235
+
236
+ ### trace
237
+ Trace execution flow for a symbol.
238
+ ```bash
239
+ python3 src/cli/main.py trace <function_name> <path>
240
+ ```
241
+
242
+ ### analyze
243
+ Analyze code quality (security, performance, code smells).
244
+ ```bash
245
+ python3 src/cli/main.py analyze <path>
246
+ ```
247
+
248
+ ### gendocs
249
+ Generate documentation for the project.
250
+ ```bash
251
+ python3 src/cli/main.py gendocs <path>
252
+ ```
253
+
254
+ ## Project Structure
255
+
256
+ See [ARCHITECTURE.md](ARCHITECTURE.md) for detailed project architecture and module descriptions.
257
+
258
+ ## Setup & Installation
259
+
260
+ See [SETUP.md](SETUP.md) for detailed setup instructions.
261
+
262
+ ## Requirements
263
+
264
+ - Python 3.7+
265
+ - click>=8.1.0
266
+ - rich>=13.0.0
267
+
268
+ ## License
269
+
270
+ MIT License
271
+
272
+ ---
273
+
274
+ Generated on {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
275
+ """
276
+ return content
277
+
278
+ def _generate_architecture(self) -> str:
279
+ """Generate ARCHITECTURE.md.
280
+
281
+ Returns:
282
+ ARCHITECTURE content
283
+ """
284
+ content = """# Architecture
285
+
286
+ ## Project Structure
287
+
288
+ ```
289
+ code-compass/
290
+ ├── src/
291
+ │ ├── __init__.py # Package initialization
292
+ │ ├── cli/
293
+ │ │ ├── __init__.py
294
+ │ │ └── main.py # CLI entry point and command definitions
295
+ │ ├── scanner/
296
+ │ │ ├── __init__.py
297
+ │ │ └── repo_scanner.py # Repository scanning and analysis
298
+ │ ├── query/
299
+ │ │ ├── __init__.py
300
+ │ │ └── copilot_query.py # NLP query engine
301
+ │ ├── visualizer/
302
+ │ │ ├── __init__.py
303
+ │ │ └── flow_tracer.py # Execution flow tracing
304
+ │ ├── quality/
305
+ │ │ ├── __init__.py
306
+ │ │ └── analyzer.py # Code quality analysis
307
+ │ └── docs/
308
+ │ ├── __init__.py
309
+ │ └── doc_generator.py # Documentation generation
310
+ ├── requirements.txt # Project dependencies
311
+ └── README.md
312
+ ```
313
+
314
+ ## Module Overview
315
+
316
+ ### CLI Module (`src/cli/main.py`)
317
+
318
+ **Purpose**: Command-line interface for all CodeCompass features.
319
+
320
+ **Key Components**:
321
+ - `cli()`: Main entry point, creates click command group
322
+ - `scan()`: Repository structure scanning
323
+ - `query()`: Natural language code search
324
+ - `trace()`: Execution flow visualization
325
+ - `analyze()`: Code quality analysis
326
+ - `gendocs()`: Auto-documentation generation
327
+
328
+ **Dependencies**: click, rich
329
+
330
+ ### Scanner Module (`src/scanner/repo_scanner.py`)
331
+
332
+ **Purpose**: Analyzes repository structure and file organization.
333
+
334
+ **Key Classes**:
335
+ - `RepoScanner`: Walks repository and collects file/directory information
336
+
337
+ **Key Methods**:
338
+ - `scan()`: Returns structure information
339
+ - `_collect_files()`: Gathers all project files
340
+ - `_collect_directories()`: Gathers all directories
341
+
342
+ ### Query Module (`src/query/copilot_query.py`)
343
+
344
+ **Purpose**: Intelligent code querying with natural language understanding.
345
+
346
+ **Key Classes**:
347
+ - `CopilotQuery`: Executes queries against codebase
348
+
349
+ **Key Methods**:
350
+ - `execute()`: Routes queries to appropriate handler
351
+ - `_search_query()`: Keyword-based search
352
+ - `_definition_query()`: Find class/function definitions
353
+ - `_import_query()`: Find imports and dependencies
354
+ - `_general_query()`: Answer general project questions
355
+
356
+ **Capabilities**:
357
+ - Searches code for keywords with line numbers
358
+ - Finds function and class definitions
359
+ - Identifies import statements
360
+ - Answers questions about project purpose
361
+
362
+ ### Visualizer Module (`src/visualizer/flow_tracer.py`)
363
+
364
+ **Purpose**: Traces and visualizes code execution flows.
365
+
366
+ **Key Classes**:
367
+ - `FlowTracer`: Analyzes call chains and execution paths
368
+ - `Node`: Represents a function/class in the execution graph
369
+
370
+ **Key Methods**:
371
+ - `trace()`: Analyzes execution flow from entry point
372
+ - `_scan_codebase()`: Finds all definitions and calls
373
+ - `_extract_definitions()`: Locates functions and classes
374
+ - `_extract_calls()`: Identifies function calls
375
+ - `_build_call_chain()`: Creates execution tree
376
+
377
+ **Capabilities**:
378
+ - Maps function calls and dependencies
379
+ - Shows execution paths with file/line references
380
+ - Prevents infinite recursion with depth limits
381
+ - Filters out built-in functions
382
+
383
+ ### Quality Module (`src/quality/analyzer.py`)
384
+
385
+ **Purpose**: Detects code quality issues and security vulnerabilities.
386
+
387
+ **Key Classes**:
388
+ - `CodeAnalyzer`: Analyzes code for issues
389
+ - `Issue`: Represents a detected problem
390
+
391
+ **Issue Types**:
392
+ 1. **Security** (Critical/Warning)
393
+ - SQL injection patterns
394
+ - Hardcoded secrets/API keys
395
+ - XSS vulnerabilities
396
+
397
+ 2. **Performance** (Warning/Info)
398
+ - N+1 query patterns
399
+ - Nested loops and inefficiency
400
+
401
+ 3. **Code Smells** (Info)
402
+ - Long functions (>30 lines)
403
+ - Large classes (>50 lines)
404
+ - Duplicate code
405
+
406
+ **Each Issue Includes**:
407
+ - File path and line number
408
+ - Severity level
409
+ - Category
410
+ - Description
411
+ - Fix suggestion
412
+
413
+ ### Documentation Module (`src/docs/doc_generator.py`)
414
+
415
+ **Purpose**: Auto-generates project documentation.
416
+
417
+ **Key Classes**:
418
+ - `DocumentationGenerator`: Analyzes project and generates docs
419
+
420
+ **Generated Files**:
421
+ - `README.md`: Project overview and quick start
422
+ - `ARCHITECTURE.md`: Detailed architecture guide
423
+ - `SETUP.md`: Installation and setup instructions
424
+
425
+ **Key Methods**:
426
+ - `generate()`: Creates all documentation files
427
+ - `_analyze_project()`: Scans and analyzes project structure
428
+ - `_extract_module_info()`: Extracts info from modules
429
+ - `_extract_docstring()`: Gets module docstrings
430
+ - `_extract_functions()`: Lists functions
431
+ - `_extract_classes()`: Lists classes
432
+
433
+ ## Data Flow
434
+
435
+ ### Query Processing
436
+ ```
437
+ User Input
438
+
439
+ Query Command
440
+
441
+ CopilotQuery.execute()
442
+
443
+ Query Type Detection (search/definition/import/general)
444
+
445
+ Appropriate Handler Method
446
+
447
+ Codebase Analysis
448
+
449
+ Rich Formatted Output
450
+ ```
451
+
452
+ ### Flow Tracing
453
+ ```
454
+ User Input (function name)
455
+
456
+ Trace Command
457
+
458
+ FlowTracer.trace()
459
+
460
+ Codebase Scanning
461
+
462
+ Definition Extraction
463
+
464
+ Call Analysis
465
+
466
+ Call Chain Building
467
+
468
+ Tree Visualization
469
+
470
+ Rich Formatted Output
471
+ ```
472
+
473
+ ### Quality Analysis
474
+ ```
475
+ User Input (repository path)
476
+
477
+ Analyze Command
478
+
479
+ CodeAnalyzer.analyze()
480
+
481
+ File-by-File Analysis
482
+
483
+ Security Checks
484
+
485
+ Performance Checks
486
+
487
+ Code Smell Detection
488
+
489
+ Issue Categorization by Severity
490
+
491
+ Rich Formatted Output
492
+ ```
493
+
494
+ ## Technology Stack
495
+
496
+ - **Language**: Python 3.7+
497
+ - **CLI Framework**: Click
498
+ - **Output Formatting**: Rich
499
+ - **Pattern Matching**: Regular Expressions
500
+ - **File I/O**: Standard Python libraries
501
+
502
+ ## Design Principles
503
+
504
+ 1. **Modularity**: Each feature in its own module with clear responsibilities
505
+ 2. **Extensibility**: Easy to add new query types, checks, or commands
506
+ 3. **User-Friendly**: Rich terminal output with colors, tables, and formatting
507
+ 4. **Non-Invasive**: Reads files, doesn't modify them (except docs generation)
508
+ 5. **Performance**: Efficient file scanning and pattern matching
509
+
510
+ ---
511
+
512
+ Generated documentation - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
513
+ """
514
+ return content
515
+
516
+ def _generate_setup(self) -> str:
517
+ """Generate SETUP.md.
518
+
519
+ Returns:
520
+ SETUP content
521
+ """
522
+ content = """# Setup & Installation Guide
523
+
524
+ ## Requirements
525
+
526
+ - Python 3.7 or higher
527
+ - pip (Python package manager)
528
+
529
+ ## Installation Steps
530
+
531
+ ### 1. Clone or Download the Repository
532
+
533
+ ```bash
534
+ cd code-compass
535
+ ```
536
+
537
+ ### 2. Create a Virtual Environment (Recommended)
538
+
539
+ ```bash
540
+ python3 -m venv venv
541
+ source venv/bin/activate # On Windows: venv\\\\Scripts\\\\activate
542
+ ```
543
+
544
+ ### 3. Install Dependencies
545
+
546
+ ```bash
547
+ pip install -r requirements.txt
548
+ ```
549
+
550
+ ### 4. Verify Installation
551
+
552
+ ```bash
553
+ python3 src/cli/main.py --help
554
+ ```
555
+
556
+ You should see the help menu with all available commands.
557
+
558
+ ## Project Dependencies
559
+
560
+ ### Required Packages
561
+
562
+ - **click** (>=8.1.0): Command-line interface framework
563
+ - Used for creating CLI commands
564
+ - Handles argument and option parsing
565
+
566
+ - **rich** (>=13.0.0): Rich text and formatting library
567
+ - Beautiful terminal output with colors
568
+ - Tables, panels, trees for visualization
569
+
570
+ ### Development (Optional)
571
+
572
+ For development and testing:
573
+ ```bash
574
+ pip install pytest # For running tests
575
+ pip install flake8 # For linting
576
+ pip install black # For code formatting
577
+ ```
578
+
579
+ ## Quick Start
580
+
581
+ After installation, try these commands:
582
+
583
+ ### 1. Scan the Repository
584
+
585
+ ```bash
586
+ python3 src/cli/main.py scan .
587
+ ```
588
+
589
+ Shows repository structure and files.
590
+
591
+ ### 2. Query the Codebase
592
+
593
+ ```bash
594
+ python3 src/cli/main.py query "find FlowTracer" .
595
+ ```
596
+
597
+ Searches for code patterns using natural language.
598
+
599
+ ### 3. Trace a Function
600
+
601
+ ```bash
602
+ python3 src/cli/main.py trace execute .
603
+ ```
604
+
605
+ Shows the execution flow of a function.
606
+
607
+ ### 4. Analyze Code Quality
608
+
609
+ ```bash
610
+ python3 src/cli/main.py analyze .
611
+ ```
612
+
613
+ Detects security issues, performance problems, and code smells.
614
+
615
+ ### 5. Generate Documentation
616
+
617
+ ```bash
618
+ python3 src/cli/main.py gendocs .
619
+ ```
620
+
621
+ Auto-generates README, ARCHITECTURE, and SETUP documentation.
622
+
623
+ ## Using with Other Projects
624
+
625
+ To analyze another Python project:
626
+
627
+ ```bash
628
+ python3 src/cli/main.py query "what does this project do" /path/to/project
629
+ python3 src/cli/main.py analyze /path/to/project
630
+ python3 src/cli/main.py trace main /path/to/project
631
+ ```
632
+
633
+ ## Troubleshooting
634
+
635
+ ### ModuleNotFoundError: No module named 'click'
636
+
637
+ **Solution**: Install dependencies
638
+ ```bash
639
+ pip install -r requirements.txt
640
+ ```
641
+
642
+ ### Virtual Environment Not Activated
643
+
644
+ **Solution**: Activate the virtual environment
645
+ ```bash
646
+ source venv/bin/activate # Linux/Mac
647
+ venv\\\\Scripts\\\\activate # Windows
648
+ ```
649
+
650
+ ### Permission Denied on venv/bin/activate
651
+
652
+ **Solution**: Make it executable
653
+ ```bash
654
+ chmod +x venv/bin/activate
655
+ ```
656
+
657
+ ### Python 3 Not Found
658
+
659
+ **Solution**: Use python3 explicitly or check your Python installation
660
+ ```bash
661
+ python3 --version
662
+ which python3
663
+ ```
664
+
665
+ ## Environment Setup for Different Operating Systems
666
+
667
+ ### Linux/macOS
668
+
669
+ ```bash
670
+ # Create venv
671
+ python3 -m venv venv
672
+
673
+ # Activate venv
674
+ source venv/bin/activate
675
+
676
+ # Install dependencies
677
+ pip install -r requirements.txt
678
+
679
+ # Run
680
+ python3 src/cli/main.py --help
681
+ ```
682
+
683
+ ### Windows (PowerShell)
684
+
685
+ ```bash
686
+ # Create venv
687
+ python -m venv venv
688
+
689
+ # Activate venv
690
+ .\\\\venv\\\\Scripts\\\\Activate.ps1
691
+
692
+ # If you get execution policy error, run:
693
+ Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
694
+
695
+ # Install dependencies
696
+ pip install -r requirements.txt
697
+
698
+ # Run
699
+ python src\\\\cli\\\\main.py --help
700
+ ```
701
+
702
+ ### Windows (Command Prompt)
703
+
704
+ ```bash
705
+ # Create venv
706
+ python -m venv venv
707
+
708
+ # Activate venv
709
+ venv\\\\Scripts\\\\activate.bat
710
+
711
+ # Install dependencies
712
+ pip install -r requirements.txt
713
+
714
+ # Run
715
+ python src\\\\cli\\\\main.py --help
716
+ ```
717
+
718
+ ## Next Steps
719
+
720
+ 1. Read README.md for feature overview
721
+ 2. Read ARCHITECTURE.md for technical details
722
+ 3. Start using commands to analyze your code!
723
+
724
+ ## Getting Help
725
+
726
+ - Use `--help` flag with any command for usage information
727
+ - Check command docstrings in `src/cli/main.py`
728
+ - Review module docstrings for implementation details
729
+
730
+ ---
731
+
732
+ Setup guide generated - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
733
+ """
734
+ return content