today (1697B) [raw]
1 #!/bin/sh 2 # today -- what did you do today? 3 set -e 4 err() { 5 echo "$*" 1>&2 6 } 7 8 die() { 9 err "$*" 10 exit 1 11 } 12 13 DIR=${TODAY_DIR:-$HOME/.today} 14 LOG=$DIR/log 15 16 gitdo() { 17 git -C "$DIR" "$@" 18 } 19 20 commit() { 21 if ! gitdo diff --quiet; then 22 gitdo add "$LOG" 23 gitdo commit --quiet -m "$@" 24 else 25 echo "No changes, exiting" 26 fi 27 } 28 29 init() { 30 mkdir -p "$DIR" 31 [ -d "$DIR/.git" ] && die "$DIR exists as a git repo already" 32 gitdo init -b main 33 cat <<EOM >"$LOG" 34 today -- what did you do today? 35 ------------------------------- 36 EOM 37 gitdo add "$LOG" 38 gitdo commit -m "Initial commit" 39 } 40 41 reqinit() { 42 if [ ! -d "$DIR" ]; then 43 die "$DIR doesn't exist; init with -i first or set \$TODAY_DIR" 44 fi 45 } 46 47 edlog() { 48 ed -s -p'ed> ' "$@" "$LOG" 49 commit "Auto commit" 50 } 51 52 edit() { 53 now=$(printf "[%s]" "$(date "+%F")") 54 if grep -q "^\[$(date "+%F")\]\$" "$LOG"; then 55 echo "Entry for today already exists, editing" 56 else 57 echo "Starting a new entry for today $now" 58 printf "\n$now\n" >> "$LOG" 59 fi 60 edlog 61 } 62 63 list() { 64 re='^\[[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\]$' 65 case "x$1" in 66 x) cat "$LOG" ;; 67 x[0-9]*) 68 i="$1" 69 N="$(grep "$re" "$LOG" | wc -l)" 70 if [ $i -gt $N ]; then 71 cat "$LOG" 72 return 73 fi 74 rm -f /tmp/today.ed 75 while [ $i -gt 0 ]; do 76 i=$((i - 1)) 77 printf "?%s?;" "$re" >>/tmp/today.ed 78 done 79 printf "\$p\nq\n" >>/tmp/today.ed 80 ed -s "$LOG" </tmp/today.ed 81 ;; 82 *) die "$1 isn't a number" ;; 83 esac 84 } 85 86 case "x$1" in 87 x) reqinit && edit ;; 88 x-e) reqinit && ${EDITOR:-vi} "$LOG" ;; 89 x-i) init ;; 90 x-l) reqinit && list "$2" ;; 91 x-h) die "usage: today [-ehi] [-l [NUM]]" ;; 92 *) 93 [ -n "$1" ] && err "error: unknown option $1" 94 die "usage: today [-ehi] [-l [NUM]]" 95 ;; 96 esac