dotfiles/office/.local/share/task/hooks/on-exit.git-backup
Marty Oehme c6de9b0686
task: Add new git backup hook for version 3
First exports tasks to plaintext before backing them up with git.
2025-03-10 20:22:04 +01:00

65 lines
2.1 KiB
Bash
Executable file

#!/bin/sh
# Automatically git commits, pushes and pulls if doable in the taskwarrior data directory
#
# Much of this taken from: https://github.com/mrschyte/taskwarrior-hooks/
# with much gratitude
#
# The minimum amount of time required between 2 commits in seconds.
# So only if the last commit is at least x seconds old will a new one
# be created. Set to 0 to sync each taskwarrior change.
MINIMUM_WAIT_TIME=600
# Do not display status information.
QUIET=true
# Removes the tasks.json file after each run, keeping the
# task directory clean.
REMOVE_JSON=false
if [ "${DISABLE_HOOKS}" = "true" ] || ! command -v git >/dev/null 2>&1; then
exit 0;
fi
if [ "$1" != "api:2" ]; then
printf "Taskwarrior uses different data API version than git plugin. Aborting!" 1>&2
exit 1
fi
data_dir="$(echo "$5" | cut -f2 -d:)"
command_run="$(echo "$3" | cut -f2 -d:)"
if [ "$command_run" = "synchronize" ]; then
DISABLE_HOOKS=true env task sync
git -C "$data_dir" pull >/dev/null 2>&1
pull_ret="$?"
git -C "$data_dir" push >/dev/null 2>&1
push_ret="$?"
if [ "$pull_ret" -eq 0 ] && [ "$push_ret" -eq 0 ]; then
[ $QUIET = "true" ] || echo "Git upstream synchronized."
fi
fi
last_commit=$(git -C "$data_dir" log -1 --format="%at")
# if now is not yet greater than last commit + wait time do nothing
if [ "$(date "+%s")" -lt $((last_commit + MINIMUM_WAIT_TIME)) ]; then
# TODO: Implement DEBUG msg level (info/debug) system
# echo "Too early to check for changes, exiting."
exit 0
fi
# echo "EXPORTING TASKS"
DISABLE_HOOKS=true env task export > "$data_dir/tasks.json"
# after any command, if there's changes add and commit
if ! git -C "$data_dir" diff --exit-code >/dev/null 2>&1; then
# echo "found changes"
# need to run to fully update tasks that just got done
DISABLE_HOOKS=true env task next >/dev/null 2>&1
header="auto: ${2##* }"
msg="full command: $2"
git -C "$data_dir" commit "$data_dir/tasks.json" -m "$header" -m "$msg" --no-gpg-sign >/dev/null 2>&1
[ $QUIET = "true" ] || echo "Backup up to git."
fi
[ "$REMOVE_JSON" = true ] && rm "$data_dir/tasks.json" >/dev/null 2>&1