taskhelper.sh 2.74 KB
#!/bin/env sh

function uuids() {
    # This returns a space separated string of UUIDs fitting
	# a given sort key and direction and using the provided
	# filter. Currently only one key can be specified also theoretically
	# jq could sort on multiple keys.
    eval set -- $(getopt -o ads: -l asc,desc,sort-by: -- "$@")

    local DIR="."
    local KEY="entry"

    while true; do
        case "$1" in
            -a|--asc)		DIR="."; shift;;
            -d|--desc)		DIR="-."; shift;;
            -s|--sort-by)	KEY="$2"; shift 2;;
            --) shift; break;;
            *) echo "Internal error!"; exit 1;;
        esac
    done

    task "$@" export|\
        jq -r '.|=sort_by(.'${KEY}'
                |explode
                |map('${DIR}'))
                |map(.uuid)
                |join(" ")'
}

function worktimes() {
    [[ $# -eq 0 ]] && return 1

	local PWHEN='\([^ ]*\) \([^ ]*\)'
	local PDUR='.*duration: \(\([0-9]*\)d \)\?\([^)]*\)'
	local POUT='{"uuid":"'"$1"'","stop":"\1T\2Z","duration":"\4:\5"}'
	local TIME DAYS

	echo '['
    task $1 info|\
		sed 's/'"${PWHEN}${PDUR}"'.*/'"${POUT}"'/;te;d;:e'|\
		while read TIME; do
			DUR="$(echo "${TIME}"|jq -r '.duration')"
			DAYS="${DUR%%:*}"
			DUR="${DAYS:-0}:$(date +%H:%M:%S -d "1970-01-01 ${DUR#*:}")"
			echo "${TIME}"|jq -M -c '.duration="'"${DUR}"'"'
		done|\
		sed '$!s/$/,/'
	echo ']'
}

function work() {
    [[ $# -eq 0 ]] && return 1

	local UUID="$1"
	local TIMES="$(worktimes ${UUID}|jq -M -c '.|map(del(.uuid))')"

	set -- $(echo "${TIMES}"|jq -r '.|map(.duration)|join(" ")')

	local DUR
	for DUR; do
		local DAYS_ADD=${DUR%%:*}
		local SECS=$((SECS+$(date +%s -u -d "1970-01-01 ${DUR#*:}")))
		DAYS=$((DAYS+${DAYS_ADD:-0}))
		while [[ ${SECS} -ge 86400 ]]; do
			# Bigger or equal one day.
			DAYS=$((DAYS+1))
			SECS=$((SECS-86400))
		done
	done

	DAYS=${DAYS:-0}
	SECS=${SECS:-0}

	printf '{"uuid":"%s","times":%s,"total":"%s:%s"}'\
		${UUID} "${TIMES}" ${DAYS} $(date +%H:%M:%S -u -d@${SECS})
}

function flattened_work() {
    [[ $# -eq 0 ]] && return 1

	WORK="$(work $1)"
	ITEM="$(echo "${WORK}"|jq -M -c '.|del(.times)')"

	# If there are no TIMES logged then this will be empty at all.
	# The only remaining information in that case would have been the
	# UUID. But the caller already know it.
	echo "${WORK}"|jq -M -c '.times|map(.+'"${ITEM}"')'
}

# set -- $(task end.after:$(date +%Y-%m-%d -d "1 week ago") export|\
# jq -r '.|=sort_by(.end|explode|map(-.))|map(.uuid)|join("\n")')

# set -- $(uuids "$@")
# 
# for UUID; do
# #    task _get ${UUID}.entry
# #    task _get ${UUID}.end
# #    task _get ${UUID}.modified
# #    task _get ${UUID}.description
# #    task _get ${UUID}.urgency
# #    task _get ${UUID}.project
# 	echo $(work ${UUID})
# 	echo "------"
# 	flattened_work ${UUID}
# 	echo "======"
# done