OS/habits.sh

95 lines
1.7 KiB
Bash
Raw Normal View History

2026-07-09 23:08:42 -04:00
#!/usr/bin/env bash
set -euo pipefail
HABITS_FILE="${HABITS_FILE:-$HOME/.local/share/os/habits.md}"
usage() {
cat <<'EOF'
Usage: habits <command>
Commands:
2026-07-09 23:18:23 -04:00
open Open the habits file in $EDITOR
new Add a new day to the habits file
left Print today's habits that are not done yet
2026-07-09 23:08:42 -04:00
EOF
}
ensure_file() {
mkdir -p "$(dirname "$HABITS_FILE")"
touch "$HABITS_FILE"
}
open_habits() {
ensure_file
"${EDITOR:-vi}" "$HABITS_FILE"
}
new_day() {
ensure_file
local date
date="$(date +%F)"
if grep -q "^# $date$" "$HABITS_FILE"; then
echo "A habits entry for $date already exists: $HABITS_FILE" >&2
exit 1
fi
local tmp
tmp="$(mktemp)"
{
printf '# %s\n\n' "$date"
printf '## Habits\n\n'
while IFS= read -r habit; do
[ -n "$habit" ] && printf -- '- [ ] %s\n' "$habit"
done <<< "$HABITS"
printf '\n## Metrics \n\n'
while IFS= read -r metric; do
[ -n "$metric" ] && printf -- '- %s\n' "$metric" ":"
done <<< "$METRICS"
printf '\n'
cat "$HABITS_FILE"
} > "$tmp"
mv "$tmp" "$HABITS_FILE"
echo "Added $date to $HABITS_FILE"
}
2026-07-09 23:18:23 -04:00
remaining_habits() {
ensure_file
local date
date="$(date +%F)"
awk -v date="$date" '
$0 == "# " date { in_day = 1; next }
in_day && /^# / { exit }
in_day && /^## Habits[[:space:]]*$/ { in_habits = 1; next }
in_day && in_habits && /^## / { exit }
in_day && in_habits && /^- \[ \] / {
sub(/^- \[ \] /, "")
print
}
' "$HABITS_FILE"
}
2026-07-09 23:08:42 -04:00
case "${1:-}" in
open)
open_habits
;;
new)
new_day
;;
2026-07-09 23:18:23 -04:00
left)
remaining_habits
;;
2026-07-09 23:08:42 -04:00
-h|--help|help)
usage
;;
*)
usage >&2
exit 1
;;
esac