Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
git-snapshot-sh - a script to save junk code
# - save junk code to a snapshots branch
# USAGE: [-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
shift 2
ORIGINAL_INDEX=`git rev-parse --git-dir`/index
# If the last command failed, exit with its error code after restoring the
# index.
e() {
if [ $? -ne 0 ]; then
exit $RC
# Use a temporary index file.
# 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.
# 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
# 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
git add "$@" ; e
# 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