#!/bin/sh
# Docs drift: the commands and make targets the program and the Makefile
# have must be named in README.md or docs/, and the ones the docs name must
# exist. Prints each missing or unknown item; exits 1 if there is any.
# usage: SUIT=build/dev/suit sh test/docs.sh (run from the repository root)
set -u
suit=${SUIT:-build/dev/suit}
[ -x "$suit" ] || { echo "docs: no $suit; run make suit first" >&2; exit 2; }
docs="README.md docs"
fail=0
tmp=$(mktemp -d "${TMPDIR:-/tmp}/suit-docs.XXXXXX") || exit 2
trap 'rm -rf "$tmp"' EXIT INT TERM
# Subcommands: the first word after "suit", and after each " | " when the
# part before it has no subcommand word of its own ("upstream NAME take | diff"
# and "project set .. | unset .." name arguments, not commands).
"$suit" --help 2>&1 | sed -n 's/^[ ]*\(usage: \)\{0,1\}suit //p' |
awk '{ gsub(/ \| /, "@"); n = split($0, seg, "@")
for (i = 1; i <= n; i++) {
split(seg[i], w, " ")
if (w[1] ~ /^[a-z][a-z-]*$/) print w[1]
sub_ = 0
for (j = 2; j in w; j++) if (w[j] ~ /^[a-z][a-z-]*$/) sub_ = 1
if (sub_) break
} }' | sort -u >"$tmp/cmds"
[ -s "$tmp/cmds" ] || { echo "docs: no subcommands found in $suit --help" >&2; exit 2; }
# Make targets meant for people: the phony ones.
sed -n 's/^\.PHONY:[ ]*//p' Makefile | tr ' ' '\n' | sed '/^$/d' | sort -u >"$tmp/phony"
# Every target the Makefile defines.
sed -n 's/^\([a-z][a-zA-Z0-9_-]*\):.*/\1/p' Makefile | sort -u >"$tmp/targets"
# What the docs name: `suit X` and `make X` in code spans, or at the start of a
# line inside a code block (after an optional "$ "). `suit ok` is the status
# line's output, not a command.
{ grep -rhoE '`(suit|make) [a-z][a-z-]*' $docs | sed 's/^`//'
for f in README.md docs/*.md; do
awk '/^```/ { fence = !fence; next } fence' "$f"
done | grep -oE '^[ ]*(\$ )?(suit|make) [a-z][a-z-]*' | sed 's/^[ $]*//'
} | sort -u | grep -vx 'suit ok' >"$tmp/named"
while read -r c; do
grep -rqE "suit $c([^a-z-]|\$)" $docs || { echo "docs: subcommand not in README.md or docs/: suit $c"; fail=1; }
done <"$tmp/cmds"
while read -r t; do
grep -rqE "make $t([^a-z-]|\$)" $docs || { echo "docs: make target not in README.md or docs/: make $t"; fail=1; }
done <"$tmp/phony"
while read -r kind name; do
case $kind in
suit) grep -qx "$name" "$tmp/cmds" || { echo "docs: unknown subcommand named: suit $name"; fail=1; } ;;
make) grep -qx "$name" "$tmp/targets" || { echo "docs: unknown make target named: make $name"; fail=1; } ;;
esac
done <"$tmp/named"
[ $fail -eq 0 ] && echo "docs: ok"
exit $fail