Metadata-Version: 2.4
Name: hython-cli
Version: 0.1.7
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Software Development :: Build Tools
Classifier: Environment :: Console
License-File: LICENSE
Summary: Zero-Interruption Python Automation Engine
Home-Page: https://github.com/Harsha-Fernando/hython
Author: Hython Labs
License: MIT
Requires-Python: >=3.8
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Changelog, https://hython.dev/changelog/
Project-URL: Documentation, https://hython.dev/docs/
Project-URL: Homepage, https://hython.dev
Project-URL: Repository, https://github.com/hython-labs/hython

# Hython ⚡
### Zero-Interruption Python Automation

> **"Don't ask the developer to fix something that Hython can safely fix itself.  
> And after fixing it: Tell the developer what happened, without making them participate in the process."**

Hython is an automation-first Python environment orchestrator and developer workflow engine. It completely eliminates the friction of managing virtual environments, installing missing dependencies, matching Python versions, configuring IDE settings, and answering routine `[Y/n]` prompts.

📖 **This README serves as the complete, comprehensive guide and documentation for Hython.**

---

## The Mental Model

```text
Developer intent (`hython` or `hython app.py`)
       ↓
Hython inspects project & requirements
       ↓
Hython resolves environment & runtimes
       ↓
Hython fixes safe problems automatically (auto-installs, auto-migrates, auto-imports)
       ↓
Hython runs the project & reports concisely
```

The developer should think:
> *I have a Python project. I want to build and run it. `hython`. That's it.*

---

## Key Features

- 🚫 **No Routine Prompts:** Never stops execution for safe, deterministic actions like creating `.venv` or installing missing dependencies.
- ⚡ **Live Auto-Import Watcher (`hython watch`):** Monitors your code in real-time. Whenever you save a file in VS Code or Cursor, Hython detects unbound symbols (e.g. `JsonResponse`, `requests`, `models`), auto-installs any missing packages, and inserts the import statements into your code automatically.
- 🛠️ **Zero-Boilerplate Project Scaffolding (`hython new`):** Create production-ready Django, FastAPI, Flask, or script projects in 1 command with pre-warmed virtualenvs, `.env`, `.gitignore`, and IDE configs.
- 🩺 **Self-Healing Environments:** If `.venv` is missing, corrupted, or out-of-sync, Hython recreates or synchronizes it seamlessly.
- 📦 **Dynamic Import Healing:** Intercepts `ModuleNotFoundError` during both pre-flight static analysis and runtime execution. It maps module names to PyPI packages (e.g. `yaml` → `PyYAML`, `dateutil` → `python-dateutil`, `PIL` → `Pillow`, `psycopg2` → `psycopg2-binary`) and installs them automatically.
- 🧠 **Automatic IDE & Framework IntelliSense:** Instantly writes `.vscode/settings.json`, `.vscode/extensions.json`, and `pyrightconfig.json` with Pylance depth 5 package indexing and type stubs (`django-types`). Autocomplete and auto-import proposals work lively as you type.
- 🗄️ **Pre-Flight Django Auto-Migrations:** Detects unmade model changes via dry-run check, automatically generates migrations, and applies them before server or test launch.
- 🔌 **Auto-Wiring Django Apps:** When you run `hython manage.py startapp <app>`, Hython automatically registers the new app in `INSTALLED_APPS` inside `settings.py`.
- 🌐 **Instant Free-Port Routing:** Automatically checks if ports (8000, 5000, 8888) are busy (e.g. macOS AirPlay Receiver on port 5000) and smoothly shifts to a free port without crashing.
- 🛡️ **One-Command CORS (`hython cors`):** Configures CORS middleware for Django, FastAPI, or Flask in one command.
- 👤 **Instant Dev Superuser (`hython superuser`):** Provisions `admin`/`admin` development credentials with zero prompts.
- 🧪 **Universal Test Runner (`hython test`):** Routes Django to `manage.py test` and non-Django to `pytest` (auto-installs if missing).
- 🐳 **Production Docker Generator (`hython docker`):** Generates optimized, security-hardened `Dockerfile` and `.dockerignore`.
- 🎨 **Automated Code Formatting (`hython fmt`):** Cleans, formats, and sorts imports according to PEP 8 and framework rules using ultra-fast Ruff.

---

## Quick Command Reference

```bash
# Project Creation & Initialization
hython new django my_store     # Scaffolds Django with .venv, .env, and VS Code configs
hython new fastapi my_api      # Scaffolds FastAPI with Uvicorn and Pydantic
hython new flask my_web        # Scaffolds Flask microservice
hython init                    # Initializes project in current directory

# Live Auto-Importing & IDE Assistance
hython watch                   # Real-time watcher: injects missing imports on save
hython fix                     # One-command project-wide auto-import healing

# Running & Self-Healing Execution
hython                         # Auto-detects framework and runs dev server
hython script.py               # Runs script with automatic dependency resolution
hython test                    # Runs test suite (manage.py test or pytest)

# Developer Tools
hython add <package>           # Adds dependency to manifest and installs
hython remove <package>        # Removes dependency and uninstalls cleanly
hython cors                    # Enables CORS for frontend integration
hython superuser               # Creates dev superuser (admin/admin)
hython rollback <app>          # Reverts latest migration and deletes file
hython export                  # Exports dependencies to requirements.txt
hython docker                  # Generates production Dockerfile & .dockerignore
hython doctor                  # Runs full project & environment health audit
hython fmt                     # Formats code to PEP 8 standards
hython sync                    # Synchronizes virtual environment with manifest
hython status                  # Shows detected project and runtime status
```

---

## 1. Overview & The Zero-Interruption Mental Model

Every Python developer spends significant time on non-coding friction:
- Manually creating and activating virtual environments (`python -m venv .venv`, `source .venv/bin/activate`).
- Encountering `ModuleNotFoundError: No module named 'yaml'` because the package is named `PyYAML` on PyPI, or `PIL` because it's `Pillow`.
- Forgetting to register new Django apps in `INSTALLED_APPS` inside `settings.py`.
- Forgetting to run `makemigrations` and `migrate` before testing or launching the server.
- Dealing with port collisions when macOS AirPlay blocks port 5000 or an old server blocks port 8000.
- Opening VS Code only to see red squigglies because the IDE doesn't know which interpreter to use, type stubs are missing, or Pylance auto-import completions are turned off.
- Context-switching to the top of the file every few minutes just to type `import ...` or `from ... import ...`.

**Hython eliminates all of this.**

```text
Traditional Workflow:
Write Code → Run → Crash (Missing venv/package) → Activate venv → Pip install →
Run → Crash (Forgotten migration) → makemigrations → migrate →
Run → Crash (Port 8000 busy) → kill process → Run

Hython Workflow:
hython new django my_store
code my_store
hython
↳ Isolated venv resolved
↳ Missing packages auto-installed
↳ Migrations auto-detected & applied
↳ Free port resolved (e.g., 8001 if 8000 busy)
↳ Server running with interactive dashboard!
```

---

## 2. Quick Reference: All Hython Commands

| Command | Description |
| :--- | :--- |
| `hython` | Auto-detects the project type (Django, FastAPI, Flask, Script) and runs it with self-healing |
| `hython new [type] [name]` | Scaffolds a new project (`django`, `fastapi`, `flask`, `script`) with warm `.venv` & IDE configuration |
| `hython init [type]` | Initializes a project in the current directory with zero boilerplate |
| `hython watch` | **Live Watcher:** Monitors files on save; auto-resolves, auto-installs, and auto-imports missing modules |
| `hython fix` / `hython imports` | Scans all project files at once and injects all missing import statements |
| `hython add <package>` | Adds dependency to manifest (`pyproject.toml` / `requirements.txt`) and installs into `.venv` |
| `hython remove <package>` | Removes dependency from manifest and uninstalls cleanly from `.venv` |
| `hython test [args...]` | Universal test runner: routes Django to `manage.py test` and others to `pytest` (auto-installs if missing) |
| `hython cors` | Enables CORS with 1 command (configures middleware for Django, FastAPI, or Flask) |
| `hython superuser` | Instant dev admin (`admin`/`admin`) for Django projects with zero prompts |
| `hython rollback <app>` | Rolls back latest migration and deletes orphaned migration files |
| `hython export` | Exports frozen dependencies to production-locked `requirements.txt` |
| `hython docker` | Generates optimized production `Dockerfile` and `.dockerignore` tailored to the framework |
| `hython doctor` | Diagnostic audit of Python runtimes, virtual environments, manifests, ports, and packages |
| `hython fmt` | Formats code with PEP 8 and framework rules using fast Ruff integration |
| `hython sync` | Reconciles and synchronizes virtual environment dependencies with the project manifest |
| `hython status` | Displays detected project root, entrypoint, active Python runtime, and environment status |

---

## 3. Workflow 1: Django with Hython

