Skip to content

Latest commit

 

History

History
819 lines (609 loc) · 21 KB

File metadata and controls

819 lines (609 loc) · 21 KB

VersionGuard Examples

Comprehensive Usage Examples

This document provides 12 detailed examples of using VersionGuard in various scenarios.


Table of Contents

  1. Basic Project Scan
  2. CI/CD Integration
  3. Pre-Installation Check
  4. Monorepo Scanning
  5. Custom Dependency Check
  6. JSON Export for Reports
  7. Version Comparison Utilities
  8. Finding Specific Issues
  9. Building Project Health Dashboard
  10. Pre-Commit Hook
  11. Real-Time Monitoring
  12. Team Brain Agent Integration

Example 1: Basic Project Scan

Scenario

You have a full-stack project and want to check for compatibility issues before starting work.

Code

from pathlib import Path
from versionguard import VersionGuard

# Initialize with your project root
project_path = Path("./my-fullstack-project")
guard = VersionGuard(project_path)

# Scan for all dependencies
print("Scanning project...")
frontend_deps, backend_deps = guard.scan_project()

print(f"Found {len(frontend_deps)} frontend dependencies")
print(f"Found {len(backend_deps)} backend dependencies")

# Check for compatibility issues
issues = guard.check_compatibility()

if issues:
    print(f"\nWARNING: {len(issues)} compatibility issues found!")
    for issue in issues:
        print(f"  - {issue.package}: {issue.message}")
else:
    print("\nNo compatibility issues found!")

# Generate full report
print("\n" + guard.format_report())

Expected Output

Scanning project...
Found 12 frontend dependencies
Found 5 backend dependencies

No compatibility issues found!

======================================================================
VERSIONGUARD COMPATIBILITY REPORT
======================================================================

Status: COMPATIBLE

SUMMARY
----------------------------------------
COMPATIBLE: No compatibility issues detected (12 frontend, 5 backend deps)
...

Example 2: CI/CD Integration

Scenario

You want to add VersionGuard to your build pipeline to catch issues early.

GitHub Actions Workflow

# .github/workflows/version-check.yml
name: Version Compatibility Check

on: [push, pull_request]

jobs:
  check-versions:
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v3
    
    - name: Set up Python
      uses: actions/setup-python@v4
      with:
        python-version: '3.10'
    
    - name: Run VersionGuard
      run: |
        python versionguard.py scan . --json -o version-report.json
        
    - name: Check for Critical Issues
      run: |
        if grep -q '"status": "incompatible"' version-report.json; then
          echo "::error::Version compatibility issues detected!"
          python versionguard.py scan .
          exit 1
        fi
        echo "Version compatibility check passed!"
    
    - name: Upload Report
      uses: actions/upload-artifact@v3
      with:
        name: version-report
        path: version-report.json

Expected Behavior

  • Pipeline passes if no incompatible versions
  • Pipeline fails with detailed report if issues found
  • Report artifact saved for review

Example 3: Pre-Installation Check

Scenario

Before installing a new package combination, you want to verify compatibility.

Code

from versionguard import VersionGuard, SemanticVersion, Dependency

def check_before_install(packages: dict) -> bool:
    """
    Check compatibility before installing packages.
    
    Args:
        packages: Dict of {"frontend": ["pkg@ver"], "backend": ["pkg@ver"]}
    
    Returns:
        True if compatible, False otherwise
    """
    guard = VersionGuard()
    
    # Parse frontend packages
    for pkg_spec in packages.get("frontend", []):
        name, version = pkg_spec.split("@") if "@" in pkg_spec else (pkg_spec, "")
        guard.frontend_deps.append(Dependency(
            name=name,
            version=SemanticVersion.parse(version) if version else None,
            version_spec=version,
            source="frontend",
            file_path="cli-check"
        ))
    
    # Parse backend packages
    for pkg_spec in packages.get("backend", []):
        name, version = pkg_spec.split("@") if "@" in pkg_spec else (pkg_spec, "")
        guard.backend_deps.append(Dependency(
            name=name,
            version=SemanticVersion.parse(version) if version else None,
            version_spec=version,
            source="backend",
            file_path="cli-check"
        ))
    
    # Check compatibility
    issues = guard.check_compatibility()
    
    if issues:
        print("INCOMPATIBLE: Review before installing!")
        for issue in issues:
            print(f"\n[{issue.severity.value.upper()}] {issue.package}")
            print(f"  {issue.message}")
            print(f"  Recommendation: {issue.recommendation}")
        return False
    
    print("COMPATIBLE: Safe to install!")
    return True


