Skip to main content

Overview

The protect-repo command applies comprehensive security protections to a GitHub repository, including repository-level settings and branch protection rulesets. It enforces pyrig’s opinionated security defaults to maintain code quality and prevent accidental destructive operations.
uv run pyrig protect-repo
Requires a REPO_TOKEN environment variable with repo scope permissions. The command will fail if the token is not found.

What It Does

The command configures two levels of protection:

Repository Settings

  • Sets repository description from pyproject.toml
  • Sets default branch to main
  • Enables “delete branch on merge”
  • Disables merge commits (enforces squash and rebase only)

Branch Protection Rules

  • Requires pull request reviews with code owner approval
  • Requires status checks to pass (health check workflow)
  • Requires linear commit history
  • Requires signed commits
  • Disables force pushes
  • Disables branch deletions
The command is idempotent: safe to run multiple times, updates existing rulesets instead of creating duplicates.

Usage

Basic Usage

# Set REPO_TOKEN environment variable first
export REPO_TOKEN=ghp_your_token_here

# Apply protections
uv run pyrig protect-repo

Using .env File

# Create .env file
echo "REPO_TOKEN=ghp_your_token_here" > .env

# Run command (automatically loads from .env)
uv run pyrig protect-repo

With Verbose Output

# See detailed protection application
uv run pyrig -v protect-repo

# See API calls and responses
uv run pyrig -vv protect-repo

Quiet Mode

# Only show warnings and errors
uv run pyrig -q protect-repo

Expected Output

$ uv run pyrig protect-repo
Configuring repository settings...
 Updated repository description
 Set default branch to 'main'
 Enabled delete branch on merge
 Disabled merge commits

Applying branch protection rules...
 Created/updated branch protection ruleset
 Repository protection configured successfully
$ uv run pyrig -v protect-repo
DEBUG: Loading REPO_TOKEN from environment
INFO: Configuring repository settings
DEBUG: Setting description from pyproject.toml
DEBUG: Setting default branch to 'main'
INFO: Applying branch protection rules
DEBUG: Loading rules from branch-protection.json
DEBUG: Creating ruleset via GitHub API
 Repository protection configured successfully

Prerequisites

GitHub Personal Access Token

Create a token with repo scope:
1

Go to GitHub Settings

Navigate to Settings → Developer settings → Personal access tokens → Tokens (classic)
2

Generate new token

Click “Generate new token (classic)”
3

Select scopes

Check the repo scope (full control of private repositories)
4

Generate and copy

Click “Generate token” and copy the token (starts with ghp_)
5

Set environment variable

export REPO_TOKEN=ghp_your_token_here
# Or add to .env file
echo "REPO_TOKEN=ghp_your_token_here" >> .env
Keep your token secure! Never commit it to version control. The .env file should be in .gitignore.

Protection Rules

Rules are loaded from branch-protection.json in your project root:
{
  "name": "Branch Protection",
  "target": "branch",
  "enforcement": "active",
  "conditions": {
    "ref_name": {
      "include": ["refs/heads/main"],
      "exclude": []
    }
  },
  "rules": [
    {
      "type": "pull_request",
      "parameters": {
        "require_code_owner_review": true,
        "required_approving_review_count": 1
      }
    },
    {
      "type": "required_status_checks",
      "parameters": {
        "required_status_checks": [
          {"context": "health-check"}
        ]
      }
    },
    {
      "type": "required_linear_history"
    },
    {
      "type": "required_signatures"
    },
    {
      "type": "non_fast_forward"
    },
    {
      "type": "deletion"
    }
  ]
}

Customizing Protection Rules

To customize the protection rules:
1

Generate default config

uv run pyrig mkroot  # Creates branch-protection.json
2

Edit branch-protection.json

Modify the rules according to your needs:
{
  "rules": [
    {
      "type": "pull_request",
      "parameters": {
        "required_approving_review_count": 2  # Require 2 approvals
      }
    }
  ]
}
3

Apply updated rules

uv run pyrig protect-repo

Behavior

Token Lookup
environment
Checks REPO_TOKEN in environment variables first, then falls back to .env file.
Repository Detection
automatic
Automatically detects the GitHub repository from Git remote configuration.
Idempotency
guaranteed
Updates existing rulesets instead of creating duplicates. Safe to run multiple times.
Ruleset Loading
json-file
Loads protection rules from branch-protection.json in the project root.

Applied Settings

Repository-Level

SettingValuePurpose
DescriptionFrom pyproject.tomlKeeps repo description in sync
Default branchmainStandard default branch
Delete branch on mergeEnabledKeeps repository clean
Merge commitsDisabledEnforces linear history

Branch Protection

RuleConfigurationPurpose
Pull requestsRequired with code owner approvalEnsures code review
Status checksHealth check must passEnsures CI passes
Linear historyRequiredPrevents merge commits
Signed commitsRequiredEnsures commit authenticity
Force pushesDisabledPrevents history rewriting
Branch deletionDisabledProtects main branch

When to Use

Use protect-repo When:

  • Setting up a new repository
  • Enforcing security standards across an organization
  • Updating protection rules after policy changes
  • Ensuring compliance with security requirements
  • Migrating from manual protection settings

Example Workflow

1

Initialize project

uv run pyrig init
2

Create GitHub repository

gh repo create --private --source=.
3

Set token

export REPO_TOKEN=ghp_your_token_here
4

Apply protection

uv run pyrig protect-repo

Troubleshooting

Missing Token Error

ERROR: REPO_TOKEN not found in environment or .env file
Solution: Set the REPO_TOKEN environment variable:
export REPO_TOKEN=ghp_your_token_here

Insufficient Permissions

ERROR: GitHub API returned 403 Forbidden
Solution: Ensure your token has repo scope permissions.

Repository Not Found

ERROR: Could not determine GitHub repository
Solution: Ensure you’re in a Git repository with a GitHub remote:
git remote -v
This command makes destructive changes to repository settings. Review the protection rules before applying them to production repositories.

Security Considerations

  • Token Security: Store REPO_TOKEN securely, never commit to version control
  • Scope Limitation: Use tokens with minimal required scopes
  • Token Rotation: Rotate tokens regularly
  • Audit Logs: Review GitHub audit logs for protection changes
  • Team Access: Ensure team members understand the protection rules
  • init - Full project initialization
  • mkroot - Generate branch-protection.json

Implementation

The protect-repo command calls RepoProtectionConfigFile.I.protect_repo(), which:
  1. Loads REPO_TOKEN from environment or .env
  2. Reads branch-protection.json
  3. Applies repository settings via GitHub API
  4. Creates/updates branch protection rulesets
See pyrig/rig/cli/commands/protect_repo.py:10.
Run uv run pyrig protect-repo --help to see the command’s built-in help text.

Build docs developers (and LLMs) love