### Step 1: Scaffold the Project
To start a new Django project:
```bash
hython new django bookstore
cd bookstore
```
**What Hython does automatically:**
1. Generates clean project structure (`manage.py`, `bookstore/settings.py`, `bookstore/urls.py`, `bookstore/wsgi.py`).
2. Creates an isolated `.venv` with `django`, `psycopg2-binary`, and `djangorestframework`.
3. Auto-generates a secure 50-character `SECRET_KEY` and sets up dynamic `.env` and `.env.example`.
4. Pre-configures `.vscode/settings.json`, `.vscode/extensions.json`, and `pyrightconfig.json` with Pylance indexing and `django-stubs`.

---

### Step 2: Open in Your IDE (Instant IntelliSense)
```bash
code .
```
- Open `bookstore/settings.py` or any Python file.
- VS Code immediately connects to `${workspaceFolder}/.venv/bin/python`.
- Pylance indexes all Django ORM symbols with depth 5.
- As you type `HttpResponse`, `JsonResponse`, `models.CharField`, or `render`, rich docstrings and autocompletions pop up instantly.

---

### Step 3: Start the Live Auto-Import Watcher
In a secondary terminal window (or integrated terminal):
```bash
hython watch
```
Now, whenever you write code in any `.py` file, you never have to scroll up to add import statements.
For example, create `books/views.py`:
```python
def book_detail(request, pk):
    book = get_object_or_404(Book, pk=pk)
    resp = requests.get(f"https://api.bookratings.com/{pk}")
    return JsonResponse({"title": book.title, "rating": resp.json()})
```
Hit **Save** (`Cmd+S` or `Ctrl+S`).
Hython immediately outputs:
```text
⚡ [Hython Watch] Auto-imported 'from django.shortcuts import get_object_or_404' into books/views.py
⚡ [Hython Watch] Auto-imported 'from django.http import JsonResponse' into books/views.py
✓ Detected missing dependency 'requests' for symbol 'requests'
→ Installing requests...
✓ Installed requests
⚡ [Hython Watch] Auto-imported 'import requests' into books/views.py
```
The file in your editor automatically updates with the correct imports inserted at the top.

---

### Step 4: Create a New Django App
```bash
hython manage.py startapp books
```
**Hython Zero-Interruption Action:**
Hython automatically detects that a new Django app named `books` was created and **registers `'books'` in `INSTALLED_APPS` inside `settings.py` automatically**. You do not need to open `settings.py` to add it manually.

---

### Step 5: Models and Auto-Migrations
Add a model in `books/models.py`:
```python
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=6, decimal_places=2)
```
Now run your project:
```bash
hython
```
**Hython Pre-Flight Migration Check:**
Hython runs a pre-flight dry-run check. It detects that `Book` has unmade model changes:
```text
✓ Detected unmade model changes in 'books'
→ Generating migrations...
✓ Migrations created: books/migrations/0001_initial.py
→ Applying pending migrations...
✓ Applied 1 pending migration
```
It applies the migration, checks port 8000, and displays the **Interactive Server Dashboard**:
```text
⚡ Hython ── Django Server
────────────────────────────────────────────────────────────
  🌐 Local URL:      http://127.0.0.1:8000/
  🛠️ Admin Panel:    http://127.0.0.1:8000/admin/
  📦 Runtime:        Python 3.12 (in .venv)
  📊 Status:         Ready & Listening
────────────────────────────────────────────────────────────
```

---

### Step 6: Instant Dev Superuser
Want to inspect the Django Admin without filling out interactive prompts?
```bash
hython superuser
```
Output:
```text
✓ Dev superuser ready: username 'admin', password 'admin' (http://127.0.0.1:8000/admin/)
```
Log in to `http://127.0.0.1:8000/admin/` with credentials `admin` / `admin`.

---

### Step 7: Enable CORS for Frontend Integration (React, Next.js, Vue)
Connecting a frontend? Run:
```bash
hython cors
```
**Hython Zero-Interruption Action:**
1. Installs `django-cors-headers`.
2. Adds `'corsheaders'` to `INSTALLED_APPS` in `settings.py`.
3. Inserts `corsheaders.middleware.CorsMiddleware` at the top of `MIDDLEWARE`.
4. Sets `CORS_ALLOW_ALL_ORIGINS = True`.

---

### Step 8: Running Tests
```bash
hython test
```
Routes automatically to `manage.py test`.

---

### Step 9: Database Switching (PostgreSQL / MySQL / SQLite)
Hython configures dynamic database parsing in `settings.py`. To switch from SQLite to PostgreSQL:
Simply edit `.env`:
```ini
DATABASE_URL=postgres://user:password@localhost:5432/bookstore_db
```
When you run `hython`, Hython automatically parses the URL, installs `psycopg2-binary` if missing, and connects to Postgres.

