Metadata-Version: 2.4
Name: gitshield-cli
Version: 1.0.0
Summary: GitShield — The Developer Guardian That Watches Your Code. Real-time secret detection, intelligent pre-commit checks, repo health scoring, and developer behavior intelligence.
Author: Ajay Bidyarthy
License: MIT
Project-URL: Homepage, https://github.com/kamrankausher/Git_Shield
Project-URL: Documentation, https://github.com/kamrankausher/Git_Shield#readme
Project-URL: Repository, https://github.com/kamrankausher/Git_Shield
Project-URL: Bug Tracker, https://github.com/kamrankausher/Git_Shield/issues
Project-URL: Changelog, https://github.com/kamrankausher/Git_Shield/releases
Keywords: git,security,developer-tools,code-analysis,pre-commit,secrets-detection,devops,cli,code-quality,git-hooks,code-review,static-analysis,developer-experience
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
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: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Topic :: Software Development :: Version Control :: Git
Classifier: Topic :: Security
Classifier: Operating System :: OS Independent
Classifier: Environment :: Console
Classifier: Typing :: Typed
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: click>=8.0
Requires-Dist: rich>=13.0
Requires-Dist: flask>=3.0
Requires-Dist: flask-cors>=4.0
Requires-Dist: gitpython>=3.1
Requires-Dist: watchdog>=3.0
Requires-Dist: pyyaml>=6.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: black>=23.0; extra == "dev"
Requires-Dist: ruff>=0.1; extra == "dev"
Dynamic: license-file

<div align="center">

<img src="https://img.shields.io/badge/🛡️_GitShield-v1.0.0-6C63FF?style=for-the-badge&labelColor=0D1117" alt="GitShield"/>

# 🛡️ GitShield

### The Developer Guardian That Watches Your Code — So You Don't Have To

[![Python](https://img.shields.io/badge/Python-3.8+-3776AB?style=for-the-badge&logo=python&logoColor=white)](https://python.org)
[![License](https://img.shields.io/badge/License-MIT-22C55E?style=for-the-badge)](LICENSE)
[![Tests](https://img.shields.io/badge/Tests-46/46_Passing-22C55E?style=for-the-badge&logo=pytest&logoColor=white)](#-testing)
[![VS Code](https://img.shields.io/badge/VS_Code-Extension-007ACC?style=for-the-badge&logo=visual-studio-code)](https://marketplace.visualstudio.com)
[![PyPI](https://img.shields.io/badge/PyPI-gitshield-F97316?style=for-the-badge&logo=pypi&logoColor=white)](https://pypi.org/project/gitshield)

<br/>

**Prevents mistakes BEFORE they happen** · **Guides you DURING actions** · **Fixes issues AFTER mistakes** · **Learns your behavior**

<br/>

[🚀 Quick Start](#-quick-start) · [✨ Features](#-core-features) · [💻 CLI Reference](#-cli-reference) · [🖥️ VS Code Extension](#️-vs-code-extension) · [🏗️ Architecture](#️-system-architecture) · [🧪 Testing](#-testing)

---

</div>

## 🎯 What is GitShield?

**GitShield** is a **production-ready, end-to-end developer protection system** that integrates seamlessly with your Git workflow. It combines real-time security scanning, intelligent rules enforcement, smart mentoring, and behavioral analysis into a single tool.

> **Think of it as a security-first pair programmer** that sits between your code and your repository — catching secrets before they leak, enforcing quality standards, and continuously learning how you work to give better advice.

### 🔑 Why GitShield?

| Problem | GitShield Solution |
|---------|-------------------|
| 🔓 Accidentally committed API keys | **30+ secret detection patterns** catch them before commit |
| 💬 Vague commit messages like "fix stuff" | **Smart Mentor** scores messages and suggests improvements |
| 📦 Monster commits with 80+ files | **Rule Engine** warns about oversized commits |
| 🌿 Pushing directly to `main` | **Branch protection** blocks direct commits to protected branches |
| 😰 "How do I undo my last commit?" | **Recovery Engine** provides step-by-step guided fixes |
| 📉 Repository entropy building up | **Health Analyzer** scores repo quality with actionable insights |

---

## ✨ Core Features

### 🔒 Security Scanner — 30+ Secret Detection Patterns

Detects leaked credentials from **AWS, Google Cloud, GitHub, Stripe, Slack, Twilio, SendGrid, Firebase, Discord, Shopify, Heroku**, and more. Includes **Shannon entropy analysis** for catching unknown token formats.

```
$ gitshield scan

  GitShield v1.0.0
  Developer Guardian & Git Intelligence

🔒 Security Scan Findings
┌──────────┬─────────────┬──────┬──────────────┬──────────────────────┐
│ Severity │ File        │ Line │ Pattern      │ Description          │
├──────────┼─────────────┼──────┼──────────────┼──────────────────────┤
│ 🔴 CRIT  │ config.py   │  12  │ AWS Key      │ AWS Access Key ID    │
│ 🟠 HIGH  │ .env        │   3  │ Generic Key  │ API key assignment   │
└──────────┴─────────────┴──────┴──────────────┴──────────────────────┘
  ⛔ COMMIT BLOCKED — Fix issues before proceeding.
```

<details>
<summary><b>📋 Full List of Detected Secret Types (30+)</b></summary>

| Provider | Patterns Detected |
|----------|------------------|
| **AWS** | Access Key ID, Secret Access Key, MWS Token |
| **Google** | API Key, OAuth Client ID, Service Account Key |
| **GitHub** | Personal Access Token, OAuth Token, App Token, Fine-Grained PAT |
| **Stripe** | Secret Key, Publishable Key, Restricted Key |
| **Slack** | Bot Token, User Token, Webhook URL |
| **Firebase** | Database URL, Web API Key |
| **Twilio** | API Key, Auth Token |
| **SendGrid** | API Key |
| **Discord** | Bot Token, Webhook |
| **NPM** | Access Token |
| **Shopify** | Access Token, Shared Secret |
| **Square** | Access Token, OAuth Secret |
| **Mailgun** | API Key |
| **Heroku** | API Key |
| **Generic** | API keys, passwords, tokens, JWTs, private keys, DB connection strings |

</details>

---

### 📋 Pre-Commit Rule Engine — SAFE ✅ / WARNING ⚠️ / BLOCK ❌

```
$ gitshield check -m "feat(auth): add JWT validation"

📋 Pre-Commit Rules
──────────────────────────────────────────
  ✅ Protected Branch: Working on branch 'feature/auth' (not protected)
  ✅ Staged File Count: 3 file(s) staged for commit
  ✅ File Size: All staged files are within size limits
  ⚠️ Debug Markers: Found 2 TODO/FIXME markers in staged files
  ❌ Conflict Markers: Unresolved merge conflict in utils.py

✍️ Commit Message Analysis
  Score: 🟢 92/100

🧠 Mentor Suggestions
  🌿 Branch follows conventions — good job!
  ✍️ Consider adding a body to explain the implementation approach
```

**Rules checked on every commit:**
- ✅ Protected branch detection (main, master, production)
- ✅ Staged file count limits (configurable, default 50)
- ✅ File size limits (configurable, default 5MB)
- ✅ Binary file detection (.exe, .dll, .so, .sqlite)
- ✅ TODO/FIXME/HACK marker warnings
- ✅ Merge conflict marker blocking
- ✅ Conventional commit message format validation
- ✅ Commit message length enforcement

---

### 📊 Repository Health Score

```
$ gitshield health

╭──────────────────────────────╮
│ 📊 Repository Health Report  │
│                              │
│  Grade: B — 74/100           │
│  ██████████████░░░░░░ 74%    │
│                              │
│  📁 Structure:     90/100    │
│  📄 Essentials:    85/100    │
│  📊 File Quality:  70/100    │
│  🔀 Git Hygiene:   55/100    │
│  📦 Dependencies:  80/100    │
╰──────────────────────────────╯

⚠️ Issues Found
──────────────────────────────────────────
  🟡 5/10 recent commits have poor messages
     💡 Write descriptive commit messages using conventional format
  🔵 No lock file for requirements.txt
     💡 Consider generating a lock file for reproducible builds
```

---

### 🔧 Mistake Recovery Assistant

10+ guided recovery plans for common Git mistakes — each with step-by-step instructions, risk levels, and destructive operation warnings.

```
$ gitshield fix

🔧 Available Recovery Operations
┌───┬──────────────────────────┬────────────────────────────────────────┬──────────┐
│ # │ ID                       │ Description                            │ Risk     │
├───┼──────────────────────────┼────────────────────────────────────────┼──────────┤
│ 1 │ undo_last_commit         │ Undo the most recent commit            │ LOW      │
│ 2 │ remove_file_from_history │ Remove a file from all git history     │ CRITICAL │
│ 3 │ unstage_all              │ Remove all files from staging          │ LOW      │
│ 4 │ recover_deleted_branch   │ Recover a recently deleted branch      │ LOW      │
│ 5 │ abort_merge              │ Abort a failed merge operation         │ MEDIUM   │
│ 6 │ reset_to_remote          │ Reset local branch to match remote     │ HIGH     │
│ 7 │ fix_detached_head        │ Fix a detached HEAD state              │ LOW      │
│ 8 │ squash_commits           │ Squash recent commits together         │ MEDIUM   │
│ 9 │ cherry_pick_commit       │ Apply a specific commit to this branch │ LOW      │
│10 │ clean_untracked          │ Remove all untracked files             │ HIGH     │
└───┴──────────────────────────┴────────────────────────────────────────┴──────────┘

$ gitshield fix --plan remove_file_from_history --file .env
  Step 1: Backup Repository — cp -r .git .git-backup
  Step 2: Add to .gitignore — echo ".env" >> .gitignore
  Step 3: Remove from History — git filter-branch ...
  Step 4: Force Push — git push origin --force --all ⚠️ (DESTRUCTIVE)
  Step 5: ROTATE SECRETS — Revoke and regenerate any exposed keys
```

---

### 🧠 Behavior Intelligence & Smart Mentoring

Tracks your development patterns locally using SQLite and provides personalized insights:

```
$ gitshield learn

╭──────────────────────────────╮
│ 🧠 Behavior Intelligence     │
│                              │
│  📝 Total Commits: 127       │
│  🔍 Total Scans: 89          │
│  🔒 Secrets Found: 3         │
│  🛡️ Secrets Prevented: 3    │
│  📦 Avg Files/Commit: 4.2    │
│  🔥 Current Streak: 12 days  │
╰──────────────────────────────╯

💡 Insights
  ✨ Great Commit Discipline — avg 4 files/commit
  🔒 Security Awareness — 100% prevention rate
  🔥 Hot Streak! — 12 days of continuous coding
```

---

## 🚀 Quick Start

### 1. Install via pip

```bash
pip install gitshield
```

### 2. Or install from source

```bash
git clone https://github.com/kamrankausher/Git_Shield.git
cd GitShield
pip install -e .
```

### 3. Start protecting your repository

```bash
cd your-project

# Scan for secrets
gitshield scan

# Run pre-commit checks
gitshield check

# Analyze repo health
gitshield health

# Install automatic git hooks
gitshield init
```

### Windows Installation

```powershell
cd GitShield
.\scripts\install.ps1
```

### macOS / Linux

```bash
cd GitShield
chmod +x scripts/install.sh
./scripts/install.sh
```

---

## 💻 CLI Reference

| Command | Description |
|---------|-------------|
| `gitshield` | Show status dashboard and quick start guide |
| `gitshield scan` | 🔒 Scan entire repository for secrets |
| `gitshield scan --staged` | 🔒 Scan only staged files |
| `gitshield scan --strict` | 🔒 Enable Shannon entropy analysis |
| `gitshield check` | 📋 Run all pre-commit validation rules |
| `gitshield check -m "message"` | 📋 Also validate commit message |
| `gitshield health` | 📊 Generate repository health report |
| `gitshield fix` | 🔧 List all recovery operations |
| `gitshield fix --plan <id>` | 🔧 Show detailed recovery plan |
| `gitshield fix --execute <id>` | 🔧 Execute a safe recovery operation |
| `gitshield learn` | 🧠 View behavior insights and suggestions |
| `gitshield init` | 🔗 Install pre-commit & pre-push git hooks |
| `gitshield server` | 🖥️ Start Flask backend for VS Code extension |
| `gitshield status` | 📍 Show git context and active risks |

---

## 🖥️ VS Code Extension

GitShield includes a premium VS Code extension with a glassmorphic dashboard sidebar.

### Features

| Feature | Description |
|---------|-------------|
| **Sidebar Dashboard** | Real-time scan results, health gauges, and suggestions |
| **Status Bar** | Always-visible protection status indicator |
| **Command Palette** | Access all features via `Ctrl+Shift+P` → "GitShield" |
| **Auto-Start Server** | Automatically starts the Python backend on activation |
| **Scan on Save** | Optionally scan for secrets every time you save a file |

### Installation

**Option 1 — From VSIX (local):**
```bash
cd vscode-extension
npm install
npm run compile
npx vsce package
# Then install the .vsix file via VS Code Extensions panel
```

**Option 2 — Development mode:**
1. Open the `vscode-extension/` folder in VS Code
2. Press `F5` to launch the Extension Development Host
3. The extension will activate in the new window

### Setup

1. Install the Python CLI: `pip install gitshield`
2. Install the VS Code extension
3. Start the backend server: `gitshield server` (or let auto-start handle it)

---

## 🏗️ System Architecture

```
┌──────────────────────────────────────┐
│       VS Code Extension (TS)         │
│  ┌─────────┐ ┌──────┐ ┌──────────┐  │
│  │Sidebar  │ │Status│ │ Commands │  │
│  │Dashboard│ │ Bar  │ │ Palette  │  │
│  └────┬────┘ └──┬───┘ └────┬─────┘  │
│       └─────────┴──────────┘         │
│                  │                   │
│           HTTP REST API              │
└──────────────────┬───────────────────┘
                   │
┌──────────────────┴───────────────────┐
│       Flask Backend Server           │
│    /api/scan  /api/check  /api/health│
│  /api/risks  /api/behavior  /api/fix │
└──────────────────┬───────────────────┘
                   │
┌──────────────────┴───────────────────┐
│        Core Engine (Orchestrator)    │
│                                      │
│  ┌──────────┐  ┌──────────┐         │
│  │ Security │  │  Rule    │         │
│  │ Scanner  │  │  Engine  │         │
│  └──────────┘  └──────────┘         │
│  ┌──────────┐  ┌──────────┐         │
│  │  Smart   │  │ Behavior │         │
│  │  Mentor  │  │ Tracker  │         │
│  └──────────┘  └──────────┘         │
│  ┌──────────┐  ┌──────────┐         │
│  │  Health  │  │ Recovery │         │
│  │ Analyzer │  │  Engine  │         │
│  └──────────┘  └──────────┘         │
│  ┌──────────┐  ┌──────────┐         │
│  │   Git    │  │ Pattern  │         │
│  │  Intel   │  │    DB    │         │
│  └──────────┘  └──────────┘         │
└──────────────────┬───────────────────┘
                   │
┌──────────────────┴───────────────────┐
│         Data & Storage Layer         │
│  ┌────────┐ ┌──────┐ ┌────────────┐ │
│  │ SQLite │ │ YAML │ │    Git     │ │
│  │(.devflow│ │Config│ │ subprocess │ │
│  │  /db)  │ │      │ │            │ │
│  └────────┘ └──────┘ └────────────┘ │
└──────────────────────────────────────┘
```

### Technology Stack

| Layer | Technology | Purpose |
|-------|-----------|---------|
| **CLI** | Python 3.8+ · Click · Rich | Terminal interface with colorized output |
| **Server** | Flask · Flask-CORS | REST API backend for VS Code |
| **Core** | Python standard library | Security scanning, rules, mentoring, behavior, recovery |
| **Storage** | SQLite | Local behavior tracking and scan history |
| **Git** | subprocess | Git operations (branch, diff, log, stash) |
| **Config** | PyYAML | User-configurable `.devflow.yml` files |
| **Extension** | TypeScript · VS Code API | Sidebar UI, status bar, file watchers |
| **Testing** | pytest (46 tests) | Unit tests for scanner, rules, health, CLI |

---

## 📁 Project Structure

```
GitShield/
├── pyproject.toml                  # Package configuration & metadata
├── README.md                       # This documentation
├── LICENSE                         # MIT License
├── requirements.txt                # Python dependencies
├── setup.py                        # Legacy setup script
├── .gitignore                      # Git ignore rules
│
├── src/devflow/                    # Python package (src-layout)
│   ├── __init__.py                 # Package version & metadata
│   ├── cli.py                      # Click CLI — 8 commands
│   ├── server.py                   # Flask REST API — 12 endpoints
│   │
│   ├── core/                       # Core engine modules
│   │   ├── engine.py               # Central orchestrator
│   │   ├── scanner.py              # Security scanner (30+ patterns)
│   │   ├── patterns.py             # Secret regex pattern database
│   │   ├── rules.py                # Rule engine (SAFE/WARN/BLOCK)
│   │   ├── ai_mentor.py            # Smart suggestion engine
│   │   ├── behavior.py             # Developer behavior tracker
│   │   ├── health.py               # Repository health analyzer
│   │   ├── recovery.py             # Mistake recovery assistant
│   │   └── git_intel.py            # Git context intelligence
│   │
│   ├── hooks/                      # Git hook integration
│   │   └── installer.py            # Hook installer (Unix + Windows)
│   │
│   ├── db/                         # Data persistence
│   │   └── store.py                # SQLite storage layer
│   │
│   └── utils/                      # Shared utilities
│       ├── git.py                  # Git operation wrappers
│       ├── formatters.py           # Rich terminal formatters
│       └── config.py               # YAML config management
│
├── vscode-extension/               # VS Code Extension
│   ├── package.json                # Extension manifest
│   ├── tsconfig.json               # TypeScript config
│   └── src/
│       ├── extension.ts            # Activation & command registration
│       ├── sidebarProvider.ts      # Webview dashboard (glassmorphic UI)
│       ├── devflowClient.ts        # HTTP client for Flask backend
│       └── statusBar.ts            # Status bar indicator
│
├── tests/                          # Test suite (46 tests)
│   ├── test_scanner.py             # Scanner & pattern tests
│   ├── test_rules.py               # Rule engine tests
│   ├── test_health.py              # Health analyzer tests
│   └── test_cli.py                 # CLI integration tests
│
└── scripts/                        # Installation scripts
    ├── install.sh                  # Unix installer
    └── install.ps1                 # Windows PowerShell installer
```

---

## 🔧 Configuration

Create a `.devflow.yml` in your project root to customize behavior:

```yaml
# GitShield Configuration
# Place this file in your project root as .devflow.yml

security:
  scan_on_commit: true        # Auto-scan on pre-commit hook
  scan_on_push: true          # Auto-scan on pre-push hook
  block_on_critical: true     # Block commits with CRITICAL findings
  block_on_high: true         # Block commits with HIGH findings
  entropy_analysis: false     # Shannon entropy for unknown patterns
  custom_patterns: []         # Add your own regex patterns

rules:
  max_file_size_mb: 5         # Max file size allowed (MB)
  max_files_per_commit: 50    # Max files per commit
  protected_branches:         # Branches that trigger warnings
    - main
    - master
    - production
  require_conventional_commits: true
  min_commit_message_length: 10
  max_commit_message_length: 200
  block_binary_files: true
  allowed_branch_prefixes:
    - feature/
    - fix/
    - bugfix/
    - hotfix/
    - release/
    - chore/
    - docs/
    - refactor/
    - test/
    - ci/

behavior:
  track_actions: true         # Log actions to SQLite
  track_secrets: true         # Log secret detections
  show_insights: true         # Display personalized insights

mentor:
  enabled: true
  show_on_commit: true
  max_suggestions: 5

server:
  host: 127.0.0.1
  port: 9876
  auto_start: true
```

---

## 🧪 Testing

```bash
# Run all 46 tests
pytest tests/ -v

# Run with coverage
pytest tests/ -v --cov=devflow

# Run specific test modules
pytest tests/test_scanner.py -v    # 17 scanner tests
pytest tests/test_rules.py -v      # 9 rule engine tests
pytest tests/test_health.py -v     # 4 health analyzer tests
pytest tests/test_cli.py -v        # 10 CLI integration tests
```

**Current test status:** ✅ **46/46 tests passing**

---

## 🧑‍💻 Development

### Setup Development Environment

```bash
git clone https://github.com/kamrankausher/Git_Shield.git
cd GitShield

# Create virtual environment
python -m venv venv
source venv/bin/activate        # Linux/macOS
# venv\Scripts\activate         # Windows

# Install in editable mode with dev dependencies
pip install -e ".[dev]"

# Run tests
pytest tests/ -v
```

### Build & Publish to PyPI

```bash
pip install build twine
python -m build
twine upload dist/*
```

### Build VS Code Extension

```bash
cd vscode-extension
npm install
npm run compile
npx vsce package             # Creates .vsix file
npx vsce publish             # Publish to Marketplace (requires token)
```

---

## 🔐 Privacy & Security

- **100% Local** — All data is stored locally in `.devflow/` inside your repository
- **No Cloud** — No data is ever sent to external servers
- **No Telemetry** — Zero tracking, zero analytics, zero network calls
- **SQLite Storage** — Behavior data stored in local SQLite database
- **Git-Ignored** — `.devflow/` is automatically added to `.gitignore`

---

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch: `git checkout -b feature/amazing-feature`
3. Write tests for your changes
4. Ensure all tests pass: `pytest tests/ -v`
5. Commit with conventional format: `git commit -m "feat(scanner): add new pattern"`
6. Push and open a Pull Request

---

## 📄 License

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

---

<div align="center">

**Built with ❤️ for developers who take code quality and security seriously.**

🛡️ **GitShield** — Your code deserves a guardian.

[![GitHub Stars](https://img.shields.io/github/stars/kamrankausher/Git_Shield?style=social)](https://github.com/kamrankausher/Git_Shield)

</div>
