Metadata-Version: 2.4
Name: django-deadcode
Version: 0.2.3
Summary: A Django dead code analysis tool that tracks relationships between templates, URLs, and views
Author-email: Your Name <your.email@example.com>
License: MIT
Project-URL: Homepage, https://github.com/nanorepublica/django-deadcode
Project-URL: Repository, https://github.com/nanorepublica/django-deadcode
Project-URL: Issues, https://github.com/nanorepublica/django-deadcode/issues
Keywords: django,dead-code,static-analysis,code-quality
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: Django
Classifier: Framework :: Django :: 4.2
Classifier: Framework :: Django :: 5.0
Classifier: Framework :: Django :: 5.1
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Quality Assurance
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: Django>=4.2
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-django>=4.5; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.0; extra == "dev"
Requires-Dist: django-stubs>=4.2; extra == "dev"
Dynamic: license-file

# Django Dead Code

We find your buried bones (or code)!

Note: this is currently an AI experiment. There has been zero code written or reviewed by a human so far! Use with caution!

[![PyPI version](https://badge.fury.io/py/django-deadcode.svg)](https://badge.fury.io/py/django-deadcode)
[![CI](https://github.com/nanorepublica/django-deadcode/actions/workflows/ci.yml/badge.svg)](https://github.com/nanorepublica/django-deadcode/actions/workflows/ci.yml)
[![Python versions](https://img.shields.io/pypi/pyversions/django-deadcode.svg)](https://pypi.org/project/django-deadcode/)
[![Django versions](https://img.shields.io/pypi/djversions/django-deadcode.svg)](https://pypi.org/project/django-deadcode/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A Django dead code analysis tool that tracks relationships between templates, URLs, and views to help identify and remove unused code.

## Features

- **Template Analysis**: Extract URL references from Django templates (href attributes and `{% url %}` tags)
- **URL Pattern Discovery**: Analyze all URL patterns defined in your Django project
- **View Tracking**: Identify which templates are used by which views
- **Python Code Analysis**: Detect `reverse()` and `redirect()` URL references in Python code
- **Relationship Mapping**: Track template inheritance (extends/includes) and relationships
- **Multiple Output Formats**: Console, JSON, and Markdown reports
- **Django Native**: Uses Django's management command structure for seamless integration

## Installation

```bash
pip install django-deadcode
```

Or install from source:

```bash
git clone https://github.com/nanorepublica/django-deadcode.git
cd django-deadcode
pip install -e .
```

## Setup

Add `django_deadcode` to your `INSTALLED_APPS`:

```python
INSTALLED_APPS = [
    # ... other apps
    'django_deadcode',
]
```

## Usage

### Basic Usage

Run the analysis on your Django project:

```bash
python manage.py finddeadcode
```

This will analyze your entire Django project and output a report to the console.

### Output Formats

**Console output (default):**
```bash
python manage.py finddeadcode
```

**JSON output:**
```bash
python manage.py finddeadcode --format json
```

**Markdown output:**
```bash
python manage.py finddeadcode --format markdown
```

### Save Report to File

```bash
python manage.py finddeadcode --format json --output report.json
```

### Analyze Specific Apps

```bash
python manage.py finddeadcode --apps myapp otherapp
```

### Custom Template Directory

```bash
python manage.py finddeadcode --templates-dir /path/to/templates
```

## What It Detects

### Unreferenced URL Patterns

URL patterns that are defined in `urls.py` but never referenced in templates or Python code:

```python
# urls.py - This URL is defined
path('old-feature/', views.old_feature, name='old_feature'),

# But no template references it with {% url 'old_feature' %}
# And no Python code uses reverse('old_feature')
```

### Python Code URL References

Detects URL references in Python code via:

```python
from django.shortcuts import redirect
from django.urls import reverse, reverse_lazy
from django.http import HttpResponseRedirect

# All of these are detected and marked as "referenced"
def my_view(request):
    return redirect('url-name')

def another_view(request):
    url = reverse('url-name')
    return HttpResponseRedirect(url)

class MyView(UpdateView):
    success_url = reverse_lazy('url-name')
```

### Unused Templates

Templates that exist but are not referenced by any view:

```python
# views.py - No view renders 'unused_template.html'

# But the file templates/unused_template.html exists
```

### Template Relationships

Tracks which templates include or extend other templates:

```django
{# base.html is extended by page.html #}
{% extends 'base.html' %}

{# header.html is included in base.html #}
{% include 'partials/header.html' %}
```

## Example Output

```
================================================================================
Django Dead Code Analysis Report
================================================================================

SUMMARY
--------------------------------------------------------------------------------
Total URL patterns: 45
Total templates analyzed: 32
Total views found: 28
Unreferenced URLs: 5
Unused templates: 3

UNREFERENCED URL PATTERNS
--------------------------------------------------------------------------------
These URL patterns are defined but never referenced in templates:

  • old_feature
    View: myapp.views.old_feature
    Pattern: /old-feature/

  • deprecated_api
    View: myapp.api.deprecated_endpoint
    Pattern: /api/v1/deprecated/

POTENTIALLY UNUSED TEMPLATES
--------------------------------------------------------------------------------
These templates are not directly referenced by views (may be included/extended):

  • old_landing.html
  • unused_email.html
  • legacy_form.html
```

## How It Works

1. **Template Analysis**: Scans all template files for:
   - `{% url 'name' %}` tags
   - `href="/path/"` attributes (internal links)
   - `{% include 'template' %}` tags
   - `{% extends 'template' %}` tags

2. **URL Pattern Discovery**: Inspects Django's URL configuration to find all defined URL patterns and their names

3. **View Analysis**: Parses Python files to find:
   - `render(request, 'template.html')` calls
   - `template_name = 'template.html'` in class-based views

4. **Reverse/Redirect Analysis**: Uses AST parsing to detect:
   - `reverse('url-name')` calls
   - `reverse_lazy('url-name')` calls
   - `redirect('url-name')` calls
   - `HttpResponseRedirect(reverse('url-name'))` patterns
   - Dynamic URL patterns (f-strings, concatenation) are flagged for manual review

5. **Relationship Mapping**: Connects templates ↔ URLs ↔ views to identify dead code

## Limitations

- **Static Analysis Only**: Does not execute code or track runtime behavior
- **Dynamic Templates**: Cannot detect templates loaded with dynamic names (e.g., `render(request, f'{variable}.html')`)
- **Dynamic URLs**: Cannot automatically detect URLs generated with f-strings or concatenation (but flags them for manual review)
- **Indirect Usage**: May flag templates used only through includes/extends as "unused"
- **Third-party Packages**: Analyzes your code only, not installed packages

## Development

### Setup Development Environment

```bash
# Clone the repository
git clone https://github.com/nanorepublica/django-deadcode.git
cd django-deadcode

# Install development dependencies
pip install -e ".[dev]"
```

### Running Tests

```bash
pytest
```

With coverage:

```bash
pytest --cov=django_deadcode --cov-report=html
```

### Code Quality

```bash
# Linting
ruff check .

# Type checking
mypy django_deadcode
```

## Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details.

## License

MIT License - see [LICENSE](LICENSE) for details.

## Credits

Inspired by the blog post: https://softwarecrafts.co.uk/100-words/day-71

## Roadmap

See [agent-os/product/roadmap.md](agent-os/product/roadmap.md) for the full development roadmap.

### Planned Features

- Confidence scoring for dead code detection
- Multi-app analysis with cross-app relationship tracking
- Django admin integration detection
- HTML report generation with interactive UI
- CI/CD integration helpers
- IDE plugins (VS Code, PyCharm)

## Support

- **Issues**: https://github.com/nanorepublica/django-deadcode/issues
- **Discussions**: https://github.com/nanorepublica/django-deadcode/discussions