---

## 4. Workflow 2: FastAPI with Hython

### Step 1: Scaffold FastAPI Project
```bash
hython new fastapi task_service
cd task_service
```
**What Hython does automatically:**
- Sets up `pyproject.toml` with `fastapi`, `uvicorn[standard]`, and `pydantic`.
- Scaffolds `main.py` with standard root endpoint.
- Provisions `.venv` and configures VS Code settings with Pylance type stubs.

---

### Step 2: Live Development & Auto-Imports
Start the live watcher or run the server:
```bash
hython
```
Output:
```text
✓ FastAPI project detected
⚡ Hython ── FastAPI Server
────────────────────────────────────────────────────────────
  🌐 API Root:       http://127.0.0.1:8000/
  📚 Interactive Docs: http://127.0.0.1:8000/docs
  📖 ReDoc:          http://127.0.0.1:8000/redoc
  🔄 Auto-Reload:    Enabled
────────────────────────────────────────────────────────────
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```

Now open `main.py` and write your routes:
```python
@app.post("/items")
def create_item(name: str, price: float):
    if price < 0:
        raise HTTPException(status_code=400, detail="Invalid price")
    return {"name": name, "price": price}
```
If `HTTPException` is not imported, running `hython fix` or having `hython watch` active immediately auto-injects:
```python
from fastapi import HTTPException
```

---

### Step 3: Add CORS to FastAPI
```bash
hython cors
```
Injects `CORSMiddleware` with wildcard origin permissions directly into `main.py`.

---

### Step 4: Testing with Pytest
```bash
hython test
```
FastAPI has no built-in test runner. Hython detects this, auto-installs `pytest` and `httpx`, and executes the test suite.

---

## 5. Workflow 3: Flask with Hython

### Step 1: Scaffold Flask Project
```bash
hython new flask blog_app
cd blog_app
```

### Step 2: Run Development Server
```bash
hython
```
**Hython Port Collision Healing:**
Flask defaults to port 5000. On macOS Monterey and later, Apple's AirPlay Receiver occupies port 5000.
Hython tests port 5000; if occupied, it automatically shifts to the next available port (e.g., 5001) without crashing or failing.

### Step 3: Live Auto-Imports for Flask
In `app.py`:
```python
@app.route("/dashboard")
def dashboard():
    if "user" not in session:
        return redirect(url_for("index"))
    return render_template("dashboard.html")
```
Hython's auto-importer resolves and injects:
```python
from flask import render_template, redirect, url_for, session
```

---

## 6. Workflow 4: Pure Python Scripts with Hython

You have a standalone script, e.g. `scrape.py`:
```python
# scrape.py
resp = requests.get("https://news.ycombinator.com")
soup = BeautifulSoup(resp.text, "html.parser")
for item in soup.select(".titleline > a")[:5]:
    print(item.text)
```
Notice:
1. No virtualenv exists.
2. `requests` is not installed.
3. `BeautifulSoup` requires `beautifulsoup4` (a different package name on PyPI).
4. No imports are written at the top.

Run with Hython:
```bash
hython scrape.py
```
**What Hython does in seconds:**
```text
✓ Created isolated project environment (.venv)
⚡ [Hython] Auto-imported 'import requests' into scrape.py
⚡ [Hython] Auto-imported 'from bs4 import BeautifulSoup' into scrape.py
✓ Detected missing dependency: requests
→ Installing requests...
✓ Detected missing dependency: bs4
→ Resolving module 'bs4' -> package 'beautifulsoup4'
→ Installing beautifulsoup4...
✓ Environment synchronized

Show HN: A zero-interruption Python orchestrator
Building an autonomous database
...
```
No manual virtual environment setup. No PyPI name lookups. It just works.

---

## 7. The Live IDE IntelliSense & Auto-Import Engine

### How Hython Configures VS Code / Cursor / Pyright
When you create a project or run `hython`, it writes:

