Home/Learnings/automate-git-workflow

Automate your Git Workflow using AI

Table of Contents


Prerequisites


Step 1: Create the Script File

  1. Open your favorite Text editor and create a new file.

  2. Copy and paste the following Bash Script:

    #!/bin/bash
    # git_auto_commit.sh
     
    if ! git rev-parse --git-dir > /dev/null 2>&1; then
     echo "Error: This directory is not a Git repository."
     exit 1
    fi
     
    if git diff-index --quiet HEAD --; then
     echo "No changes detected. Exiting."
     exit 0
    fi
     
    echo "Staging changes..."
    git add .
     
    summary=$(git diff --cached --name-only)
     
    echo "Generating commit message suggestion from Ollama phi3.5..."
    suggested_commit_msg=$(ollama run phi3.5 ""Generate a concise yet informative commit message that accurately summarizes the following code changes. The message should be clear, professional, and follow best practices for commit messages. Aim to describe the purpose and impact of the changes in a way that is easy to understand. Avoid unnecessary details but ensure the key modifications are covered. Format the message in an imperative style (e.g., 'Fix bug in authentication flow' instead of 'Fixed a bug...'). Here are the changes to summarize: $summary")
     
    echo "Suggested commit message:"
    echo "$suggested_commit_msg"
     
    read -p "Edit commit message? (y/n): " choice
     
    if [[ "$choice" =~ ^[Yy]$ ]]; then
       echo "Enter your commit message below. Press Ctrl+D when done."
       commit_msg=$(cat)  # Reads multiline input until Ctrl+D
    else
       commit_msg="$suggested_commit_msg"
    fi
     
    git commit -m "$commit_msg"
    git push origin master
    echo "Done!"
  3. Save the file as git_auto_commit.sh.


Step 2: Add the Script to Your Global Bin Directory

  1. Create a bin directory if it doesn’t exist:
    mkdir -p ~/bin
  2. Move the script to this directory:
    mv /path/to/git_auto_commit.sh ~/bin/

Step 3: Make the Script Executable inside a bash terminal.

  1. You can use Git Bash as well to execute it here
    chmod +x ~/bin/git_auto_commit.sh

Step 4: Add the Script Directory to Your PATH

  1. Open ~/.bashrc or ~/.bash_profile:
    nano ~/.bashrc
  2. Add this line at the end:
    export PATH="$HOME/bin:$PATH"
  3. Save and apply changes:
    source ~/.bashrc

Step 5: Testing the Script

  1. Navigate to a Git repository.
  2. Run:
    git_auto_commit.sh
  3. Follow the prompts.

Additional Notes


This script is now globally available and automates your Git workflow! πŸš€