Skip to content

Instantly share code, notes, and snippets.

@MarkLodato
Created February 13, 2010 00:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save MarkLodato/303142 to your computer and use it in GitHub Desktop.
Save MarkLodato/303142 to your computer and use it in GitHub Desktop.
git-snapshot-sh - a script to save junk code
#!/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
}
# Use a temporary index file.
cp $ORIGINAL_INDEX $GIT_INDEX_FILE || exit $?
# 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.
rm $GIT_INDEX_FILE
TREE_ID=`git write-tree` ; e
SNAPSHOT_ID=`echo initial snapshot | git commit-tree $TREE_ID` ; e
cp $ORIGINAL_INDEX $GIT_INDEX_FILE
fi
# 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