Add README, new_cycle, weekly_review, and update habits.sh

This commit is contained in:
Alex Selimov 2026-07-24 10:00:31 -04:00
parent b5b58c8b90
commit fa9b90ae1b
4 changed files with 507 additions and 16 deletions

View file

@ -19,41 +19,79 @@ ensure_file() {
touch "$HABITS_FILE"
}
date_add_days() {
local day="$1" offset="$2" date_arg epoch
date_arg="$day $offset days"
if date -d "$date_arg" +%F >/dev/null 2>&1; then
date -d "$date_arg" +%F
return
fi
# BSD/macOS date. Parse at noon to avoid midnight DST edges.
epoch="$(date -j -f '%F %H:%M:%S' "$day 12:00:00" +%s)"
epoch=$((epoch + offset * 86400))
date -r "$epoch" +%F
}
open_habits() {
ensure_file
"${EDITOR:-vi}" "$HABITS_FILE"
}
print_day() {
local day="$1"
printf '# %s\n\n' "$day"
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'
}
new_day() {
ensure_file
local date
date="$(date +%F)"
local today latest start day tmp added
today="$(date +%F)"
latest="$(grep -E '^# [0-9]{4}-[0-9]{2}-[0-9]{2}$' "$HABITS_FILE" | sed 's/^# //' | sort | tail -n 1 || true)"
if grep -q "^# $date$" "$HABITS_FILE"; then
echo "A habits entry for $date already exists: $HABITS_FILE" >&2
if [ -n "$latest" ] && [[ "$latest" > "$today" ]]; then
echo "Latest habits entry is in the future: $latest" >&2
exit 1
fi
local tmp
if [ "$latest" = "$today" ]; then
echo "Habits entries already exist through $today: $HABITS_FILE"
return
fi
if [ -n "$latest" ]; then
start="$(date_add_days "$latest" 1)"
else
start="$today"
fi
tmp="$(mktemp)"
added=0
{
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'
day="$today"
while [[ "$day" > "$start" || "$day" = "$start" ]]; do
print_day "$day"
added=$((added + 1))
day="$(date_add_days "$day" -1)"
done
cat "$HABITS_FILE"
} > "$tmp"
mv "$tmp" "$HABITS_FILE"
echo "Added $date to $HABITS_FILE"
echo "Added $added habits entr$( [ "$added" -eq 1 ] && printf 'y' || printf 'ies' ) through $today to $HABITS_FILE"
}
remaining_habits() {
@ -80,6 +118,7 @@ case "${1:-}" in
;;
new)
new_day
open_habits
;;
left)
remaining_habits