Skip to content

Instantly share code, notes, and snippets.

@LisannaAtHome
Created July 9, 2019 06:50
Show Gist options
  • Save LisannaAtHome/dcc6c2ba4c57958da9d9b2956caec81b to your computer and use it in GitHub Desktop.
Save LisannaAtHome/dcc6c2ba4c57958da9d9b2956caec81b to your computer and use it in GitHub Desktop.
Better git commit viewing and editing

I created these small git commands to help make exploring commits and editing them easier.

The first set of commands, git uc (Undo Commit) and git rc (Redo Commit), will undo a commit while saving the commit message and keeping the changes staged, so you can make changes to the commit and re-perform the commit while having the original commit message restored. Example:

$ git uc
...make edits to staged changes...
$ git rc
...update commit message, original one is loaded into editor...

git rc accepts any additional arguments that git commit will accept.

The second set of commands, git uuc (Unstage and Undo Commit) and git urc (Unstaged Restore Commit) are meant to be used as a way to make examining a commit's diff easier. When using an editor like Visual Studio Code, you can usually see your unstaged changes highlighted in some way in the editor. Using git uuc will let you view a commit as if it was still an unstaged change, by undoing it (with git uc) and unstaging all changes. The commit SHA is saved by this command, so to recover the commit use git urc to put things back the way they were. Example:

$ git uuc
...view changes in visual editor...
$ git urc

Please don't use any of these without fully understanding what they're doing, as they probably have lots of corner cases that could mess up your repository.

#! /usr/bin/env bash
set -eu
set -o pipefail
if ! [ -e ./.git_uc ]; then
echo "No previous commit message found to restore. Did you run git uc?"
exit 1
fi
git commit --file ./.git_uc --edit "$@"
rm ./.git_uc
#! /usr/bin/env bash
# Undos a commit while keeping its changes staged, and saves the commit message for restoring with git-rc
set -eu
set -o pipefail
if [ -e ./.git_uc ] ; then
echo "./.git_uc already exists, meaning you're already undoing a commit! Run git rc or delete the file."
exit 1
fi
git log -1 --pretty=%B > ./.git_uc
git reset --soft HEAD~1
echo "Last commit undone and message saved. Make changes to staged files and then run git rc to commit using the saved commit message."
#! /usr/bin/env bash
set -eu
set -o pipefail
if ! [ -e ./.git_uuc_sha ]; then
echo "./.git_uuc_sha doesn't exist, did you run git uuc first?"
exit 1
fi
git reset --hard $(cat ./.git_uuc_sha)
rm ./.git_uuc_sha
#! /usr/bin/env bash
set -eu
set -o pipefail
git rev-parse HEAD > ./.git_uuc_sha # save SHA in case of git urc
git uc
git reset
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment