Skip to content

Instantly share code, notes, and snippets.

@loucadufault
Created October 20, 2022 08:19
Show Gist options
  • Save loucadufault/12a2b5dc811d3e71a9536f5600adcffa to your computer and use it in GitHub Desktop.
Save loucadufault/12a2b5dc811d3e71a9536f5600adcffa to your computer and use it in GitHub Desktop.
Bash script to snapshot current state of working directory, then make a single (squashed) commit of that snapshot in another branch for archival
#!/bin/bash
# Script to take a snapshot of current state of files in working directory, then make a single commit of that snapshot in another branch for archival
ARCHIVE_BRANCH=release
# see https://git-scm.com/book/en/v2/Git-Basics-Viewing-the-Commit-History#pretty_format
GIT_LOG_PRETTY_FORMAT_STRING="%h -%d %an <%ae> - %s (%ad)"
# e844ce9 - (HEAD -> foo, origin/myBranch, myBranch) Louca Dufault <[email protected]> - commit msg (2022-10-20)
# ensure inside git repo
git rev-parse --is-inside-work-tree 1> /dev/null
if [ $? -eq 1 ]; then
exit 1
fi
# ensure not already on archive branch
orig_git_branch=$(git branch --show-current)
if [ "$orig_git_branch" == "$ARCHIVE_BRANCH" ]; then
echo "Already on archive branch $ARCHIVE_BRANCH" # operation would be useless
exit 1
fi
# retrieve latest commit info (if any)
pretty_latest_commit=$(git log -1 --pretty=format:\""$GIT_LOG_PRETTY_FORMAT_STRING"\" --date=short)
if [ $? -eq 1 ]
then
error_msg_components=($pretty_latest_commit)
echo "'${error_msg_components[0]}', there won\'t be a starter commit message"
fi
repo_root_dir=$(git rev-parse --show-toplevel)
if [ $? -eq 1 ]
then
echo "$repo_root_dir"
echo "Failed to get root dir of repo"
fi
cleanup () {
git stash pop &> /dev/null
rm -rf "$tmp_dir"
}
# from this point we need to do some cleanup
tmp_dir=$(mktemp -d)
cp -a /"$repo_root_dir"/. /"$tmp_dir"/
rm -rf "$tmp_dir/.git" # excluding .git/ dir
git branch "$ARCHIVE_BRANCH" 2> /dev/null # silence if already exists
# from this point it needs to be transactional
git stash &> /dev/null
git_checkout_command_out=$(git checkout "$ARCHIVE_BRANCH")
if [ $? -eq 1 ]
then
echo "$git_checkout_command_out"
echo "Failed to checkout archive branch"
cleanup
exit 1
fi
cp -a /"$tmp_dir"/. /"$repo_root_dir"/
git add -A
git commit -m "$pretty_latest_commit" -e # open editor still
git checkout "$orig_git_branch"
cleanup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment