Created
December 26, 2024 15:34
-
-
Save geniusmonir/e18f32d19a470b8364a4ad9de1236a76 to your computer and use it in GitHub Desktop.
Prevent Branch Checkout if file modified or not pushed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # Get the current branch name | |
| branch=$(git symbolic-ref --short HEAD) | |
| # Function to check if there are uncommitted changes | |
| has_uncommitted_changes() { | |
| # Check if there are modified, added, or deleted files in the working directory | |
| git diff --quiet || return 0 # If there are changes, return 0 (true) | |
| git diff --cached --quiet || return 0 # Check staged changes | |
| return 1 # No changes if we reached here | |
| } | |
| # Function to check if the branch has unpushed commits | |
| has_unpushed_commits() { | |
| # Fetch the latest changes from the remote repository | |
| git fetch origin | |
| # Compare local and remote commit counts | |
| local local_commit_count=$(git rev-list --count HEAD) | |
| local remote_commit_count=$(git rev-list --count origin/"$branch") | |
| if [ "$local_commit_count" -gt "$remote_commit_count" ]; then | |
| return 0 # Unpushed commits found | |
| else | |
| return 1 # No unpushed commits | |
| fi | |
| } | |
| # Function to block checkout if there are uncommitted changes or unpushed commits | |
| prevent_checkout() { | |
| # Check for uncommitted changes | |
| if has_uncommitted_changes; then | |
| echo "ERROR: You have uncommitted changes in your working directory. Please commit or stash them before switching branches." | |
| exit 1 # Prevent checkout if there are uncommitted changes | |
| fi | |
| # Check for unpushed commits | |
| if has_unpushed_commits; then | |
| echo "ERROR: You have unpushed commits. Please push your changes before switching branches." | |
| exit 1 # Prevent checkout if there are unpushed commits | |
| fi | |
| # If no issues, allow checkout to proceed | |
| echo "All checks passed. You can proceed with the checkout." | |
| } | |
| # Run the prevent_checkout function to check before switching branches | |
| prevent_checkout | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment