repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

skills/gh-cli/scripts/gh_pages_deploy.py

Raw
File outline
#!/usr/bin/env python3
"""
GitHub Pages Deployment Script

A Python script to automate GitHub Pages deployment using the GitHub CLI (gh).
Supports enabling Pages, checking status, triggering rebuilds, and creating deployment workflows.

Requirements:
    - GitHub CLI (gh) must be installed and authenticated
    - Python 3.8+

Usage:
    python gh_pages_deploy.py enable <owner>/<repo> [--branch BRANCH] [--path PATH]
    python gh_pages_deploy.py status <owner>/<repo>
    python gh_pages_deploy.py rebuild <owner>/<repo>
    python gh_pages_deploy.py create-workflow [--output PATH]
"""

import argparse
import json
import re
import subprocess
import sys
from pathlib import Path


class GitHubPagesError(Exception):
    """Custom exception for GitHub Pages errors."""

    pass


def check_gh_auth() -> tuple[bool, list[str]]:
    """
    Verify gh CLI is authenticated and check available scopes.

    Returns:
        Tuple of (is_authenticated, scopes_list)
    """
    try:
        result = subprocess.run(
            ["gh", "auth", "status", "--show-token"], capture_output=True, text=True, check=False
        )
        if result.returncode != 0:
            return False, []

        # Extract scopes from output
        scopes = []
        for line in result.stdout.split("\n"):
            if "scope" in line.lower():
                # Parse scope lines like "  - workflow:..."
                match = re.search(r":\s*(\w+)", line)
                if match:
                    scopes.append(match.group(1))

        return True, scopes
    except FileNotFoundError:
        return False, []


def format_json(data: dict) -> str:
    """Format data as JSON for machine output."""
    return json.dumps(data, indent=2)


def format_message(msg: str, style: str = "info") -> str:
    """Format a message with style prefix."""
    prefixes = {
        "info": "ℹ",
        "success": "✓",
        "error": "✗",
        "warning": "⚠",
    }
    return f"{prefixes.get(style, '')} {msg}"


class GitHubPagesManager:
    """Manager class for GitHub Pages operations using gh CLI."""

    def __init__(self, repo: str, dry_run: bool = False, json_output: bool = False):
        """
        Initialize the manager with a repository.

        Args:
            repo: Repository in format 'owner/repo'
            dry_run: If True, only show what would be done
            json_output: If True, output machine-readable JSON
        """
        self.repo = repo
        self.dry_run = dry_run
        self.json_output = json_output
        self.last_result: dict = {}
        self._verify_gh_cli()

    def _verify_gh_cli(self) -> None:
        """Verify that gh CLI is installed and authenticated."""
        is_auth, scopes = check_gh_auth()
        if not is_auth:
            error = {
                "error": "GitHub CLI is not authenticated",
                "solution": "Run 'gh auth login' to authenticate",
            }
            if self.json_output:
                print(format_json(error))
            else:
                print(format_message("GitHub CLI is not authenticated.", "error"), file=sys.stderr)
                print("Run 'gh auth login' to authenticate.", file=sys.stderr)
            sys.exit(1)

        # Verify repo scope
        if "repo" not in scopes:
            warning = {
                "warning": "Missing 'repo' scope",
                "scopes": scopes,
                "may_not_work": "Private repo operations may fail",
            }
            if self.json_output:
                print(format_json(warning))

    def _run_gh_api(
        self, endpoint: str, method: str = "GET", data: dict | None = None, check: bool = True
    ) -> tuple[int, dict]:
        """
        Execute a gh api command.

        Args:
            endpoint: API endpoint (e.g., '/repos/owner/repo/pages')
            method: HTTP method (GET, POST, PUT, DELETE)
            data: Optional data dictionary for POST/PUT requests
            check: Whether to raise error on non-zero exit code

        Returns:
            Tuple of (status_code, response_dict)
        """
        if self.dry_run and method != "GET":
            print(f"[DRY RUN] Would execute: {method} {endpoint}", file=sys.stderr)
            if data:
                print(f"[DRY RUN] With data: {json.dumps(data)}", file=sys.stderr)
            return 0, {"dry_run": True, "endpoint": endpoint, "method": method}

        cmd = [
            "gh",
            "api",
            "-X",
            method,
            "-H",
            "Accept: application/vnd.github+json",
            "-H",
            "X-GitHub-Api-Version: 2022-11-28",
            endpoint,
        ]

        # Add data fields if provided
        if data:
            for key, value in data.items():
                if isinstance(value, bool):
                    cmd.extend(["-f", f"{key}={'true' if value else 'false'}"])
                elif isinstance(value, dict):
                    # Handle nested objects (e.g., source[branch])
                    for subkey, subvalue in value.items():
                        cmd.extend(["-f", f"{key}[{subkey}]={subvalue}"])
                else:
                    cmd.extend(["-f", f"{key}={value}"])

        try:
            result = subprocess.run(cmd, capture_output=True, text=True, check=check, timeout=30)

            response = {}
            if result.stdout.strip():
                try:
                    response = json.loads(result.stdout)
                except json.JSONDecodeError:
                    response = {"raw": result.stdout}

            if result.returncode != 0 and check:
                error_msg = result.stderr or str(response)
                raise GitHubPagesError(f"API call failed: {error_msg}")

            return result.returncode, response

        except subprocess.TimeoutExpired as e:
            raise GitHubPagesError("API request timed out after 30 seconds") from e
        except subprocess.CalledProcessError as e:
            error_msg = e.stderr or str(e)
            raise GitHubPagesError(f"Failed to execute gh command: {error_msg}") from e

    def enable_pages(
        self,
        branch: str = "main",
        path: str = "/",
        build_type: str = "workflow",
        https_enforced: bool = True,
    ) -> dict:
        """
        Enable GitHub Pages for the repository.

        Args:
            branch: Source branch (default: 'main')
            path: Source path, '/' or '/docs' (default: '/')
            build_type: 'workflow' for GitHub Actions or 'legacy' for Jekyll (default: 'workflow')
            https_enforced: Whether to enforce HTTPS (default: True)

        Returns:
            API response dictionary
        """
        if not self.json_output:
            print(f"Enabling GitHub Pages for {self.repo}...")
            print(f"  Branch: {branch}")
            print(f"  Path: {path}")
            print(f"  Build type: {build_type}")

        endpoint = f"/repos/{self.repo}/pages"

        data = {"source": {"branch": branch, "path": path}, "build_type": build_type}

        # Try to create Pages site
        status, response = self._run_gh_api(endpoint, method="POST", data=data, check=False)

        if status == 0 or response.get("dry_run"):
            is_dry_run = response.get("dry_run", False)
            self.last_result = {
                "status": "success" if not is_dry_run else "dry_run",
                "action": "pages_enabled",
                "repository": self.repo,
                "config": {
                    "branch": branch,
                    "path": path,
                    "build_type": build_type,
                    "https_enforced": https_enforced,
                },
                "dry_run": is_dry_run,
            }
            if self.json_output:
                print(format_json(self.last_result))
            elif is_dry_run:
                print(format_message("GitHub Pages would be enabled (dry-run)", "success"))
            else:
                print(format_message("GitHub Pages enabled successfully!", "success"))

            # Update to enforce HTTPS if requested (skip in dry run)
            if https_enforced and not self.dry_run:
                if not self.json_output:
                    print("  Enforcing HTTPS...")
                self._run_gh_api(endpoint, method="PUT", data={"https_enforced": True}, check=False)

            return response
        elif status == 422:
            # Pages might already exist
            if not self.json_output:
                print(format_message("Pages may already be enabled. Checking status...", "warning"))
            return self.check_status()
        else:
            error = response.get("message", "Unknown error")
            self.last_result = {"status": "error", "error": error}
            if self.json_output:
                print(format_json(self.last_result))
            else:
                print(format_message(f"Failed to enable Pages: {error}", "error"), file=sys.stderr)
            return response

    def check_status(self) -> dict:
        """
        Check GitHub Pages status and configuration.

        Returns:
            API response dictionary with Pages information
        """
        if not self.json_output:
            print(f"Checking GitHub Pages status for {self.repo}...")

        endpoint = f"/repos/{self.repo}/pages"
        status, response = self._run_gh_api(endpoint, check=False)

        if status == 0:
            self.last_result = {
                "status": "enabled",
                "repository": self.repo,
                "url": response.get("html_url", "N/A"),
                "pages_status": response.get("status", "N/A"),
                "build_type": response.get("build_type", "N/A"),
                "source": response.get("source", {}),
                "https_enforced": response.get("https_enforced", False),
                "custom_domain": response.get("cname"),
            }
            if self.json_output:
                print(format_json(self.last_result))
            else:
                print(format_message("GitHub Pages is enabled:", "success"))
                print(f"  URL: {response.get('html_url', 'N/A')}")
                print(f"  Status: {response.get('status', 'N/A')}")
                print(f"  Build type: {response.get('build_type', 'N/A')}")

                source = response.get("source", {})
                print(f"  Source branch: {source.get('branch', 'N/A')}")
                print(f"  Source path: {source.get('path', 'N/A')}")
                print(f"  HTTPS enforced: {response.get('https_enforced', False)}")

                if response.get("cname"):
                    print(f"  Custom domain: {response.get('cname')}")
        else:
            self.last_result = {
                "status": "disabled",
                "repository": self.repo,
                "message": "GitHub Pages is not enabled",
            }
            if self.json_output:
                print(format_json(self.last_result))
            else:
                print(
                    format_message("GitHub Pages is not enabled for this repository.", "warning"),
                    file=sys.stderr,
                )

        return response

    def trigger_rebuild(self) -> dict:
        """
        Trigger a new GitHub Pages build.

        Returns:
            API response dictionary
        """
        if not self.json_output:
            print(f"Triggering rebuild for {self.repo}...")

        endpoint = f"/repos/{self.repo}/pages/builds"
        status, response = self._run_gh_api(endpoint, method="POST", check=False)

        if status == 0 or response.get("dry_run"):
            self.last_result = {
                "status": "triggered",
                "repository": self.repo,
                "build_url": response.get("url"),
            }
            if self.json_output:
                print(format_json(self.last_result))
            else:
                print(format_message("Build triggered successfully!", "success"))
                print(f"  Status: {response.get('status', 'N/A')}")
                if "url" in response:
                    print(f"  Build URL: {response['url']}")
        else:
            error = response.get("message", "Unknown error")
            self.last_result = {"status": "error", "error": error}
            if self.json_output:
                print(format_json(self.last_result))
            else:
                print(format_message(f"Failed to trigger build: {error}", "error"), file=sys.stderr)

        return response

    def get_latest_build(self) -> dict:
        """
        Get the latest build information.

        Returns:
            API response dictionary with latest build info
        """
        endpoint = f"/repos/{self.repo}/pages/builds/latest"
        status, response = self._run_gh_api(endpoint, check=False)

        if status == 0:
            self.last_result = {
                "status": response.get("status", "N/A"),
                "commit": response.get("commit", "N/A"),
                "created_at": response.get("created_at"),
                "error": response.get("error", {}),
            }
            if self.json_output:
                print(format_json(self.last_result))
            else:
                print("\nLatest build:")
                print(f"  Status: {response.get('status', 'N/A')}")
                print(f"  Commit: {response.get('commit', 'N/A')}")
                if "created_at" in response:
                    print(f"  Created: {response['created_at']}")
                if "error" in response and response["error"].get("message"):
                    print(f"  Error: {response['error']['message']}")

        return response