# Example usage
packages = {
    "frontend": ["socket.io-client@4.7.2", "react@18.2.0", "react-dom@18.2.0"],
    "backend": ["python-socketio@5.8.0", "flask@2.3.0"]
}

if check_before_install(packages):
    print("\nProceeding with installation...")
else:
    print("\nInstallation blocked - resolve issues first!")

Expected Output

INCOMPATIBLE: Review before installing!

[CRITICAL] socket.io
  Socket.IO client v4.7.2 is incompatible with server v5.8.0
  Recommendation: Use socket.io-client v4 with python-socketio v4, or upgrade both to v5

Installation blocked - resolve issues first!

Example 4: Monorepo Scanning

Scenario

You have a monorepo with multiple packages and want to check all of them.

Code

from pathlib import Path
from versionguard import VersionGuard

# Scan monorepo
monorepo_path = Path("./my-monorepo")
guard = VersionGuard(monorepo_path)

print(f"Scanning monorepo: {monorepo_path}")
frontend_deps, backend_deps = guard.scan_project()

# Group dependencies by file
deps_by_package = {}
for dep in frontend_deps + backend_deps:
    pkg_dir = Path(dep.file_path).parent.name
    if pkg_dir not in deps_by_package:
        deps_by_package[pkg_dir] = {"frontend": [], "backend": []}
    deps_by_package[pkg_dir][dep.source].append(dep)

# Report per package
print(f"\nFound {len(deps_by_package)} packages:")
for pkg_name, deps in deps_by_package.items():
    fe_count = len(deps["frontend"])
    be_count = len(deps["backend"])
    print(f"  {pkg_name}: {fe_count} frontend, {be_count} backend")

# Check overall compatibility
issues = guard.check_compatibility()
print(f"\nTotal issues: {len(issues)}")

Expected Output

Scanning monorepo: ./my-monorepo
Found 3 packages:
  web: 15 frontend, 0 backend
  api: 0 frontend, 8 backend
  shared: 3 frontend, 2 backend

Total issues: 0

Example 5: Custom Dependency Check

Scenario

You want to check specific package combinations without scanning files.

CLI Usage

# Check socket.io client/server compatibility
python versionguard.py check -f socket.io-client@4.7.2 -b python-socketio@5.8.0

# Check React ecosystem
python versionguard.py check -f react@18.2.0 -f react-dom@17.0.0

Python Code

from versionguard import VersionGuard, Dependency, SemanticVersion

guard = VersionGuard()

# Manually add dependencies to check
guard.frontend_deps = [
    Dependency("react", SemanticVersion.parse("18.2.0"), "^18.2.0", "frontend", "manual"),
    Dependency("react-dom", SemanticVersion.parse("17.0.0"), "^17.0.0", "frontend", "manual"),
]

# Check for issues
issues = guard.check_compatibility()

for issue in issues:
    print(f"[{issue.severity.value}] {issue.message}")

Expected Output

[warning] React v18.2.0 must match React-DOM v17.0.0

Example 6: JSON Export for Reports

Scenario

You need machine-readable output for automated processing.

CLI Usage

# Export as JSON
python versionguard.py scan ./project --json -o compatibility.json

Python Code

from pathlib import Path
import json
from versionguard import VersionGuard

guard = VersionGuard(Path("./my-project"))
guard.scan_project()
guard.check_compatibility()

# Export to JSON
output_path = Path("./reports/compatibility.json")
guard.export_json(output_path)

# Or get dict directly
report = guard.generate_report()
report_dict = report.to_dict()

print(json.dumps(report_dict, indent=2))

Expected Output

