summaryrefslogtreecommitdiff
path: root/bin/extra/clock
blob: bd6efd242fdecb8cf82bb395f5c1c1e0da509b7e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/bin/sh

clocks="${XDG_DATA_HOME:-$HOME}"/clocks.csv

if [ ! -f "$clocks" ]
then
	printf 'start,end,message\n' > "$clocks"
fi

# print clocks file prettily 
if [ "$1" = "-p" ]
then
	# empty
	[ "$(wc -l < "$clocks")" -eq 1 ] && exit

	timefmt="%y%m%d-%T"
	IFS=","
	# skip csv header
	tail -n +2 "$clocks" |   
	while read -r start end message
	do
		printf "%s - %s | %s\n" "$(date -d "@$start" +"$timefmt" )" "$(date -d "@$end" +"$timefmt")" "$message"
	done
	exit
fi

# edit clocks file in $EDITOR
if [ "$1" = "-e" ]
then
	$EDITOR "$clocks"
	exit
fi

trap 'exit 0' INT # The proper way to exit

while true
do
	>&2 printf ' > ' 
	message="$(head -n 1)" 

	[ "$message" ] || exit 1
	printf '\033[1A' # move cursor up once: https://en.wikipedia.org/wiki/ANSI_escape_code

	start_time="$(date +%s)"
	start_time_pretty="$(date -d "@$start_time" +%R)" 
	>&2 printf -- '\r%s- > %s' "$start_time_pretty" "$message"

	# Wait for EOF
	cat > /dev/null 2>&1

	end_time="$(date +%s)"
	end_time_pretty="$(date -d "@$end_time" +%R)" 
	>&2 printf -- '\r%s-%s > %s\n' "$start_time_pretty" "$end_time_pretty" "$message"

	if printf '%s' "$message" | grep ',' > /dev/null
	then
		# escape potential double quotes
		message="$(printf '%s' "$message" | sed -e 's/"/""/g')"
		message="\"$message\""
	fi

	# save clocked time and message
	printf '%s,%s,%s\n' "$start_time" "$end_time" "$message" >> "$clocks"
done