code-compass-cli 0.1.1
A Python CLI tool for intelligent code analysis and navigation
License: MIT
Requires Python: >=3.7
Keywords: code-analysis, code-navigation, code-quality, static-analysis, cli, python, security, performance

# CodeCompass CLI

<div align="center">

[![Python Version](https://img.shields.io/badge/python-3.7+-blue.svg)](https://www.python.org/downloads/)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Status](https://img.shields.io/badge/status-alpha-yellow.svg)](https://github.com/techwhiz/code-compass)

A powerful Python CLI tool for intelligent code analysis, navigation, and documentation. Navigate and understand your codebase with ease using natural language queries, execution flow tracing, and comprehensive code quality analysis.

[Features](#features) • [Installation](#installation) • [Quick Start](#quick-start) • [Documentation](#documentation) • [Contributing](#contributing)

</div>

---

## Overview

CodeCompass is an intelligent code analysis and navigation CLI tool designed to help developers quickly understand, analyze, and document their codebases. Whether you're onboarding to a new project, performing code reviews, or optimizing performance, CodeCompass provides powerful tools to navigate and inspect code efficiently.

### Key Benefits

- 🔍 **Quick Navigation**: Scan and visualize repository structures instantly
- 🤖 **AI-Powered Q&A**: Ask natural language questions about your code
- 🛡️ **Security Analysis**: Detect vulnerabilities, exposed secrets, and XSS risks
- ⚡ **Performance Insights**: Identify N+1 queries, nested loops, and bottlenecks
- 📊 **Code Quality Metrics**: Catch code smells, duplicates, and design issues
- 🔄 **Execution Flow Tracing**: Visualize function call chains and dependencies
- 📚 **Auto Documentation**: Generate comprehensive project documentation

---

## Features

### 1. **Repository Scanner** (`scan`)
Quickly scan and visualize your entire repository structure with a beautiful tree view.

- Displays directory tree with file counts
- Intelligent exclusion of build artifacts, virtual environments, and cache directories
- Supports projects of any size
- Real-time progress feedback

### 2. **AI-Powered Query Engine** (`query`)
Ask natural language questions about your codebase and get intelligent results.

- Function/class definition search
- Import and dependency analysis
- Keyword-based code search
- General code queries with smart routing
- Supports 14+ programming languages (Python, JavaScript, TypeScript, Java, C++, Go, Rust, PHP, Ruby, Swift, Kotlin, and more)

### 3. **Code Quality Analyzer** (`analyze`)
Comprehensive static analysis with three categories of findings:

**Security Issues**
- SQL injection detection
- Exposed API keys and secrets
- XSS vulnerabilities
- Hardcoded credentials

**Performance Issues**
- N+1 query pattern detection
- Inefficient loop identification
- Nested loop warnings

**Code Smells**
- Long function detection (30+ lines)
- Large class identification (50+ lines)
- Duplicate code detection
- Code structure violations

### 4. **Execution Flow Tracer** (`trace`)
Visualize execution paths and function call chains with dependency mapping.

- Entry point-based flow visualization
- Multi-level call chain tracing
- File and line number references
- Not-found detection for incomplete chains

### 5. **Documentation Generator** (`gendocs`)
Auto-generate comprehensive project documentation from your codebase.

- Project README generation
- Architecture documentation
- Setup and installation guides
- Module and function documentation
- Generates files to `docs/` directory

---

## Installation

### Prerequisites

- Python 3.7 or higher
- pip (Python package manager)
- GitHub Copilot CLI (for enhanced query capabilities)

### Via pipx

```bash
pipx install code-compass-cli
```

### Verify Installation

```bash
codecompass --version
codecompass --help
```

---

## Quick Start

### Basic Usage

CodeCompass is invoked via the `codecompass` command with five main subcommands:

```bash
# Display all available commands
codecompass --help

# Show version
codecompass --version
```

---

## Usage Examples

### 1. Scan Repository Structure

Analyze the structure of your project and visualize the directory tree.

```bash
# Scan current directory
codecompass scan

# Scan a specific directory
codecompass scan /path/to/project

# Scan a subdirectory
codecompass scan ./src
```

**Output Example:**
```
╭───────────────────────────────────╮
│ CodeCompass Repository Scan       │
╰───────────────────────────────────╯
Path: /home/user/myproject
Files found: 42
Directories: 12

📁 myproject
├── 📂 src
│   ├── 🐍 main.py
│   ├── 🐍 utils.py
│   └── 📂 modules
│       └── 🐍 handler.py
├── 📂 tests
│   ├── 🐍 test_main.py
│   └── 🐍 test_utils.py
├── 📝 README.md
└── 📋 requirements.txt

✓ Scan completed successfully
```

---

### 2. Query Code with Natural Language

Ask questions about your codebase in plain English.

```bash
# Find functions or classes
codecompass query "find the main function"
codecompass query "where is the User class defined"

# Search for imports and dependencies
codecompass query "what imports are used for database"
codecompass query "find all Flask dependencies"

# General code search
codecompass query "locate authentication handler"
codecompass query "search for error handling code"

# Search in specific directory
codecompass query "find API endpoints" ./src/api
```

**Output Example:**
```
╭────────────────────╮
│ CodeCompass Query  │
╰────────────────────╯
Query: find the database handler
Path: .

✓ Results found:

[1] src/db/handler.py (Function/Class definition)
  Keyword: handler
  Definitions:
    function at line 15
      DatabaseHandler
      def __init__(self, config: Dict)...
    function at line 23
      execute_query
      def execute_query(self, sql: str)...

Found 1 file(s) with relevant code content.
```

---

### 3. Analyze Code Quality

Detect security vulnerabilities, performance issues, and code smells.

```bash
# Analyze current directory
codecompass analyze

# Analyze specific path
codecompass analyze /path/to/project

# Analyze a single file's directory
codecompass analyze ./src
```

**Output Example:**
```
╭─────────────────────────────────╮
│ CodeCompass Quality Analysis    │
╰─────────────────────────────────╯
Path: .

Analysis Results:
  🔴 Critical: 2
  🟡 Warnings: 5
  🔵 Info: 12
  Total Issues: 19

━ CRITICAL ISSUES ━

  1. SECURITY [bold red]SQL Injection Risk[/bold red]
     📄 src/db.py:45
     query(f"SELECT * FROM users WHERE id={user_id}")
     💡 Suggestion: Use parameterized queries/prepared statements

  2. SECURITY [bold red]Exposed Secret[/bold red]
     📄 src/config.py:12
     api_key = "sk_live_abc123xyz789"
     💡 Suggestion: Move secrets to environment variables

━ WARNINGS ━

  1. PERFORMANCE [yellow]Potential N+1 Query Problem[/yellow]
     📄 src/service.py:78
     for user in users: ...
     💡 Suggestion: Consider using batch queries or joins

...
```

---

### 4. Trace Execution Flow

Visualize how functions call each other and trace execution paths.

```bash
# Trace a function from current directory
codecompass trace "main"

# Trace a method in a specific path
codecompass trace "database_query" ./src

# Trace a class method
codecompass trace "User.authenticate"
```

**Output Example:**
```
╭────────────────────────────╮
│ CodeCompass Flow Trace     │
╰────────────────────────────╯
Entry Point: handle_request
Path: .

✓ Execution flow traced:

handle_request
├── validate_input
│   ├── check_type
│   └── check_length
├── process_data
│   ├── parse_json
│   └── transform
└── save_result
    └── write_database
        └── execute_query

Total function calls: 8
```

---

### 5. Generate Documentation

Automatically create comprehensive project documentation.

```bash
# Generate documentation for current project
codecompass gendocs

# Generate documentation for specific path
codecompass gendocs /path/to/project
```

**Output Example:**
```
╭──────────────────────────────────────╮
│ CodeCompass Documentation Generator  │
╰──────────────────────────────────────╯
Path: .

Generating documentation...

✓ Documentation generated successfully!

Generated Files:
  ✓ README.md (2,450 bytes)
  ✓ ARCHITECTURE.md (5,120 bytes)
  ✓ SETUP.md (1,890 bytes)

📁 Location: /home/user/myproject/docs

File Descriptions:
  • README.md
    Project overview, features, and quick start guide
  • ARCHITECTURE.md
    Detailed architecture, module descriptions, and data flow diagrams
  • SETUP.md
    Installation instructions for different operating systems

Next Steps:
  • Review the generated documentation in: docs/
  • Use the documentation for onboarding and reference
  • Share with team members for project understanding
```

---

## Requirements

### Core Dependencies

- **click** (≥8.1.0) - Command-line interface toolkit
- **rich** (≥13.0.0) - Beautiful terminal output and formatting

### Optional Dependencies

**Development:**
```
pytest>=7.0
pytest-cov>=3.0
flake8>=4.0
black>=22.0
mypy>=0.950
```

**Documentation:**
```
sphinx>=4.0
sphinx-rtd-theme>=1.0
```

### System Requirements

- **Operating System**: Linux, macOS, or Windows
- **Python**: 3.7, 3.8, 3.9, 3.10, 3.11, or 3.12
- **Disk Space**: ~50MB for installation

### GitHub Copilot CLI Integration

For enhanced query capabilities, install [GitHub Copilot CLI](https://github.com/cli/cli):

```bash
# macOS
brew install gh

# Linux (Ubuntu/Debian)
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null
sudo apt update
sudo apt install gh

# Windows
choco install gh
```

---

## Configuration

CodeCompass works out of the box with sensible defaults. No configuration file is required.

### Customization Options

You can customize behavior through command-line flags:

```bash
# Limit files displayed in tree output
codecompass scan --max-files 200

# Specify analysis depth
codecompass analyze --depth 5

# Set output format (future versions)
codecompass query "find main" --format json
```

---

## Output Formats

All commands produce beautifully formatted terminal output using the Rich library:

- **Colors and Styling**: Syntax highlighting and semantic coloring for readability
- **Tables and Trees**: Structured visualization of hierarchical data
- **Progress Indicators**: Real-time feedback for long-running operations
- **Status Symbols**: Clear indicators (✓, ✗, ⚠, 🔴, etc.) for quick scanning

---

## Common Use Cases

### 1. Onboarding to a New Project
```bash
codecompass scan
codecompass query "what are the main entry points"
codecompass gendocs
```

### 2. Security Audit
```bash
codecompass analyze
# Look for critical and warning issues
```

### 3. Performance Review
```bash
codecompass analyze
# Focus on performance category issues
```

### 4. Understanding Complex Functions
```bash
codecompass trace "function_name"
codecompass query "what does this function do"
```

### 5. Dependency Analysis
```bash
codecompass query "find all imports from database module"
codecompass query "where is this dependency used"
```

---

## Contributing

We welcome contributions! Please follow these guidelines:

### Getting Started

1. **Fork the Repository**
   ```bash
   git clone https://github.com/YOUR_USERNAME/code-compass.git
   cd code-compass
   ```

2. **Create a Virtual Environment**
   ```bash
   python -m venv venv
   source venv/bin/activate  # On Windows: venv\Scripts\activate
   ```

3. **Install Development Dependencies**
   ```bash
   pip install -e ".[dev]"
   ```

### Development Workflow

1. **Create a Feature Branch**
   ```bash
   git checkout -b feature/your-feature-name
   ```

2. **Make Your Changes**
   - Follow the existing code style
   - Add docstrings to functions and classes
   - Keep functions focused and testable
   - Add type hints where appropriate

3. **Run Tests**
   ```bash
   pytest
   pytest --cov=src  # With coverage
   ```

4. **Format Code**
   ```bash
   black src/ tests/
   flake8 src/ tests/
   mypy src/
   ```

5. **Commit Your Changes**
   ```bash
   git add .
   git commit -m "feat: description of your feature"
   ```

6. **Push and Create a Pull Request**
   ```bash
   git push origin feature/your-feature-name
   ```

### Contribution Areas

- **Bug Fixes**: Fix issues and improve stability
- **New Features**: Add support for more languages, analysis types, or query capabilities
- **Documentation**: Improve README, inline comments, or usage examples
- **Performance**: Optimize analysis speed and reduce memory usage
- **Testing**: Increase test coverage and add edge case tests

### Code Style

- Follow PEP 8 conventions
- Use meaningful variable names
- Add docstrings to all public functions
- Keep functions under 30 lines when possible
- Use type hints for better code clarity

### Pull Request Process

1. Update documentation if needed
2. Add tests for new functionality
3. Ensure all tests pass: `pytest`
4. Ensure code is formatted: `black src/`
5. Submit PR with clear description of changes

### Reporting Issues

When reporting bugs, please include:
- Python version and OS
- CodeCompass version
- Steps to reproduce
- Expected vs actual behavior
- Relevant code snippets or error messages

---

## Project Structure

```
code-compass/
├── src/
│   ├── cli/
│   │   └── main.py           # CLI entry point
│   ├── scanner/
│   │   └── repo_scanner.py   # Repository scanning
│   ├── query/
│   │   └── copilot_query.py  # Natural language queries
│   ├── quality/
│   │   └── analyzer.py       # Code quality analysis
│   ├── visualizer/
│   │   └── flow_tracer.py    # Execution flow visualization
│   └── docs/
│       └── doc_generator.py  # Documentation generation
├── tests/                     # Test suite
├── docs/                      # Generated documentation
├── pyproject.toml            # Project configuration
├── setup.py                  # Setup script
├── requirements.txt          # Dependencies
└── README.md                 # This file
```

---

## Supported Languages

CodeCompass can analyze code in the following languages:

- Python (.py)
- JavaScript (.js, .jsx)
- TypeScript (.ts, .tsx)
- Java (.java)
- C/C++ (.c, .cpp, .h)
- PHP (.php)
- Ruby (.rb)
- Go (.go)
- Rust (.rs)
- SQL (.sql)
- Swift (.swift)
- Kotlin (.kt)
- And more...

---

## Limitations

- **Analysis Scope**: Currently analyzes code structure and patterns; does not execute code
- **Language Features**: Pattern matching may not catch all edge cases in dynamic languages
- **Performance**: Very large codebases (100,000+ files) may take longer to analyze
- **Dependencies**: External dependency analysis is limited to import statements

---

## Troubleshooting

### Common Issues

**"Command not found: codecompass"**
- Ensure you've installed the package: `pip install code-compass-cli`
- Check that it's in your PATH: `which codecompass`
- Try reinstalling: `pip install --force-reinstall code-compass-cli`

**"Permission denied" errors**
- Run with appropriate permissions: `sudo pip install ...` (not recommended)
- Use a virtual environment instead: `python -m venv venv && source venv/bin/activate`

**No results from queries**
- Try broader search terms
- Check file extensions are supported
- Ensure files aren't in excluded directories (venv, .git, etc.)

**Slow analysis on large projects**
- Exclude unnecessary directories
- Consider analyzing subdirectories separately
- Check for disk I/O bottlenecks

---

## License

CodeCompass is released under the **MIT License**. See [LICENSE](LICENSE) file for details.

---

## Roadmap

Future versions will include:

- 🚀 **Interactive Mode**: REPL for continuous querying
- 📊 **JSON Export**: Machine-readable output formats
- 🔗 **Integration APIs**: Integration with IDEs and CI/CD pipelines
- 🌐 **Multi-Repository Support**: Analyze across multiple repos
- 🤖 **ML-Based Analysis**: Machine learning for smarter insights
- ⚙️ **Configuration Files**: Support for .codecompass config files
- 🧪 **Test Coverage**: Automatic test coverage analysis

---

## Support

For questions, bug reports, or feature requests:

- 📝 **Issues**: [GitHub Issues](https://github.com/techwhiz/code-compass/issues)
- 💬 **Discussions**: [GitHub Discussions](https://github.com/techwhiz/code-compass/discussions)
- 📧 **Email**: support@codecompass.dev

---

## Acknowledgments

Built with:
- [Click](https://click.palletsprojects.com/) - CLI framework
- [Rich](https://rich.readthedocs.io/) - Terminal output
- [Python AST](https://docs.python.org/3/library/ast.html) - Code analysis

---

<div align="center">

Made with ❤️ by the CodeCompass Team

[⭐ Star us on GitHub](https://github.com/techwhiz/code-compass) | [🐛 Report Issues](https://github.com/techwhiz/code-compass/issues) | [💡 Request Features](https://github.com/techwhiz/code-compass/discussions)

</div>