Skip to content

Instantly share code, notes, and snippets.

@matta
Forked from DarkOoze/snapshot.sh
Created January 16, 2022 17:51
Show Gist options
  • Save matta/a63a9d276dbf0445c36bcd3bece0071c to your computer and use it in GitHub Desktop.
Save matta/a63a9d276dbf0445c36bcd3bece0071c to your computer and use it in GitHub Desktop.
Git script to save a snapshot of the current worktree
#!/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