def create_workflow_file(output_path: str | None = None, force: bool = False) -> dict:
    """
    Create a GitHub Actions workflow file for Pages deployment.

    Args:
        output_path: Optional custom output path (default: .github/workflows/pages.yml)
        force: Overwrite existing file without prompting

    Returns:
        Result dictionary
    """
    if output_path is None:
        output_path = ".github/workflows/pages.yml"

    workflow_file = Path(output_path)

    if workflow_file.exists() and not force:
        result = {
            "status": "skipped",
            "reason": "file_exists",
            "path": str(workflow_file.absolute()),
        }
        print(format_json(result))
        return result

    workflow_content = """name: Deploy to GitHub Pages

on:
  push:
    branches: ["main"]
  workflow_dispatch:

# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
  contents: read
  pages: write
  id-token: write

# Allow only one concurrent deployment
concurrency:
  group: "pages"
  cancel-in-progress: false

jobs:
  # Build job
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Pages
        uses: actions/configure-pages@v5

      - name: Build site
        run: |
          # Add your build commands here
          # Example: npm install && npm run build
          # For static sites, you can skip this step

          # Create output directory
          mkdir -p _site

          # Copy your built files to _site/
          # Example: cp -r dist/* _site/
          # For now, copying everything as example:
          cp -r * _site/ 2>/dev/null || true

      - name: Upload artifact
        uses: actions/upload-pages-artifact@v3
        with:
          path: '_site'

  # Deployment job
  deploy:
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    runs-on: ubuntu-latest
    needs: build
    steps:
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4
"""

    workflow_file.parent.mkdir(parents=True, exist_ok=True)
    workflow_file.write_text(workflow_content)

    result = {"status": "created", "path": str(workflow_file.absolute())}
    print(format_json(result))

    if Path.cwd().name != "gh-cli":
        print("\nNext steps:")
        print("1. Customize the 'Build site' step with your build commands")
        print("2. Ensure the correct files are copied to _site/")
        print("3. Commit and push this workflow file to your repository")
        print("4. Enable GitHub Pages with 'GitHub Actions' as the source")
    return result


def main():
    """Main entry point for the CLI."""
    parser = argparse.ArgumentParser(
        description="Automate GitHub Pages deployment using gh CLI",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )

    # Global options
    parser.add_argument(
        "--dry-run", action="store_true", help="Show what would be done without making changes"
    )
    parser.add_argument("--json", action="store_true", help="Output machine-readable JSON")

    subparsers = parser.add_subparsers(dest="command", help="Commands")

    # Enable command
    enable_parser = subparsers.add_parser("enable", help="Enable GitHub Pages")
    enable_parser.add_argument("repo", help="Repository in format owner/repo")
    enable_parser.add_argument("--branch", default="main", help="Source branch (default: main)")
    enable_parser.add_argument(
        "--path", default="/", choices=["/", "/docs"], help="Source path (default: /)"
    )
    enable_parser.add_argument(
        "--build-type",
        default="workflow",
        choices=["workflow", "legacy"],
        help="Build type: workflow (GitHub Actions) or legacy (Jekyll)",
    )
    enable_parser.add_argument("--no-https", action="store_true", help="Disable HTTPS enforcement")

    # Status command
    status_parser = subparsers.add_parser("status", help="Check Pages status")
    status_parser.add_argument("repo", help="Repository in format owner/repo")
    status_parser.add_argument(
        "--build-info", action="store_true", help="Show latest build information"
    )

    # Rebuild command
    rebuild_parser = subparsers.add_parser("rebuild", help="Trigger a new build")
    rebuild_parser.add_argument("repo", help="Repository in format owner/repo")

    # Create workflow command
    workflow_parser = subparsers.add_parser(
        "create-workflow", help="Create GitHub Actions workflow file"
    )
    workflow_parser.add_argument(
        "--output", help="Output path (default: .github/workflows/pages.yml)"
    )
    workflow_parser.add_argument("--force", action="store_true", help="Overwrite existing file")

    args = parser.parse_args()

    if not args.command:
        parser.print_help()
        sys.exit(1)

    try:
        if args.command == "enable":
            manager = GitHubPagesManager(args.repo, dry_run=args.dry_run, json_output=args.json)
            manager.enable_pages(
                branch=args.branch,
                path=args.path,
                build_type=args.build_type,
                https_enforced=not args.no_https,
            )

            if args.build_type == "workflow" and not args.json:
                print("\nTip: Create a deployment workflow with:")
                print("   gh pages create-workflow")

        elif args.command == "status":
            manager = GitHubPagesManager(args.repo, json_output=args.json)
            manager.check_status()

            if args.build_info:
                manager.get_latest_build()

        elif args.command == "rebuild":
            manager = GitHubPagesManager(args.repo, dry_run=args.dry_run, json_output=args.json)
            manager.trigger_rebuild()

        elif args.command == "create-workflow":
            create_workflow_file(args.output, args.force)

    except KeyboardInterrupt:
        print("\nCancelled by user.", file=sys.stderr)
        sys.exit(130)
    except GitHubPagesError as e:
        result = {"status": "error", "error": str(e)}
        print(format_json(result))
        sys.exit(1)
    except Exception as e:
        result = {"status": "error", "error": str(e)}
        print(format_json(result))
        sys.exit(1)


if __name__ == "__main__":
    main()