{
  "status": "compatible",
  "frontend_dep_count": 12,
  "backend_dep_count": 5,
  "issue_count": 0,
  "issues": [],
  "recommendations": [],
  "summary": "COMPATIBLE: No compatibility issues detected (12 frontend, 5 backend deps)"
}

Example 7: Version Comparison Utilities

Scenario

You need to compare and analyze version numbers programmatically.

Code

from versionguard import SemanticVersion

# Parse versions
v1 = SemanticVersion.parse("4.7.2")
v2 = SemanticVersion.parse("5.0.0")
v3 = SemanticVersion.parse("4.6.1")

print(f"Parsed v1: {v1} (major={v1.major}, minor={v1.minor}, patch={v1.patch})")

# Comparisons
print(f"\nComparisons:")
print(f"  {v1} < {v2}: {v1 < v2}")      # True
print(f"  {v1} > {v3}: {v1 > v3}")      # True
print(f"  {v1} == {v3}: {v1 == v3}")    # False

# Compatibility checks
print(f"\nCompatibility:")
print(f"  {v1} major-compatible with {v3}: {v1.is_major_compatible(v3)}")  # True
print(f"  {v1} major-compatible with {v2}: {v1.is_major_compatible(v2)}")  # False
print(f"  {v1} minor-compatible with {v3}: {v1.is_minor_compatible(v3)}")  # False

# Parse with prefixes
v_caret = SemanticVersion.parse("^4.7.2")
v_tilde = SemanticVersion.parse("~4.7.2")
print(f"\nPrefixes stripped:")
print(f"  ^4.7.2 -> {v_caret}")
print(f"  ~4.7.2 -> {v_tilde}")

# Prerelease versions
v_alpha = SemanticVersion.parse("1.0.0-alpha")
v_beta = SemanticVersion.parse("1.0.0-beta.2")
print(f"\nPrerelease:")
print(f"  {v_alpha.raw} -> prerelease='{v_alpha.prerelease}'")
print(f"  {v_beta.raw} -> prerelease='{v_beta.prerelease}'")

Expected Output

Parsed v1: 4.7.2 (major=4, minor=7, patch=2)

Comparisons:
  4.7.2 < 5.0.0: True
  4.7.2 > 4.6.1: True
  4.7.2 == 4.6.1: False

Compatibility:
  4.7.2 major-compatible with 4.6.1: True
  4.7.2 major-compatible with 5.0.0: False
  4.7.2 minor-compatible with 4.6.1: False

Prefixes stripped:
  ^4.7.2 -> 4.7.2
  ~4.7.2 -> 4.7.2

Prerelease:
  1.0.0-alpha -> prerelease='alpha'
  1.0.0-beta.2 -> prerelease='beta.2'

Example 8: Finding Specific Issues

Scenario

You want to filter and find specific types of issues.

Code

from versionguard import VersionGuard, Severity, CompatibilityStatus
from pathlib import Path

guard = VersionGuard(Path("./problematic-project"))
guard.scan_project()
issues = guard.check_compatibility()

# Filter by severity
critical_issues = [i for i in issues if i.severity == Severity.CRITICAL]
warnings = [i for i in issues if i.severity == Severity.WARNING]

print(f"Found {len(critical_issues)} critical issues:")
for issue in critical_issues:
    print(f"  - {issue.package}: {issue.message}")

print(f"\nFound {len(warnings)} warnings:")
for issue in warnings:
    print(f"  - {issue.package}: {issue.message}")

# Filter by status
incompatible = [i for i in issues if i.status == CompatibilityStatus.INCOMPATIBLE]
print(f"\nIncompatible packages: {[i.package for i in incompatible]}")

# Get all recommendations
all_recommendations = set()
for issue in issues:
    if issue.recommendation:
        all_recommendations.add(issue.recommendation)

print(f"\nUnique recommendations:")
for rec in all_recommendations:
    print(f"  - {rec}")

Expected Output

Found 1 critical issues:
  - socket.io: Socket.IO client v4.7.2 is incompatible with server v5.8.0

Found 2 warnings:
  - pydantic: Pydantic v2.0.0 - major API changes between versions
  - sqlalchemy: SQLAlchemy v2.0.0 - check for API compatibility

Incompatible packages: ['socket.io']

Unique recommendations:
  - Use socket.io-client v4 with python-socketio v4, or upgrade both to v5
  - Use pydantic.v1 namespace for 1.x compatibility in 2.0
  - If mixing 1.x and 2.x code, use sqlalchemy.future for forward compatibility

Example 9: Building Project Health Dashboard

Scenario

You want to create a summary of dependency health across multiple projects.

Code

from pathlib import Path
from versionguard import VersionGuard, CompatibilityStatus

projects = [
    Path("./project-alpha"),
    Path("./project-beta"),
    Path("./project-gamma"),
]

dashboard = []

for project_path in projects:
    if not project_path.exists():
        continue
        
    guard = VersionGuard(project_path)
    guard.scan_project()
    guard.check_compatibility()
    report = guard.generate_report()
    
    dashboard.append({
        "project": project_path.name,
        "frontend_deps": len(guard.frontend_deps),
        "backend_deps": len(guard.backend_deps),
        "status": report.status.value,
        "issue_count": len(report.issues),
        "critical_count": sum(1 for i in report.issues if i.severity.value == "critical")
    })

# Print dashboard
print("=" * 70)
print("PROJECT HEALTH DASHBOARD")
print("=" * 70)
print(f"{'Project':<20} {'Frontend':<10} {'Backend':<10} {'Status':<15} {'Issues':<10}")
print("-" * 70)

for item in dashboard:
    status_display = item["status"].upper()
    if item["critical_count"] > 0:
        status_display += f" ({item['critical_count']} CRIT)"
    
    print(f"{item['project']:<20} {item['frontend_deps']:<10} {item['backend_deps']:<10} {status_display:<15} {item['issue_count']:<10}")

print("=" * 70)

Expected Output

======================================================================
PROJECT HEALTH DASHBOARD
======================================================================
Project              Frontend   Backend    Status          Issues    
----------------------------------------------------------------------
project-alpha        12         5          COMPATIBLE      0         
project-beta         8          3          WARNING         2         
project-gamma        15         7          INCOMPATIBLE (1 CRIT) 3         
======================================================================

Example 10: Pre-Commit Hook

Scenario

You want to prevent commits that introduce incompatible dependencies.

Setup

# .git/hooks/pre-commit (make executable: chmod +x)
#!/bin/bash

echo "Running VersionGuard compatibility check..."

# Run the check
python versionguard.py scan . --json -o .versionguard-check.json 2>/dev/null

# Check for incompatible status
if grep -q '"status": "incompatible"' .versionguard-check.json; then
    echo ""
    echo "=========================================="
    echo "COMMIT BLOCKED: Version Incompatibilities"
    echo "=========================================="
    echo ""
    python versionguard.py scan .
    echo ""
    echo "Please resolve the above issues before committing."
    rm .versionguard-check.json
    exit 1
fi

rm .versionguard-check.json
echo "VersionGuard check passed!"
exit 0

Python Alternative

#!/usr/bin/env python3
# .git/hooks/pre-commit

import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

from versionguard import VersionGuard, CompatibilityStatus

guard = VersionGuard(Path("."))
guard.scan_project()
guard.check_compatibility()
report = guard.generate_report()

if report.status == CompatibilityStatus.INCOMPATIBLE:
    print("COMMIT BLOCKED: Version incompatibilities detected!")
    print(guard.format_report())
    sys.exit(1)

print("VersionGuard: All clear!")
sys.exit(0)

Example 11: Real-Time Monitoring

Scenario

You want to monitor dependency files for changes and check compatibility automatically.

Code

import time
from pathlib import Path
from versionguard import VersionGuard
from datetime import datetime

