dotfiles/office/.local/share/task/hooks/on-exit.git-backup
Marty Oehme df48e29fb7
task: Fix git-backup output to be stable
By default sort the exported output by creation date and modify date.
Also use the jq expanded (prettified) output. Will take a little more
space, but ultimately makes it easier to see task changes since each
value is on a single line.
2025-03-15 20:08:44 +01:00

77 lines
2.6 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=60
# Do not display status information.
QUIET=true
# Removes the tasks.json file after each run, keeping the
# task directory clean.
REMOVE_JSON=false
# Sort with `jq` commandline program if it is found.
# Also drops extra values 'urgency' and 'id' which are not
# necessary for backups and automatically calculated by tw.
STABLE_JSON=true
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"
if [ "$STABLE_JSON" = true ] && command -v jq >/dev/null 2>&1; then
DISABLE_HOOKS=true env task export | jq -S 'map(del(.id, .urgency)) | sort_by(.entry, .modified) | reverse' >"$data_dir/tasks.json"
else
DISABLE_HOOKS=true env task export >"$data_dir/tasks.json"
fi
# 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
if [ "$REMOVE_JSON" = true ] && [ -f "$data_dir/tasks.json" ]; then
rm "$data_dir/tasks.json" >/dev/null 2>&1
fi