Skip to content

Instantly share code, notes, and snippets.

@bonzini
Forked from MarkLodato/git-snapshot.sh
Created February 13, 2010 16:13
Show Gist options
  • Save bonzini/303521 to your computer and use it in GitHub Desktop.
Save bonzini/303521 to your computer and use it in GitHub Desktop.
#!/bin/sh
#
# git-snapshot.sh - save junk code to a snapshots branch
#
# USAGE: git-snapshot.sh [-m message] [files...]
#
# Run `git add files` and then create a new commit on branch 'snapshot'
# with two parents, the previous snapshot and HEAD.
#
# If -m is given, the 'message' is used as the commit message; otherwise
# "snapshot" is used. This option must be given as the first argument.
#
# The 'files' argument can be any argument for git add; it defaults to "-a".
# Configuration:
BRANCH=refs/heads/snapshot # full refname of branch to update
MESSAGE=snapshot # default commit message
EXT=.snapshot # extension for temporary index file
# Parse the -m argument.
if [ "$1" = "-m" ]; then
if [ $# -lt 2 ]; then
echo "ERROR: -m takes an argument" >&2
exit 1
fi
MESSAGE="$2"
shift 2
fi
ORIGINAL_INDEX=`git rev-parse --git-dir`/index
GIT_INDEX_FILE=$ORIGINAL_INDEX$EXT
export GIT_INDEX_FILE
# If the last command failed, exit with its error code after restoring the
# index.
e() {
if [ $? -ne 0 ]; then
RC=$?
rm $GIT_INDEX_FILE
exit $RC
fi
}
# Ensure there are no traces of a previous version of our temporary index file.
rm -f $GIT_INDEX_FILE ; e
# Save the commit ID of where we currently are.
HEAD_ID=`git rev-parse HEAD` ; e
# Save the commit ID of the old head of the snapshots branch.
SNAPSHOT_ID=`git rev-parse $BRANCH 2>/dev/null`
if [ $? -ne 0 ]; then
# The branch doesn't exist. Create it with an initial empty commit
# ($GIT_INDEX_FILE does not exist). For a description of these commands,
# see below.
TREE_ID=`git write-tree` ; e
SNAPSHOT_ID=`echo initial snapshot | git commit-tree $TREE_ID` ; e
fi
# From now on, base our index on the user's
cp $ORIGINAL_INDEX $GIT_INDEX_FILE ; e
# Add all of the files listed on the command line, or use '-a' if no arguments
# given.
if [ $# -eq 0 ]; then
git add --all ; e
else
git add "$@" ; e
fi
# Record the index as a tree in the object database, and save its ID.
TREE_ID=`git write-tree` ; e
# Create a new commit with the tree we just created, the message given,
# and two parents: the previous snapshot and the current HEAD.
# Save the ID of this new commit.
COMMIT_ID=`echo "$MESSAGE" | \
git commit-tree $TREE_ID -p $SNAPSHOT_ID -p $HEAD_ID` ; e
# Update our branch to point to this new commit.
git update-ref $BRANCH $COMMIT_ID ; e
# Restore the original index.
rm $GIT_INDEX_FILE || exit $?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment