Created
December 13, 2023 06:20
-
-
Save aquilax/4903a4efe0728aa72e99aca87f230bc0 to your computer and use it in GitHub Desktop.
Script to auto-create fixup commits towards the first change in the branch
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 | |
set -e | |
# Function to create fixup commits for changed files | |
create_fixup_commits() { | |
target_branch="${1:-origin/develop}" | |
# Get the list of changed files | |
changed_files=$(git diff --name-only) | |
# Iterate over each changed file | |
while IFS= read -r file; do | |
if [ -z "$file" ]; then | |
echo "No changes found" | |
exit 1 | |
fi | |
# Find the most recent commit that changed this file | |
first_commit=$(git log --reverse --follow "$target_branch"..HEAD --pretty=format:"%H" -- "$file" | head -1) | |
if [ -n "$first_commit" ]; then | |
commit_message=$(git log --format=%B -n 1 "$first_commit" | head -1) | |
# Create the fixup commit | |
echo "git commit --fixup=$first_commit $file # $commit_message" | |
if [ "$dry_run" = false ]; then | |
git commit --fixup="$first_commit" "$file" | |
fi | |
fi | |
done <<< "$changed_files" | |
} | |
# Parse command-line options using getopts | |
dry_run=false | |
while getopts ":n" opt; do | |
case $opt in | |
n) | |
dry_run=true | |
;; | |
\?) | |
echo "Invalid option: -$OPTARG" | |
exit 1 | |
;; | |
esac | |
done | |
# Shift the options so that $1 now refers to the first argument (if provided) | |
shift $((OPTIND - 1)) | |
# Call the function to create fixup commits | |
create_fixup_commits "$1" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment