Skip to content

Instantly share code, notes, and snippets.

@lacymorrow
Created July 19, 2025 12:12
Show Gist options
  • Save lacymorrow/c6c5b345444665cd1f5644fceffb9d44 to your computer and use it in GitHub Desktop.
Save lacymorrow/c6c5b345444665cd1f5644fceffb9d44 to your computer and use it in GitHub Desktop.
Create a pull request an entire branch, to trigger code review bots
#!/bin/bash
# Exit on any error
set -e
# Generate timestamp for unique branch names
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
# Default configuration
EMPTY_BRANCH="empty-base-$TIMESTAMP"
FEATURE_BRANCH="full-review-$TIMESTAMP"
MAIN_BRANCH="main"
CLEANUP_MODE=false
# Help message
show_help() {
echo "Usage: $0 [branch_name] [options]"
echo ""
echo "Arguments:"
echo " branch_name Source branch name (default: main)"
echo ""
echo "Options:"
echo " -e, --empty-branch NAME Base name for empty branch (will be appended with timestamp)"
echo " -f, --feature-branch NAME Base name for feature branch (will be appended with timestamp)"
echo " --cleanup Delete all existing code review branches (full-review-* and empty-base-*)"
echo " -h, --help Show this help message"
exit 0
}
# Function to cleanup all code review branches
cleanup_all_branches() {
echo "Cleaning up all code review branches..."
# Check for uncommitted changes before cleanup
CLEANUP_STASH_CREATED=false
if ! git diff --quiet || ! git diff --cached --quiet; then
echo "Warning: You have uncommitted changes."
echo "Stashing changes to prevent data loss during cleanup..."
git stash push -m "Auto-stash before cleanup - $(date)"
CLEANUP_STASH_CREATED=true
echo "Changes stashed successfully."
fi
# Get current branch to return to it later
CURRENT_BRANCH=$(git symbolic-ref --short HEAD || echo "HEAD")
# Switch to main branch for cleanup
git checkout "$MAIN_BRANCH"
# Find and delete local branches matching pattern
echo "Deleting local branches..."
for branch in $(git branch --format='%(refname:short)' | grep -E '^(full-review-|empty-base-)' || true); do
if [ -n "$branch" ]; then
echo " Deleting local branch: $branch"
git branch -D "$branch"
fi
done
# Find and delete remote branches matching pattern
echo "Deleting remote branches..."
for branch in $(git ls-remote --heads origin | grep -E '(full-review-|empty-base-)' | awk '{print $2}' | sed 's|refs/heads/||' || true); do
if [ -n "$branch" ]; then
echo " Deleting remote branch: $branch"
git push origin --delete "$branch"
fi
done
# Return to original branch if it still exists
if git show-ref --verify --quiet "refs/heads/$CURRENT_BRANCH"; then
git checkout "$CURRENT_BRANCH"
fi
# Restore stashed changes if any were stashed
if [ "$CLEANUP_STASH_CREATED" = true ]; then
echo "Restoring your stashed changes..."
git stash pop
echo "Changes restored successfully."
fi
echo "Cleanup completed!"
exit 0
}
# First check if the first argument is a branch name (not starting with -)
if [ $# -gt 0 ] && [[ ! $1 =~ ^- ]]; then
MAIN_BRANCH="$1"
shift
fi
# Parse remaining command line arguments
while [[ $# -gt 0 ]]; do
case $1 in
-e|--empty-branch)
EMPTY_BRANCH="$2-$TIMESTAMP"
shift 2
;;
-f|--feature-branch)
FEATURE_BRANCH="$2-$TIMESTAMP"
shift 2
;;
--cleanup)
CLEANUP_MODE=true
shift
;;
-h|--help)
show_help
;;
*)
echo "Unknown option: $1"
show_help
;;
esac
done
# If cleanup mode, run cleanup and exit
if [ "$CLEANUP_MODE" = true ]; then
cleanup_all_branches
fi
# Check if gh CLI is installed
if ! command -v gh &> /dev/null; then
echo "Error: GitHub CLI (gh) is not installed. Please install it first:"
echo " macOS: brew install gh"
echo " Linux: https://github.com/cli/cli#installation"
exit 1
fi
# Check if gh is authenticated
if ! gh auth status &> /dev/null; then
echo "Error: GitHub CLI is not authenticated. Please run 'gh auth login' first."
exit 1
fi
# Function to check if branch exists
branch_exists() {
git show-ref --verify --quiet "refs/heads/$1"
}
# Function to check if branch exists on remote
remote_branch_exists() {
git ls-remote --exit-code --heads origin "$1" &> /dev/null
}
# Store current branch
ORIGINAL_BRANCH=$(git symbolic-ref --short HEAD || echo "HEAD")
echo "Starting code review automation process..."
echo "Using source branch: $MAIN_BRANCH"
echo "Empty branch: $EMPTY_BRANCH"
echo "Feature branch: $FEATURE_BRANCH"
echo "Branches will be kept after PR creation (use --cleanup to remove all code review branches)"
# Check if we're in a git repository
if ! git rev-parse --is-inside-work-tree &> /dev/null; then
echo "Error: Not in a git repository"
exit 1
fi
# Check for uncommitted changes
STASH_CREATED=false
if ! git diff --quiet || ! git diff --cached --quiet; then
echo "Warning: You have uncommitted changes."
echo "Stashing changes to prevent data loss..."
git stash push -m "Auto-stash before code review automation - $(date)"
STASH_CREATED=true
echo "Changes stashed successfully."
fi
# Check if main branch exists
if ! branch_exists "$MAIN_BRANCH"; then
echo "Error: Branch '$MAIN_BRANCH' does not exist"
exit 1
fi
# Create empty branch from main first
if branch_exists "$EMPTY_BRANCH" || remote_branch_exists "$EMPTY_BRANCH"; then
echo "Error: Branch '$EMPTY_BRANCH' already exists. Please delete it first or use a different name."
exit 1
fi
echo "Creating empty branch..."
git checkout "$MAIN_BRANCH"
git checkout -b "$EMPTY_BRANCH"
# Remove all files except .git
find . -mindepth 1 -maxdepth 1 -not -name '.git' -exec rm -rf {} +
git add -A
git commit -m "Empty state for code review"
git push origin "$EMPTY_BRANCH"
# Create feature branch from main
if branch_exists "$FEATURE_BRANCH" || remote_branch_exists "$FEATURE_BRANCH"; then
echo "Error: Branch '$FEATURE_BRANCH' already exists. Please delete it first or use a different name."
git checkout "$ORIGINAL_BRANCH"
exit 1
fi
echo "Creating feature branch..."
git checkout "$MAIN_BRANCH"
git checkout -b "$FEATURE_BRANCH"
# Add a marker file to ensure there's a commit difference
echo "# Code review marker - created at $TIMESTAMP" > .code-review-marker
git add .code-review-marker
git commit -m "Add code review marker"
git push origin "$FEATURE_BRANCH"
# Create pull request using GitHub CLI
echo "Creating pull request..."
PR_URL=$(gh pr create \
--base "$EMPTY_BRANCH" \
--head "$FEATURE_BRANCH" \
--title "Full Codebase Review ($TIMESTAMP)" \
--body "This PR is created to trigger a full codebase review by comparing against an empty branch.")
echo "Process completed! PR created at: $PR_URL"
echo ""
echo "Branches created:"
echo " - $EMPTY_BRANCH"
echo " - $FEATURE_BRANCH"
echo ""
echo "To cleanup all code review branches later, run:"
echo " $0 --cleanup"
# Return to original branch
git checkout "$ORIGINAL_BRANCH"
# Restore stashed changes if any were stashed
if [ "$STASH_CREATED" = true ]; then
echo "Restoring your stashed changes..."
git stash pop
echo "Changes restored successfully."
fi
echo "Done!"
@lacymorrow
Copy link
Author

lacymorrow commented Jul 19, 2025

Automated Code Review Trigger Script

Automate full codebase code reviews by creating a PR that compares your entire codebase against an empty branch.

Overview

This script solves a common problem: triggering AI code review tools (like CodeRabbit, Sourcery, etc.) to analyze your entire codebase when they've never been run before. These tools typically only analyze changed files in PRs, but this script creates a special PR that shows every file as "added" by comparing against an empty branch.

How It Works

  1. Creates an empty branch - A branch with all files removed
  2. Creates a feature branch - Your full codebase with a marker file
  3. Creates a PR - Comparing empty → full, showing all files as additions
  4. Triggers code review tools - AI tools analyze the entire codebase as "new" code

Features

  • Safe: Automatically stashes/restores uncommitted changes
  • Timestamped branches: Unique branch names prevent conflicts
  • Configurable: Custom branch names and source branches
  • Cleanup mode: Bulk delete all code review branches
  • Error handling: Comprehensive checks and validations
  • GitHub CLI integration: Automatic PR creation

Prerequisites

  1. GitHub CLI (gh) installed and authenticated
  2. Git repository with a main/master branch
  3. Push access to the repository

Installation

curl -O https://gist.githubusercontent.com/c6c5b345444665cd1f5644fceffb9d44/trigger-code-review.sh
chmod +x trigger-code-review.sh

