public
Last active

git-snapshot-sh - a script to save junk code

  • Download Gist
git-snapshot.sh
Shell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
#!/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 $?

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.