#### 1. `.vscode/settings.json`
```json
{
  "python.defaultInterpreterPath": "${workspaceFolder}/.venv/bin/python",
  "python.terminal.activateEnvironment": true,
  "python.languageServer": "Pylance",
  "python.analysis.indexing": true,
  "python.analysis.autoImportCompletions": true,
  "python.analysis.autoSearchPaths": true,
  "python.analysis.diagnosticMode": "workspace",
  "python.analysis.packageIndexDepths": [
    { "name": "django", "depth": 5, "includeAllSymbols": true },
    { "name": "rest_framework", "depth": 5, "includeAllSymbols": true },
    { "name": "fastapi", "depth": 5, "includeAllSymbols": true },
    { "name": "pydantic", "depth": 5, "includeAllSymbols": true },
    { "name": "flask", "depth": 5, "includeAllSymbols": true },
    { "name": "requests", "depth": 3, "includeAllSymbols": true }
  ],
  "editor.quickSuggestions": {
    "other": "on",
    "comments": "off",
    "strings": "on"
  },
  "editor.suggestOnTriggerCharacters": true,
  "editor.acceptSuggestionOnEnter": "on",
  "editor.tabCompletion": "on",
  "editor.formatOnSave": true
}
```

#### 2. `.vscode/extensions.json`
Recommends `ms-python.python`, `ms-python.vscode-pylance`, and `charliermarsh.ruff`.

#### 3. `pyrightconfig.json`
Sets `"autoImportCompletions": true` and links directly to `.venv`.

### Live In-Editor Experience:
1. **Auto-Import Completion while Typing:** When typing `HttpRes...`, Pylance displays `HttpResponse (Auto-import from django.http)`. Selecting it completes the symbol and writes the import statement at the top.
2. **Auto-Import Watcher (`hython watch`):** If you paste code, type quickly without choosing from dropdowns, or write `models.CharField`, saving the file triggers Hython to analyze the AST, install any missing package, and insert the import statement into the file automatically.

---

## 8. Production & Tooling Workflows

### Export Locked Dependencies
```bash
hython export
```
Exports all frozen environment packages to `requirements.txt`.

### Generate Production Dockerfile
```bash
hython docker
```
Generates a production-ready, security-hardened `Dockerfile` and `.dockerignore` customized to the detected framework (Gunicorn for Django/Flask, Uvicorn for FastAPI).

### Environment & Health Diagnostics
```bash
hython doctor
```
Audits Python interpreter compatibility, virtual environment health, manifest consistency, port status, and framework configuration.

### Roll Back Migrations Cleanly
```bash
hython rollback books
```
Reverts the last applied migration for the `books` app and deletes any orphaned migration files.

---

## 9. Developer Comparison: Traditional Python vs. Hython

| Task / Scenario | Traditional Python Workflow | The Hython Workflow |
| :--- | :--- | :--- |
| **New Project Setup** | `python -m venv .venv`<br>`source .venv/bin/activate`<br>`pip install django`<br>`django-admin startproject myapp` | `hython new django myapp`<br>*(Venv, dependencies, settings, .env, and IDE configured in 1 step)* |
| **Opening in VS Code** | Manually select interpreter via Command Palette;<br>fix red squigglies; configure settings manually | Open editor (`code myapp`).<br>Interpreter and Pylance type stubs work immediately |
| **Missing Module** | Script crashes with `ModuleNotFoundError: yaml`<br>Manual lookup → `pip install PyYAML` | Hython detects, maps `yaml` → `PyYAML`, installs, and continues execution |
| **Writing Code without Imports** | Stop typing, scroll to line 1, write `import ...`, scroll back down | Write code freely.<br>`hython watch` injects imports into your code on save |
| **Django Migrations** | `python manage.py makemigrations`<br>`python manage.py migrate` | `hython`<br>*(Detects unmade changes, generates, and applies migrations automatically)* |
| **New Django App** | `python manage.py startapp blog`<br>Open `settings.py` → edit `INSTALLED_APPS` | `hython manage.py startapp blog`<br>*(Hython auto-registers app in `INSTALLED_APPS`)* |
| **Port Conflicts** | `Error: Port 8000 already in use`<br>Find PID with `lsof -i :8000` → `kill -9 <PID>` | Detects occupied port and shifts to available port (e.g. 8001) automatically |
| **CORS Enablement** | Look up package name, edit settings, configure middleware | `hython cors` |
| **Dev Superuser** | `python manage.py createsuperuser`<br>Answer interactive prompts for username, email, password | `hython superuser`<br>*(Creates `admin`/`admin` instantly)* |
| **Testing** | Check which runner is used (`pytest` or `manage.py test`), activate venv, run command | `hython test` |

---

## Summary
Hython is designed to let you focus entirely on building your application. Whether you are building an API with **FastAPI**, a full-stack platform with **Django**, a microservice with **Flask**, or writing a **Python script**, Hython manages your environment, dependencies, IDE configuration, and runtime health completely in the background.

---

## License

MIT License — Hython Labs