Usage

Basic Usage

# Use default 'main' branch
./trigger-code-review.sh

# Use specific source branch
./trigger-code-review.sh master

Advanced Options

# Custom branch names
./trigger-code-review.sh main --empty-branch "baseline" --feature-branch "review"

# Cleanup all code review branches
./trigger-code-review.sh --cleanup

Help

./trigger-code-review.sh --help

Examples

Trigger full codebase review:

$ ./trigger-code-review.sh
Starting code review automation process...
Using source branch: main
Empty branch: empty-base-20240319-143022
Feature branch: full-review-20240319-143022
Branches will be kept after PR creation (use --cleanup to remove all code review branches)

Creating empty branch...
Creating feature branch...
Creating pull request...
Process completed! PR created at: https://github.com/user/repo/pull/123

Branches created:
  - empty-base-20240319-143022
  - full-review-20240319-143022

To cleanup all code review branches later, run:
  ./trigger-code-review.sh --cleanup
Done!

Cleanup old branches:

$ ./trigger-code-review.sh --cleanup
Cleaning up all code review branches...
Deleting local branches...
  Deleting local branch: empty-base-20240319-143022
  Deleting local branch: full-review-20240319-143022
Deleting remote branches...
  Deleting remote branch: empty-base-20240319-143022
  Deleting remote branch: full-review-20240319-143022
Cleanup completed!

Options

Option Description
branch_name Source branch to review (default: main)
-e, --empty-branch NAME Base name for empty branch (timestamp appended)
-f, --feature-branch NAME Base name for feature branch (timestamp appended)
--cleanup Delete all existing code review branches
-h, --help Show help message

Safety Features

  • Auto-stash: Uncommitted changes are automatically stashed before operations
  • Auto-restore: Changes are restored when returning to original branch
  • Branch validation: Checks for existing branches to prevent conflicts
  • Error handling: Comprehensive validation and error messages
  • Original branch: Always returns to your starting branch

Branch Naming

Branches are created with timestamps to ensure uniqueness:

  • Empty branch: empty-base-YYYYMMDD-HHMMSS
  • Feature branch: full-review-YYYYMMDD-HHMMSS

Custom names still get timestamps: --empty-branch "baseline"baseline-YYYYMMDD-HHMMSS

Use Cases

  1. First-time setup - Run code review tools on existing codebases
  2. Periodic full reviews - Comprehensive analysis of entire codebase
  3. Baseline establishment - Create a reference point for code quality
  4. Tool evaluation - Test different AI code review tools on your codebase
  5. Compliance audits - Generate reports covering all code

Compatible Tools

This script works with any PR-based code review tool:

  • CodeRabbit
  • Sourcery
  • Codacy
  • SonarCloud
  • DeepCode
  • GitHub Copilot
  • Custom GitHub Actions

Troubleshooting

GitHub CLI not authenticated:

gh auth login

Branch already exists:
The script uses timestamps to prevent conflicts, but you can delete existing branches:

./trigger-code-review.sh --cleanup

No commits between branches:
This was a previous issue that's been resolved. The script now ensures proper commit differences.

Technical Details

The script creates two branches from your source branch:

  1. Empty branch: Removes all files, commits empty state
  2. Feature branch: Keeps all files, adds a marker file

This ensures both branches share common git history (required by GitHub) while having maximum differences for code review tools to analyze.

License

MIT License - Feel free to modify and distribute.

Contributing

Suggestions and improvements welcome! This script can be enhanced with:

  • Support for other git platforms (GitLab, Bitbucket)
  • Integration with specific code review tools
  • Batch processing for multiple repositories
  • Configuration file support

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment