Comprehensive Guide to Automate Git Operations and Pull Requests

·

5 min read

Automation can save developers time and effort, especially when performing repetitive tasks like committing changes, pushing them to a remote repository, and raising pull requests (PRs). In this article, we'll explore how to implement this automation with a script and configure it to run globally on any operating system. This guide provides step-by-step instructions for Windows, macOS, and Linux users.


1. Prerequisites

Before you begin, ensure you have the following installed on your system:

  • Git: Install Git from git-scm.com and ensure it is accessible from the command line.

  • GitHub CLI (gh): Install the GitHub CLI from cli.github.com.

    • After installation, authenticate using:

        gh auth login
      

Follow: https://cli.github.com/manual/gh_auth_login

  • Text Editor: Any text editor (e.g., VS Code, Notepad++, Nano, Vim).

2. Writing the Script

Script Overview

The script performs the following steps:

  1. Detects the current Git branch.

  2. Stages and commits changes.

  3. Pushes the changes to the remote branch.

  4. Creates a pull request against a target branch.

    Example Workflow

    1. You are currently on the dev branch of your project.

    2. You make changes to the code, like fixing a UI bug.

    3. The script detects the current branch (dev), stages your changes, and commits them with a message like "Fix UI bug on homepage."

    4. It then pushes these changes to the remote dev branch.

    5. Finally, the script creates a pull request from the dev branch to the main branch with a specified title and description.

Result*: Your changes are now ready for review and merge in the main branch.*

The Script

Create a file named git_commit_push_pr.sh and add the following code:

#!/bin/bash

# Variables
TARGET_BRANCH=${1:-main}   # Default target branch is 'main'
COMMIT_MESSAGE=${2:-"Auto-commit changes"}
PR_TITLE=${3:-"Auto-created Pull Request"}
PR_BODY=${4:-"This PR was created via script."}

# Step 1: Get the current branch name
CURRENT_BRANCH=$(git branch --show-current)
if [ -z "$CURRENT_BRANCH" ]; then
  echo "You are not in a Git repository or on a valid branch. Exiting..."
  exit 1
fi
echo "Current branch detected: $CURRENT_BRANCH"

# Step 2: Check for uncommitted changes
if ! git diff-index --quiet HEAD --; then
  echo "Adding and committing changes..."
  git add .
  git commit -m "$COMMIT_MESSAGE"
fi

# Step 3: Pull the latest changes from the remote target branch
echo "Pulling latest changes from $TARGET_BRANCH..."
if ! git pull origin "$TARGET_BRANCH" --rebase; then
  echo "Merge conflicts detected! Please resolve them manually before running the script again."
  exit 1
fi

# Step 4: Push changes to the remote branch
echo "Pushing changes to remote branch: $CURRENT_BRANCH"
if ! git push -u origin "$CURRENT_BRANCH"; then
  echo "Failed to push changes. Resolve conflicts or ensure the branch is up-to-date."
  exit 1
fi

# Step 5: Raise a pull request
echo "Raising a pull request against branch: $TARGET_BRANCH"
if ! gh pr create --base "$TARGET_BRANCH" --head "$CURRENT_BRANCH" --title "$PR_TITLE" --body "$PR_BODY"; then
  echo "Failed to create a pull request. Ensure 'gh' CLI is configured properly."
  exit 1
fi

echo "Pull request created successfully!"

3. Making the Script Globally Accessible

To run the script from any directory, you need to configure it globally.

3.1 Windows

  1. Save the Script:

    • Save the script as git_commit_push_pr.sh in a directory. Create a new folder global-scripts in C directory, e.g., C:\global-scripts.
  2. Install Git Bash:

    • Ensure Git Bash is installed and accessible from your system.
  3. Create a Batch Wrapper:

    • Create a git_commit_push_pr.bat file in the same directory (C:\global-scripts) with the following content:

    • Why to create git_commit_push_pr.bat file, because Windows Command Prompt (CMD) does not recognize Bash scripts (.sh) directly. To make the script work in CMD as well.

        @echo off
        "C:\Program Files\Git\bin\bash.exe" C:\global-scripts\git_commit_push_pr.sh %*
      

This is how your directory should look like; with two scripts.

  1. Add Directory to PATH:

    • Add C:\global-scripts to your system's PATH:

      1. Right-click This PCPropertiesAdvanced System SettingsEnvironment Variables.

      2. Under "System Variables", select PathEdit → Add C:\global-scripts.

  2. Test the Script:

    • Open Command Prompt or Git Bash and run:

        #Test the script, Default target to 'main' branch
        git_commit_push_pr 
      
        #Run the script, by specifying target branch, commit messaage, PR title and PR body
        git_commit_push_pr [target_branch] [commit_message] [pr_title] [pr_body]
      
        #Example:
        #Specify target branch and commit message:
        git_commit_push_pr development "Fix bugs" "Bug Fix PR" "Resolved critical bugs."
        # where;
        # 'development' is the target branch you are pushing your code to from your feature branch.
        # "Fix bugs" serves as the commit message.
        # "Bug Fix PR" is the title of your pull request.
        # "Resolved critical bugs." is the description or body of your pull request.
      

3.2 macOS and Linux

  1. Save the Script:

    • Save the script as git_commit_push_pr.sh in a directory, e.g., /usr/local/bin.
  2. Make the Script Executable:

    • Run the following commands in your terminal:

        chmod +x /usr/local/bin/git_commit_push_pr.sh
      
  3. Create a Shell Alias (Optional):

    • Add an alias to your shell configuration file (e.g., ~/.bashrc, ~/.zshrc):

        alias git_commit_push_pr="/usr/local/bin/git_commit_push_pr.sh"
      
    • Reload the shell configuration:

        source ~/.bashrc
      
  4. Test the Script:

    • Open the terminal and run:

        git_commit_push_pr
      

4. Handling Edge Cases

4.1 Merge Conflicts

If the branch has merge conflicts, the script will fail to push changes. You must resolve conflicts manually:

  1. Check for conflicts:

     git status
    
  2. Resolve conflicts in the affected files.

  3. Add the resolved files and re-run the script:

     git add .
     git_commit_push_pr
    

4.2 No Changes to Commit

If there are no changes to commit, the script will exit after displaying the following message:

Nothing to commit, working tree clean.

5. Verifying the Setup

After completing the setup:

  1. Navigate to any Git repository.

  2. Make some changes to the files.

  3. Run the script:

     git_commit_push_pr
    
  4. Verify that:

    • Changes are committed.

    • Changes are pushed to the remote branch.

    • A pull request is created on GitHub.


6. Customizing the Script

You can enhance the script to:

  • Accept commit messages as arguments:

      COMMIT_MESSAGE="$1"
    
  • Accept target branches dynamically.

  • Add logging for better debugging.


7. Conclusion

By automating the Git workflow, you can focus more on coding and less on repetitive tasks. This guide has shown you how to:

  • Write a script to automate Git operations.

  • Configure the script globally for Windows, macOS, and Linux.

  • Handle edge cases like merge conflicts and empty commits.

Feel free to customize the script to suit your workflow and share it with your team to boost productivity!