master lean-101 / bin / watch
Dylan Cant  ·  2026-10-27
 1#!/bin/sh
 2# Usage: bin/watch FILE.lean
 3# Re-checks FILE each time it (or another file in Game/) changes and prints
 4# Lean's messages. Earlier worlds that changed are rebuilt first.
 5#
 6# Goals: a `sorry` after your tactics (on a line of its own, or after `=>`)
 7# shows the goal at that point; the `sorry` of a level you haven't started
 8# stays quiet. Elsewhere, `trace_state` on a line of its own prints the goal.
 9# An unfinished proof shows what is left as an "unsolved goals" error.
10set -eu
11[ $# -eq 1 ] || { echo "usage: $0 FILE.lean" >&2; exit 2; }
12[ -f "$1" ] || { echo "$0: no such file: $1" >&2; exit 2; }
13# Resolve FILE before moving to the project root.
14file=$(cd "$(dirname "$1")" && pwd)/$(basename "$1")
15cd "$(dirname "$0")/.."
16root=$(pwd)/
17PATH=$HOME/.elan/bin:$PATH
18# `lake lean` leaves a file in $TMPDIR each time it runs: give it a private
19# one, removed on exit.
20TMPDIR=$(mktemp -d)
21export TMPDIR
22trap 'rm -rf "$TMPDIR"' EXIT
23trap 'exit 130' INT TERM
24# Lake's log of the imports' build goes to stderr; it matters only when one
25# of them fails.
26log=$TMPDIR/log
27# FILE is checked through a copy where those `sorry`s print the goal first,
28# on the same line, so line numbers don't change.
29copy=$TMPDIR/$(basename "$file")
30rel=${file#"$root"}
31tidy() { sed -e "s|$copy|$rel|g" -e "s|$root||g"; }
32last=
33while :; do
34  # Compare contents, not times: portable, and no saves are missed. An editor
35  # that saves by renaming can leave a file missing for a moment: wait.
36  if now=$(cat "$file" Game/*.lean 2>/dev/null | cksum) &&
37     [ -f "$file" ] && [ "$now" != "$last" ]; then
38    last=$now
39    printf '\033[H\033[2J== %s  (%s)\n\n' "$rel" "$(date +%H:%M:%S)"
40    awk '
41      function show() {
42        sub(/sorry[ \t]*$/, "trace \"Goal at line " NR ":\"; trace_state; sorry")
43      }
44      /^[ \t]*sorry[ \t]*$/ && prev !~ /by[ \t]*$/ { show() }
45      /=>[ \t]*sorry[ \t]*$/ { show() }
46      { print; if ($0 !~ /^[ \t]*$/) prev = $0 }
47    ' "$file" > "$copy"
48    # `lake lean` builds the file's imports first, with the project's options.
49    if out=$(lake -q lean "$copy" 2>"$log"); then
50      if [ -z "$out" ]; then
51        echo "No warnings: every level in this file is done."
52      else
53        printf '%s\n\n' "$out" | tidy
54        left=$(printf '%s\n' "$out" | grep -c 'declaration uses `sorry`' || true)
55        [ "$left" -eq 0 ] || echo "$left level(s) left in this file."
56      fi
57    elif [ -n "$out" ]; then
58      printf '%s\n' "$out" | tidy
59    else
60      echo "A file this one imports has an error. Fix it first:"
61      echo
62      grep -v -e 'declaration uses `sorry`' -e '^⚠ ' -e '^trace: ' "$log" | tidy
63    fi
64  fi
65  sleep 1
66done