Last active
January 16, 2022 17:51
-
-
Save DarkOoze/69593c63977bf445223c421bf4a69ba3 to your computer and use it in GitHub Desktop.
Git script to save a snapshot of the current worktree
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 | |
if [ ! -z $1 ]; then | |
export GIT_DIR=$1 | |
fi | |
git rev-parse -q --verify HEAD >/dev/null; | |
if [ $? -ne 0 ]; then | |
exit | |
fi | |
# Set the index to a temp file to previous changing the current index. | |
export GIT_INDEX_FILE=$(mktemp) | |
# Delete the temp file as git except it to not exist. | |
rm -f $GIT_INDEX_FILE | |
# Delete temp file on exit. | |
trap "rm -f $GIT_INDEX_FILE" 0 1 2 3 15 | |
branch=$(git branch --show-current) | |
head=$(git rev-parse --short HEAD) | |
snapshotTag="refs/snapshot/$head" | |
if ! git rev-parse -q --verify "$snapshotTag" >/dev/null; then | |
# No previous snapshot exist, using the head as previous snapshot. | |
git update-ref $snapshotTag HEAD | |
fi | |
snapshot=$(git rev-parse $snapshotTag) | |
# Add all changes to the index and build a tree of the index. | |
git add -A | |
workdir=`git write-tree 2>/dev/null` | |
if [ $(git rev-parse $snapshotTag^{tree}) == $workdir ]; then | |
echo "'$snapshotTag' is already up to date." | |
exit | |
fi | |
# Commit with the previous snapshot as parent. | |
commit=$(git commit-tree -m "Snapshot of $branch" -p $snapshot $workdir 2>/dev/null) | |
if [ $? -ne 0 ]; then | |
echo "Error creating commit." | |
exit | |
fi | |
# Update references to the new commit. | |
git update-ref $snapshotTag $commit | |
echo "'$snapshotTag' updated." | |
git update-ref refs/heads/snapshot/$branch $commit | |
echo "'refs/heads/snapshot/$branch' updated." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment