my-homelab-configs/scripts/change-journal

68 lines
1.9 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
HOMELAB_STATE_DIR="${HOMELAB_STATE_DIR:-${XDG_DATA_HOME:-${HOME}/.local/share}/homelab}"
JOURNAL_DIR="${HOMELAB_CHANGE_JOURNAL_DIR:-${HOMELAB_STATE_DIR}/change-journal}"
ACTION="${1:-list}"
mkdir -p "$JOURNAL_DIR"
timestamp() {
date -u +%Y%m%dT%H%M%SZ
}
latest_entries() {
local count="${1:-20}"
find "$JOURNAL_DIR" -maxdepth 1 -type f -name '*.log' -print 2>/dev/null |
sort |
tail -n "$count" |
while IFS= read -r file; do
printf '\n== %s ==\n' "$(basename "$file")"
sed -n '1,80p' "$file"
done
}
append_entry() {
local command_name="${2:-unknown}"
local detail="${3:-}"
local now
local file
now="$(timestamp)"
file="${JOURNAL_DIR}/${now}-${command_name//[^A-Za-z0-9_.-]/_}.log"
{
printf 'created_utc=%s\n' "$now"
printf 'command=%s\n' "$command_name"
printf 'detail=%s\n' "$detail"
printf 'host=%s\n' "$(hostname 2>/dev/null || echo unknown)"
printf 'repo=%s\n' "$REPO_ROOT"
printf 'branch=%s\n' "$(git -C "$REPO_ROOT" rev-parse --abbrev-ref HEAD 2>/dev/null || echo unknown)"
printf 'revision=%s\n' "$(git -C "$REPO_ROOT" rev-parse HEAD 2>/dev/null || echo unknown)"
printf 'dirty_files=%s\n' "$(git -C "$REPO_ROOT" status --short 2>/dev/null | wc -l | tr -d ' ')"
printf '\n-- git status --short --\n'
git -C "$REPO_ROOT" status --short 2>/dev/null || true
} >"$file"
printf 'Recorded change journal entry: %s\n' "$file"
}
case "$ACTION" in
append)
append_entry "$@"
;;
list)
latest_entries "${2:-20}"
;;
path)
printf '%s\n' "$JOURNAL_DIR"
;;
*)
echo "Usage: ./jeannie change-journal {list [count]|path}" >&2
echo "Internal: scripts/change-journal append <command> [detail]" >&2
exit 1
;;
esac