def watch_project(project_path: Path, interval: int = 30):
    """
    Watch a project for dependency changes.
    
    Args:
        project_path: Path to project root
        interval: Check interval in seconds
    """
    guard = VersionGuard(project_path)
    last_check = {}
    
    print(f"Watching {project_path} for dependency changes...")
    print(f"Check interval: {interval} seconds")
    print("Press Ctrl+C to stop\n")
    
    while True:
        # Find dependency files
        dep_files = []
        dep_files.extend(project_path.rglob("package.json"))
        dep_files.extend(project_path.rglob("requirements*.txt"))
        dep_files.extend(project_path.rglob("pyproject.toml"))
        
        # Filter out node_modules
        dep_files = [f for f in dep_files if "node_modules" not in str(f)]
        
        # Check for modifications
        changed = False
        for dep_file in dep_files:
            mtime = dep_file.stat().st_mtime
            if str(dep_file) not in last_check or last_check[str(dep_file)] != mtime:
                changed = True
                last_check[str(dep_file)] = mtime
        
        if changed:
            timestamp = datetime.now().strftime("%H:%M:%S")
            print(f"[{timestamp}] Change detected - running compatibility check...")
            
            guard.frontend_deps = []
            guard.backend_deps = []
            guard.scan_project()
            issues = guard.check_compatibility()
            
            if issues:
                print(f"  WARNING: {len(issues)} issues found!")
                for issue in issues:
                    print(f"    - {issue.package}: {issue.severity.value.upper()}")
            else:
                print(f"  OK: No compatibility issues")
        
        time.sleep(interval)


# Usage
# watch_project(Path("./my-project"), interval=10)

Example 12: Team Brain Agent Integration

Scenario

You're a Team Brain agent and want to use VersionGuard before starting work.

For IRIS (Desktop Development)

# IRIS Pre-Development Check
from pathlib import Path
from versionguard import VersionGuard, CompatibilityStatus

def iris_pre_check(project_path: str) -> bool:
    """
    IRIS's pre-development compatibility check.
    
    Returns True if safe to proceed, False if issues found.
    """
    print("[IRIS] Running pre-development compatibility check...")
    
    guard = VersionGuard(Path(project_path))
    guard.scan_project()
    guard.check_compatibility()
    report = guard.generate_report()
    
    if report.status == CompatibilityStatus.INCOMPATIBLE:
        print("[IRIS] BLOCKED: Critical compatibility issues detected!")
        print("[IRIS] Alerting team via SynapseLink...")
        
        # Would integrate with SynapseLink here
        # from synapselink import quick_send
        # quick_send("FORGE,NEXUS", "Version Incompatibility Alert", ...)
        
        print(guard.format_report())
        return False
    
    elif report.status == CompatibilityStatus.WARNING:
        print(f"[IRIS] CAUTION: {len(report.issues)} warnings found")
        print("[IRIS] Proceeding with awareness...")
        return True
    
    else:
        print("[IRIS] All clear - proceeding with development!")
        return True


# Usage in IRIS workflow
if iris_pre_check("./bch-mobile"):
    print("\n[IRIS] Starting BCH Mobile development session...")
else:
    print("\n[IRIS] Development blocked - resolve issues first!")

For BOLT (Build Executor)

# BOLT Build Pipeline Integration
from pathlib import Path
from versionguard import VersionGuard, CompatibilityStatus
import sys

def bolt_build_check() -> int:
    """
    BOLT's build pipeline compatibility check.
    
    Returns exit code (0 = success, 1 = failure).
    """
    print("[BOLT] Build Step: Version Compatibility Check")
    print("-" * 50)
    
    guard = VersionGuard(Path("."))
    guard.scan_project()
    guard.check_compatibility()
    report = guard.generate_report()
    
    # Export report for artifacts
    guard.export_json(Path(".versionguard-report.json"))
    
    if report.status == CompatibilityStatus.INCOMPATIBLE:
        print("[BOLT] BUILD FAILED: Incompatible versions detected")
        print(guard.format_report())
        return 1
    
    print(f"[BOLT] CHECK PASSED: {report.summary}")
    return 0


# Usage in build script
if __name__ == "__main__":
    sys.exit(bolt_build_check())

Summary

These examples demonstrate VersionGuard's flexibility for:

Use Case Example
Basic scanning Example 1
CI/CD pipelines Example 2
Pre-installation checks Example 3
Monorepo support Example 4
Manual dependency checks Example 5
Machine-readable output Example 6
Version comparison Example 7
Issue filtering Example 8
Multi-project dashboards Example 9
Git hooks Example 10
Real-time monitoring Example 11
Team Brain integration Example 12

VersionGuard - Pre-validate. Don't waste time.