Skip to content

Instantly share code, notes, and snippets.

@3v0k4
Last active March 31, 2023 11:06
Show Gist options
  • Save 3v0k4/06d1110b30ff7b05dcd3be372130a0e8 to your computer and use it in GitHub Desktop.
Save 3v0k4/06d1110b30ff7b05dcd3be372130a0e8 to your computer and use it in GitHub Desktop.
git amend-files

If you like me have OCCD, obsessive-compulsive-commit-disorder, you create a ton of local commits and amend/squash/fixup stuff before a git push.

Unfortunately, git commit --amend only works if you are adding to the most recent commit. But if you want to add the current file(s) changes to the latest commit that changed them, you have to rebase manually and fix up.

No more.

This is what git amend-files does:

  • Finds all modified files in the working directory.
  • Gets the hash of the most recent commit that modified each file.
  • Checks that all modified files have the same previous commit hash.
  • Stages all modified files for the next commit.
  • Creates a new commit that fixes the previous commit.
  • Opens the code editor and wait for you to confirm the fixup into the previous commit.
#!/bin/bash
set -e
paths=$(git status --porcelain | awk '{print $2}')
if [[ -z "$paths" ]]; then
echo "Error: Found no modified files."
exit 1
fi
prevcommits=()
for path in $paths; do
hash=$(git log -n 1 --pretty=format:%h -- "$path")
prevcommits+=("$hash")
done
prevcommit=${prevcommits[0]}
for hash in ${prevcommits[@]}; do
if [[ "$hash" != "$prevcommit" ]]; then
echo "Error: Found modified files with different previous commits."
exit 1
fi
done
alreadypushed=$(git branch --remote --contains $prevcommit | grep $(git rev-parse --abbrev-ref HEAD) | wc -l | xargs)
if [[ $alreadypushed -gt 0 ]]; then
echo "Error: Commit is already on remote."
exit 1
fi
git add "$paths"
git commit --fixup $prevcommit
git rebase --interactive --autosquash $prevcommit~
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment