Skip to content

Instantly share code, notes, and snippets.

@bogado
Created January 11, 2016 04:23
Show Gist options
  • Save bogado/0e83de719758930e8228 to your computer and use it in GitHub Desktop.
Save bogado/0e83de719758930e8228 to your computer and use it in GitHub Desktop.
Simple backup engine to git.
# create a reference if it dosen't exist yet
function __ensure_create_backup_branch()
{
branch_name=$1
reason=$2
if [[ "$reason" != "" ]]; then
reason_flag="-m"
fi
if [[ "$1" != "" ]]; then
git rev-parse --verify "$branch_name" > /dev/null 2>&1 || git update-ref "$reason_flag" "$reason" "$branch_name" HEAD
fi
}
# save all changed files (includes non-tracked, but not ignored ones) into a commit
function __save_all()
{
branch_name=$1
GIT_INDEX_FILE=$(mktemp -u $(git rev-parse --git-dir)/backup_index_XXXX)
export GIT_INDEX_FILE
git ls-files -o -m -c --exclude-standard | git update-index --add --remove --refresh --ignore-submodules --stdin > /dev/null 2>&1
tree=$(git write-tree)
branch_tree=$(git cat-file -p $(git log -1 --format=format:%H "$branch_name") | grep tree | cut -d ' ' -f 2)
if [[ "$tree" != "$branch_tree" ]]; then
git update-ref -m "update backup" "$branch_name" $(git commit-tree "$tree" -p "$branch_name" -m "Backup created on $(date -I)") || echo "could not update $branch_name"
fi
rm "$GIT_INDEX_FILE"
}
# Print the current task management and crates a backup (use on PS1)
function _task_management()
{
current_task=$(task)
if [[ "$current_task" == "" ]]; then
echo "<no task>"
else
echo "[$current_task]"
fi
git rev-parse --git-dir >/dev/null 2>&1
if [[ $? -eq 0 ]] ; then (
branch_name="$(__task_backup_ref)"
__ensure_create_backup_branch "$branch_name" "Creating backup branch"
__save_all $branch_name
)& fi
}
export TASKFILE="$HOME/.current_task"
# select the current task
function task()
{
if [[ "$1" != "" ]]; then
echo $1 > $TASKFILE;
fi
if [[ -f "$TASKFILE" ]]; then
head -n 1 "$TASKFILE"
fi
}
# finish the current task
function end_task()
{
rm "$TASKFILE"
}
# cleanup all but the current task
function cleanup_backup_tasks()
{
git_dir=$(git rev-parse --git-dir 2> /dev/null)
current_task=$(task)
for backup_ref in $(ls $git_dir/refs/backup); do
if [[ "$backup_ref" != "$current_task" ]]; then
git update-ref -m "cleanup backup tasks" -d $(__task_backup_ref "$backup_ref")
fi
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment