#!/bin/sh
# Copyright (c) Nov 2026 Wolfram Schneider <wosch@FreeBSD.org>
# SPDX-License-Identifier: BSD-2-Clause
#
# mandoc-lint-regression.sh - check manual pages changed in a Git commit
#                             for new mandoc(1) lint warnings
#
# usage: mandoc-lint-regression.sh [-cku] [-d level] [-F file] [-W level]
#            {commit ... | staged | unstaged}
#        mandoc-lint-regression.sh [-Acku] [-a who] [-d level] [-F file]
#            [-W level] {-D days [-n count] | -n count}
#        mandoc-lint-regression.sh [-c] [-d level] [-F file] [-W level]
#            -s [path ... | staged | unstaged]
#        mandoc-lint-regression.sh -h
#        mandoc-lint-regression.sh -V
#
#   commit    a commit hash, or any name Git accepts for a commit,
#             e.g. HEAD, HEAD~3, a branch or a tag; several commits are
#             checked one after another, in the given order
#
# For every manual page added or modified in the given commit (a file
# matching $MANPATTERN that file(1) detects as troff), run "mandoc -T lint"
# on the new version and on the version in the parent commit, and
# report warnings that were introduced or fixed.  Line and column
# numbers are ignored for the comparison, so moved text does not show
# up as a change.  Each page is shown with the short hash, date and
# committer of the commit, the subject of the commit message and, in a
# FreeBSD repository, the URL of the commit.
#
# Instead of a commit, you can check local changes that are not
# committed yet:
#   staged    changes in the index against HEAD (git diff --cached)
#   unstaged  changes in the working tree against the index (git diff)
# These keywords take precedence over branches or tags of the same
# name; use e.g. refs/heads/staged for such a branch.  New files must
# be known to Git: git add them, or use "git add -N" for unstaged.
#
# With -D, the script finds the commits itself: all commits of the
# last days on the current branch that change a manual page, newest
# first.  This is the same as the list of commits from
#   git log --first-parent --since="N days ago" -- '*.[1-9]'
# With -n, the script checks the last commits that change a manual
# page, newest first; with -D as well, both limits apply.
# With -A, only your own commits are checked: those where you are the
# author or the committer, by the e-mail address in "git config
# user.email".  As a committer, this includes the patches you committed
# for other people.  With -a who, the same for somebody else: who is an
# e-mail address, or a name without @ that matches the part of the
# address before the @, e.g. -a wosch for wosch@FreeBSD.org.
#
# With -s, the script does not look for regressions, but reports the
# current lint status of all manual pages below the given paths, or
# below the current directory without a path, as they are on disk: which
# pages are lint clean, and which need to be fixed.  Only files tracked
# by Git are checked, so build output and other untracked files are
# ignored.  Instead of paths, the keyword staged or unstaged reports the
# status of the manual pages changed in the index or in the working
# tree; for staged, the version in the index is checked.  Use e.g.
# ./staged for a directory of that name.
#
# With -F file, references to manual pages that are not installed,
# e.g. pages from the ports collection, are ignored: the mandoc message
# "referenced manual not found: Xr cvs 1" is removed before the
# comparison, if the file lists "cvs 1".  The file has one manual page
# per line, as name and section; empty lines and lines starting with #
# are ignored.  At output level 3, the ignored messages are shown.
#
# Symbolic links are never followed: like Git, the script treats a
# symlinked manual page as a file that contains the link target, so it
# is skipped as not troff.  File names with tabs or newlines are not
# supported.
#
# With -V, and when the usage is printed after a wrong call, the script
# checks if a newer version is available for download, and prints a
# note on stderr if so.  Network errors and timeouts are ignored.
# There is no check at output level 0, or with VERSION_CHECK=no.  A
# normal run never accesses the network.
#
# Homepage: https://wolfram.schneider.org/src/mandoc-lint-regression/
# See README.md there for sample output, a pre-commit hook and more
# examples.
#
# Options:
#   -A        with -D or -n: check only your own commits, see above
#   -a who    with -D or -n: check only the commits of who, see above
#   -c        ignore vendor code: manual pages below contrib/, crypto/,
#             cddl/, secure/ and sys/contrib/ (FreeBSD), external/
#             (NetBSD) and gnu/ (OpenBSD, NetBSD)
#   -D days   check the commits of the last days, see above
#   -d level  output level (default: 1, or $debug if set):
#               0  print nothing, only set the exit status
#               1  show new warnings; for a list of commits and with
#                  -D or -n, also a summary at the end
#               2  show new and fixed warnings; after a fix, also show
#                  whether the page is now lint clean (no mandoc output
#                  at all) or how many warnings are left
#               3  show everything: unchanged and skipped files, summary
#             with -s:
#               0  print nothing, only set the exit status
#               1  list the pages that need fixing, and a summary
#               2  also show their warnings, and the URL of the page
#                  on the Git web server
#               3  also list the lint clean and the skipped pages
#   -F file   ignore "referenced manual not found" for the manual pages
#             listed in file, see above
#   -h        print the usage message and the homepage, and exit
#   -k        keep the work directory with the files and lint output
#   -n count  check the last count commits that change a manual page,
#             see above
#   -s        show the lint status of all manual pages below the given
#             paths (directories or files; default: the current
#             directory), or of the changed manual pages with staged or
#             unstaged, see above
#   -u        do not show the URL of the commit, or with -s of the
#             manual page, on the Git web server
#   -V        print the version and exit; unless the output level is
#             0, also check for a newer version
#   -W level  the minimum level of the mandoc messages to look at:
#             base, style, warning, error or unsupp, see mandoc(1).  The
#             default is all messages (base, also called all).  With
#             -W warning, the STYLE messages are ignored, e.g.
#             whitespace at the end of a line.
#
# Environment:
#   COMMIT_URL  URL of a commit on the Git web server, without the
#               hash at the end.  By default, a FreeBSD src, doc or
#               ports repository is detected from the URLs of the Git
#               remotes, and the URL points to cgit.freebsd.org.  For
#               other repositories, e.g. openbsd-src or netbsd-src, no
#               URL is shown, unless you set this variable, e.g.
#               COMMIT_URL=https://codeberg.org/owner/repo/commit/
#   MANDOC_LINT_EXCLUDE  default for -F file
#   MANDOC      mandoc binary to use, a command name or path without
#               options (default: mandoc)
#   MANPATTERN  file names of manual pages, as shell patterns separated
#               by spaces (default: "*.[1-9]", FreeBSD sections 1-9),
#               e.g. MANPATTERN="*.[1-9] *.[1-9]lua"
#   NO_COLOR    if set, print no colored marks
#   TMPDIR      directory for the work directory (default: /tmp)
#   VERSION_CHECK  set to "no" to disable the check for a newer version
#   debug       default output level, overridden by -d
#
# Exit status:
#   0  no new warnings; with -s: all manual pages are lint clean
#   1  new warnings were introduced, in at least one of the commits;
#      with -s: at least one manual page has warnings
#   2  usage or other error, e.g. mandoc failed to run (exit status 5
#      or 6 of mandoc), a git command failed, or a manual page could
#      not be read; the script never reports success for a page it
#      could not check
#
# Examples:
#   # a single commit
#   mandoc-lint-regression.sh 11a64dfa100d
#
#   # local changes before you commit them
#   mandoc-lint-regression.sh unstaged
#   mandoc-lint-regression.sh staged
#
#   # which manual pages in usr.bin/find and lib/libc need fixing?
#   mandoc-lint-regression.sh -s usr.bin/find lib/libc
#
#   # the same, but only warnings and errors, no style messages
#   mandoc-lint-regression.sh -W warning -s usr.bin/find lib/libc
#
#   # all warnings of the manual pages you changed, not only new ones
#   mandoc-lint-regression.sh -d 2 -s unstaged
#
#   # the last 30 days, ignoring vendor code
#   mandoc-lint-regression.sh -c -D 30
#
#   # your own commits of the last 90 days, with fixed warnings
#   mandoc-lint-regression.sh -A -d 2 -D 90
#
#   # your last 10 commits that change a manual page
#   mandoc-lint-regression.sh -A -n 10
#
#   # the commits of wosch@FreeBSD.org of the last 90 days
#   mandoc-lint-regression.sh -a wosch -D 90
#
#   # the last 30 days again, with a list of commits from git log,
#   # which you can adapt, e.g. with --author
#   mandoc-lint-regression.sh -c $(git log --first-parent --format=%h \
#       --since="30 days ago" -- '*.[1-9]')

set -u

: "${MANDOC:=mandoc}"
: "${MANPATTERN:=*.[1-9]}"
: "${debug:=1}"
prog=${0##*/}
version=2.11
homepage=https://wolfram.schneider.org/src/mandoc-lint-regression/
keep=no
nocontrib=no
showurl=yes
smode=no

# download url
# Print the content of url on stdout, with a short timeout.
download() {
	if command -v fetch > /dev/null 2>&1; then
		fetch -q -T 3 -o - "$1"
	elif command -v curl > /dev/null 2>&1; then
		curl -fsS -m 3 "$1"
	elif command -v wget > /dev/null 2>&1; then
		wget -q -T 3 -O - "$1"
	fi 2> /dev/null
}

# check_version
# Print a note on stderr if a newer version of the script is available.
# All errors are ignored: no network, a timeout, no download program.
# Never at output level 0.
check_version() {
	[ "$debug" != 0 ] || return 0
	[ "${VERSION_CHECK:-yes}" != no ] || return 0

	# only a plain version number, not e.g. an HTML error page
	latest=$(download "${homepage}LATEST-VERSION.txt" | head -n 1)
	case $latest in
	"" | *[!0-9.]*) return 0 ;;
	esac

	# compare the numbers between the dots: 2.10 is newer than 2.9
	newer=$(awk -v a="$latest" -v b="$version" 'BEGIN {
		n = split(a, x, "."); m = split(b, y, ".")
		for (i = 1; i <= n || i <= m; i++) {
			if (x[i] + 0 > y[i] + 0) { print "yes"; exit }
			if (x[i] + 0 < y[i] + 0) exit
		}
	}')
	if [ "$newer" = yes ]; then
		echo "$prog: version $latest is available," \
		    "you are running $version" >&2
		echo "download: $homepage" >&2
	fi
	return 0
}

# usage [status]
# Print the usage message and the homepage, and exit: for -h on stdout
# with exit status 0, otherwise as an error on stderr with exit status
# 2, followed by the version check.
usage() {
	status=${1:-2}
	if [ "$status" -eq 0 ]; then fd=1; else fd=2; fi
	{
		echo "usage: $prog [-cku] [-d level] [-F file] [-W level]" \
		    "{commit ... | staged | unstaged}"
		echo "       $prog [-Acku] [-a who] [-d level] [-F file]" \
		    "[-W level] {-D days [-n count] | -n count}"
		echo "       $prog [-c] [-d level] [-F file] [-W level]" \
		    "-s [path ... | staged | unstaged]"
		echo "       $prog -h"
		echo "       $prog -V"
		echo "homepage: $homepage"
	} >&$fd
	[ "$status" -eq 0 ] || check_version
	exit "$status"
}

vflag=no
uflag=
wlevel=
days=
count=
mine=no
who=
exclude=${MANDOC_LINT_EXCLUDE:-}
while getopts Aa:cD:d:F:hkn:suVW: opt; do
	case $opt in
	A) mine=yes ;;
	a)
		if [ -z "$OPTARG" ]; then
			echo "$prog: -a: empty name" >&2
			exit 2
		fi
		who=$OPTARG
		;;
	D)
		case $OPTARG in
		"" | *[!0-9]*)
			echo "$prog: invalid number of days: $OPTARG" >&2
			exit 2
			;;
		esac
		days=$OPTARG
		;;
	d) debug=$OPTARG ;;
	c) nocontrib=yes ;;
	F) exclude=$OPTARG ;;
	h) [ -n "$uflag" ] || uflag=0 ;;
	n)
		case $OPTARG in
		"" | 0 | *[!0-9]*)
			echo "$prog: invalid number of commits: $OPTARG" >&2
			exit 2
			;;
		esac
		count=$OPTARG
		;;
	k) keep=yes ;;
	s) smode=yes ;;
	u) showurl=no ;;
	V) vflag=yes ;;
	W)
		case $OPTARG in
		all | base | style | warning | error | unsupp) ;;
		*)
			echo "$prog: invalid message level: $OPTARG (use" \
			    "base, style, warning, error or unsupp)" >&2
			exit 2
			;;
		esac
		wlevel=$OPTARG
		;;
	*) uflag=2 ;;
	esac
done
shift $((OPTIND - 1))

# -h, -V and unknown options: after the loop, so that -d 0 turns off
# the version check, whether it is given before or after them
[ -z "$uflag" ] || usage "$uflag"
if [ "$vflag" = yes ]; then
	echo "$version"
	check_version
	exit 0
fi

if [ "$mine" = yes ] && [ -n "$who" ]; then
	echo "$prog: -A and -a cannot be combined" >&2
	exit 2
fi

# -F: the list of manual pages to ignore, as an absolute path, as the
# script changes the directory
if [ -n "$exclude" ]; then
	if [ ! -f "$exclude" ] || [ ! -r "$exclude" ]; then
		echo "$prog: cannot read $exclude" >&2
		exit 2
	fi
	case $exclude in
	/*) ;;
	*) exclude=$(pwd)/$exclude ;;
	esac
fi

# awk functions for -F: read_exclude() reads the list into ex[],
# excluded(line) is true for a message about a listed manual page
awk_exclude='
	function read_exclude(file,	line) {
		while ((getline line < file) > 0) {
			if (line ~ /^[ \t]*(#|$)/)
				continue
			gsub(/[ \t]+/, " ", line)
			sub(/^ /, "", line)
			sub(/ $/, "", line)
			ex[line] = 1
		}
		close(file)
	}
	function excluded(line,	key, i) {
		key = "referenced manual not found: Xr "
		if ((i = index(line, key)) == 0)
			return 0
		line = substr(line, i + length(key))
		# mandoc reports repeated references only once, e.g.
		# "Xr emacs 1 (3 times)"
		sub(/[ \t]*\([0-9]+ times\)[ \t]*$/, "", line)
		gsub(/[ \t]+/, " ", line)
		sub(/ $/, "", line)
		return (line in ex)
	}
'
if [ -n "$days$count" ]; then
	if [ "$smode" = yes ] || [ $# -gt 0 ]; then
		echo "$prog: -D and -n cannot be combined with -s, commits," \
		    "staged or unstaged" >&2
		exit 2
	fi
elif [ "$mine" = yes ] || [ -n "$who" ]; then
	echo "$prog: -A and -a need -D days or -n count" >&2
	exit 2
elif [ "$smode" = yes ]; then
	# without a path: the current directory
	[ $# -ge 1 ] || set -- .
else
	[ $# -ge 1 ] || usage
	# staged and unstaged stand alone, not in a list of commits
	if [ $# -gt 1 ]; then
		for arg; do
			case $arg in
			staged | unstaged)
				echo "$prog: $arg cannot be combined with" \
				    "other arguments" >&2
				exit 2
				;;
			esac
		done
	fi
fi

case $debug in
[0-3]) ;;
*) echo "$prog: invalid debug level: $debug (use 0-3)" >&2; exit 2 ;;
esac

for cmd in "$MANDOC" file git; do
	if ! command -v "$cmd" > /dev/null 2>&1; then
		echo "$prog: $cmd: command not found" >&2
		exit 2
	fi
done

# print file names with non-ASCII characters as they are, not quoted
# with octal escapes, so they still match MANPATTERN
git() {
	command git -c core.quotePath=false "$@"
}

if ! top=$(git rev-parse --show-toplevel 2>/dev/null); then
	echo "$prog: not in a Git working tree" >&2
	exit 2
fi

# -s: list the tracked files below the given paths, before changing the
# directory, as the paths are relative to the current directory.  With
# the keyword staged or unstaged, list the changed files instead; for
# staged, the pages are read from the index, not from the disk.
ssource=worktree
if [ "$smode" = yes ]; then
	case $#:$1 in
	1:staged)
		ssource=index
		if ! files=$(git diff --cached --name-only \
		    --diff-filter=ACMRT); then
			echo "$prog: git diff failed" >&2
			exit 2
		fi
		;;
	1:unstaged)
		if ! files=$(git diff --name-only --diff-filter=ACMRT); then
			echo "$prog: git diff failed" >&2
			exit 2
		fi
		;;
	*)
		for path; do
			if [ ! -e "$path" ]; then
				echo "$prog: $path: no such file or" \
				    "directory" >&2
				exit 2
			fi
		done
		files=$(git ls-files --full-name -- "$@") || exit 2
		;;
	esac
fi

# Git prints paths relative to the top-level directory
cd "$top" || exit 2

# Resolve all commits first, so a typo in a long list is reported
# before anything is checked.  Hashes do not contain spaces.
revs=
mode=commits
[ -z "$days$count" ] || mode=days
[ "$smode" = no ] || mode=status
case $mode:${1:-} in
status:*) ;;
days:*)
	# -D and -n: the commits that change a manual page, of the last
	# days, the last count commits, or both

	# -A and -a: only the commits of one person, as author or
	# committer.  An e-mail address must match in full; a name
	# without @ matches the part of the address before the @.
	email=$who
	if [ "$mine" = yes ]; then
		if ! email=$(git config user.email) || [ -z "$email" ]; then
			echo "$prog: -A: no e-mail address," \
			    "see git config user.email" >&2
			exit 2
		fi
	fi

	# Newest first, as git log prints them.  Without -A or -a, git log
	# stops after count commits; with them, awk stops after count
	# commits of that person.  The patterns are for Git, not for file
	# globbing.
	since= max=
	[ -z "$days" ] || since="--since=$days days ago"
	[ -z "$count" ] || [ -n "$email" ] || max="-n$count"
	set -f
	revs=$({
		git log --first-parent --format='%H %ae %ce' \
		    ${since:+"$since"} ${max:+"$max"} -- $MANPATTERN ||
		    echo FAILED 2> /dev/null
	} | awk -v email="$email" -v max="${count:-0}" '
		function me(a) {
			a = tolower(a)
			if (index(email, "@") == 0)
				sub(/@.*/, "", a)
			return a == email
		}
		BEGIN { email = tolower(email) }
		$0 == "FAILED" { failed = 1; exit }
		email == "" || me($2) || me($3) {
			hash[++n] = $1
			if (max > 0 && n >= max)
				exit
		}
		END {
			if (failed) {
				print "FAILED"
				exit
			}
			for (i = 1; i <= n; i++)
				print hash[i]
		}')
	set +f
	case $revs in
	*FAILED*)
		echo "$prog: git log failed" >&2
		exit 2
		;;
	esac

	if [ -z "$revs" ]; then
		[ "$debug" -lt 1 ] || echo "$prog: no commits with manual" \
		    "pages${days:+ in the last $days day(s)}${email:+ by $email}"
		exit 0
	fi
	;;
*:staged | *:unstaged) revs=$1 ;;
*)
	for arg; do
		if ! commit=$(git rev-parse --verify --quiet "$arg^{commit}"); then
			echo "$prog: unknown commit: $arg" >&2
			exit 2
		fi
		revs="$revs $commit"
	done
	;;
esac

# setup rev
# Set the variables for a commit, or for the keyword staged or unstaged:
#   oldrev, newrev  a commit, INDEX or WORKTREE (see lint() below);
#                   oldrev is empty if there is no old version, e.g.
#                   for a root commit
#   info            for the header of a manual page
#   changes         the changed files, from git diff --name-status
setup() {
	commit=
	case $1 in
	staged)
		oldrev=$(git rev-parse --verify --quiet HEAD) || oldrev=
		newrev=INDEX
		info="staged changes"
		changes=$(git diff --cached --name-status -M \
		    --diff-filter=ACMRT) || git_failed diff
		;;
	unstaged)
		oldrev=INDEX
		newrev=WORKTREE
		info="unstaged changes"
		changes=$(git diff --name-status --diff-filter=ACMRT) ||
		    git_failed diff
		;;
	*)
		commit=$1

		# short hash, commit date and committer, e.g.
		# "11a64dfa100d 2026-11-08 @wosch" for wosch@FreeBSD.org
		info=$(git log -1 --format='%h %cs %ce' "$commit") ||
		    git_failed log
		committer=${info##* }
		info="${info% *} @${committer%%@*}"

		# first parent; empty for a root commit
		oldrev=$(git rev-parse --verify --quiet "$commit^" \
		    2>/dev/null) || oldrev=
		newrev=$commit
		if [ -n "$oldrev" ]; then
			changes=$(git diff --name-status -M \
			    --diff-filter=ACMRT "$oldrev" "$commit") ||
			    git_failed diff
		else
			changes=$(git diff-tree -r --root --no-commit-id \
			    --name-status --diff-filter=ACMRT "$commit") ||
			    git_failed diff-tree
		fi
		;;
	esac

	# per commit, see vendor_branch()
	vendor_checked=no
	subject=
	url=
}

# status marks: a red cross for new warnings, or with -s for a page
# that needs fixing; a green check mark if the page is lint clean, a
# yellow one if warnings are left.  Only on
# a UTF-8 terminal and unless NO_COLOR is set; plain text in pipes and
# log files.
bad=
ok_clean=
ok_left=
if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
	case ${LC_ALL:-${LC_CTYPE:-${LANG:-}}} in
	*[Uu][Tt][Ff]-8* | *[Uu][Tt][Ff]8*)
		bad=$(printf '\033[31m\342\234\227\033[0m ')
		ok_clean=$(printf '\033[32m\342\234\223\033[0m ')
		ok_left=$(printf '\033[33m\342\234\223\033[0m ')
		;;
	esac
fi

work=$(mktemp -d "${TMPDIR:-/tmp}/mandoc-lint.XXXXXXXXXX") || exit 2
cleanup() {
	if [ "$keep" = yes ]; then
		echo "$prog: output kept in $work" >&2
	else
		rm -rf "$work"
	fi
}
trap cleanup EXIT
trap 'exit 2' HUP INT TERM

# unreadable path where
# Report that a file could not be extracted, and exit.
unreadable() {
	echo "$prog: cannot read $1 from $2" >&2
	exit 2
}

# git_failed command
# Report a failed git command, and exit.  Git has printed the reason.
git_failed() {
	echo "$prog: git $1 failed" >&2
	exit 2
}

# is_troff file name
# True if file(1) detects the file as troff; name is for the error
# message.  Exits if file(1) fails to run, so a broken file(1) does not
# skip all manual pages.
is_troff() {
	if ! ftype=$(file -b -- "$1"); then
		echo "$prog: file failed on $2" >&2
		exit 2
	fi
	case $ftype in
	*troff*) return 0 ;;
	esac
	return 1
}

# lint rev path name dir
# Extract path at rev as dir/name and run mandoc on it from within dir,
# so the file name in the messages is the same for both versions, even
# for a renamed file.  rev is a commit, INDEX for the staged version or
# WORKTREE for the file on disk.  Writes dir.lint; empty if rev is
# empty, as there is no old version.  A symlink in the working tree is
# not followed: as in Git, its content is the link target.  Exits if
# the file cannot be extracted or if mandoc fails to run, as the result
# would be wrong: a page that cannot be read must not pass as checked.
lint() {
	: > "$4.lint" || exit 2
	[ -n "$1" ] || return 0
	mkdir -p "$4/$(dirname -- "$3")" || exit 2
	case $1 in
	INDEX)
		git show ":$2" > "$4/$3" 2>/dev/null ||
		    unreadable "$2" "the index"
		;;
	WORKTREE)
		if [ -L "$2" ]; then
			readlink -- "$2" > "$4/$3" ||
			    unreadable "$2" "the working tree"
		else
			cat -- "$2" > "$4/$3" 2>/dev/null ||
			    unreadable "$2" "the working tree"
		fi
		;;
	*)
		git show "$1:$2" > "$4/$3" 2>/dev/null ||
		    unreadable "$2" "commit $1"
		;;
	esac

	# exit status 0-4: lint result; 5: bad arguments, 6: system error
	(cd "$4" && "$MANDOC" -T lint ${wlevel:+-W "$wlevel"} -- "$3" \
	    > ../"${4##*/}.lint" 2>&1)
	rc=$?
	if [ $rc -ge 5 ]; then
		echo "$prog: $MANDOC failed on $2 with exit status $rc:" >&2
		cat -- "$4.lint" >&2
		exit 2
	fi

	# -F: move the messages about listed manual pages to dir.ignored
	if [ -n "$exclude" ]; then
		awk -v exfile="$exclude" -v ignored="$4.ignored" \
		    "$awk_exclude"'
			BEGIN { read_exclude(exfile) }
			excluded($0) { print > ignored; next }
			{ print }
		' "$4.lint" > "$4.lint.new" &&
		    mv "$4.lint.new" "$4.lint" || exit 2
	fi
	return 0
}

# header
# Print the file name, once per manual page, before its first message.
header() {
	[ "$shown" = no ] || return 0
	shown=yes
	vendor_branch
	echo "==> $new ($info)"
	[ -z "$subject" ] || echo "  log: $subject"
	[ -z "$url" ] || echo "  url: $url"
	case $status in
	A*) echo "  (new file)" ;;
	R*) echo "  (renamed from $old)" ;;
	esac
}

# vendor_branch
# If the commit is on a vendor branch, e.g. a vendor import, add the
# branch to info: "d3419e91c112 origin/vendor/zlib 2026-11-07 @delphij".
# This takes a few seconds, so it is done only once, and only when a
# header is printed.
#
# Also set subject to the first line of the commit message, and url to
# the URL of the commit on the Git web server, unless -u is given.
# The web server is looked up only once, for the first header.
vendor_branch() {
	[ "$vendor_checked" = no ] || return 0
	vendor_checked=yes
	[ -n "$commit" ] || return 0
	subject=$(git log -1 --format=%s "$commit")
	if [ "$showurl" = yes ]; then
		[ -n "${urlbase+set}" ] || urlbase=$(commit_url)
		[ -z "$urlbase" ] || url=$urlbase${info%% *}
	fi
	branch=$(git branch -r --contains "$commit" --list '*/vendor/*' \
	    2>/dev/null | sed -n '1s/^ *//p')
	[ -z "$branch" ] || info="${info%% *} $branch ${info#* }"
}

# freebsd_repo
# Print src, doc or ports if one of the Git remotes is that FreeBSD
# repository, and nothing for other repositories.
freebsd_repo() {
	remotes=$(git config --get-regexp '^remote\..*\.url$' |
	    sed -e 's/^[^ ]* //' -e 's,/*$,,' -e 's/\.git$//')

	# FreeBSD: git.freebsd.org/src.git, gitrepo.freebsd.org:src.git,
	# or a mirror like codeberg.org/FreeBSD/freebsd-src
	for repo in src doc ports; do
		if echo "$remotes" | tr A-Z a-z |
		    grep -q -e "freebsd\.org[:/]$repo\$" \
		    -e "[:/]freebsd/freebsd-$repo\$"; then
			echo "$repo"
			return 0
		fi
	done
	return 0
}

# commit_url
# Print the URL of a commit on the Git web server, without the hash:
# $COMMIT_URL if set, otherwise cgit.freebsd.org in a FreeBSD
# repository.  Prints nothing for other repositories.
commit_url() {
	if [ -n "${COMMIT_URL+set}" ]; then
		echo "$COMMIT_URL"
		return 0
	fi
	repo=$(freebsd_repo)
	[ -z "$repo" ] || echo "https://cgit.freebsd.org/$repo/commit/?id="
}

# is_vendor path
# True if path is vendor code that -c ignores.
is_vendor() {
	case $1 in
	contrib/* | crypto/* | cddl/* | secure/* | sys/contrib/* | \
	external/* | gnu/*)
		return 0
		;;
	esac
	return 1
}

# is_manpage path
# True if the file name matches one of the patterns in MANPATTERN.
is_manpage() {
	set -f		# the patterns are for case, not for file globbing
	for pattern in $MANPATTERN; do
		case $1 in
		$pattern) set +f; return 0 ;;
		esac
	done
	set +f
	return 1
}

# compare a b
# Print the lines of b whose message (without line:column) does not
# appear in a, counting duplicates.
compare() {
	awk '
		function norm(s) { sub(/:[0-9]+:[0-9]+:/, ":", s); return s }
		FILENAME == ARGV[1] { count[norm($0)]++; next }
		{ k = norm($0); if (count[k] > 0) count[k]--; else print "  " $0 }
	' "$1" "$2"
}

n=0
pages=0
skipped=0
vendor=0
regressions=0	# pages with new warnings
fixedpages=0	# pages with fixed warnings
nowclean=0	# pages with warnings before, and none after the change
tab=$(printf '\t')

# -s: lint status of all manual pages, then exit.
#
# For many pages, e.g. the whole source tree, starting file(1) and
# mandoc(1) for every page is slow.  So this is done in three steps:
# select the pages in the shell, without starting a program; run
# file(1) and mandoc(1) on many pages at once, on all CPUs in parallel;
# and let awk(1) assign the messages to the pages and print the report.
if [ "$smode" = yes ]; then
	list=$work/list		# kind and name of every candidate
	pages=$work/pages	# full path of the pages for file(1)
	troff=$work/troff	# full path of the pages for mandoc(1)
	: > "$list" && : > "$pages" && : > "$work/failed" || exit 2
	mkdir "$work/empty" || exit 2

	# the directory the pages are read from: the working tree, or
	# for staged a copy of the pages in the index
	sroot=$top
	[ "$ssource" = worktree ] || sroot=$work/index

	# kind: V vendor code, L symbolic link, P page for file(1)
	while IFS= read -r f; do
		is_manpage "$f" || continue

		if [ "$ssource" = index ]; then
			# 120000: a symbolic link in the index
			mode=$(git ls-files -s -- "$f" | sed -n '1s/ .*//p')
			[ -n "$mode" ] || continue
		else
			# tracked, but deleted in the working tree
			[ -f "$f" ] || [ -L "$f" ] || continue
			mode=
			[ ! -L "$f" ] || mode=120000
		fi

		if [ "$nocontrib" = yes ] && is_vendor "$f"; then
			kind=V
		elif [ "$mode" = 120000 ]; then
			# never followed: as in Git, its content is the
			# link target, which is not troff
			kind=L
		else
			if [ "$ssource" = index ]; then
				mkdir -p "$sroot/$(dirname -- "$f")" || exit 2
				git show ":$f" > "$sroot/$f" 2> /dev/null ||
				    unreadable "$f" "the index"
			else
				[ -r "$f" ] || unreadable "$f" "the working tree"
			fi
			kind=P
			printf '%s\n' "$sroot/$f" >&4
		fi
		printf '%s\t%s\n' "$kind" "$f" >&3
	done 3> "$list" 4> "$pages" <<EOF
$files
EOF

	# split the list of pages into one part per CPU, at least 100
	# pages each; the parts sort in the order of the list
	# nproc(1): FreeBSD 13.2 and later, Linux; it honors cpuset(1).
	# sysctl(8): older FreeBSD, NetBSD, OpenBSD and macOS.
	ncpu=$(nproc 2> /dev/null) ||
	    ncpu=$(sysctl -n hw.ncpu 2> /dev/null) || ncpu=1
	case $ncpu in
	"" | 0 | *[!0-9]*) ncpu=1 ;;
	esac

	# parts list
	# Split the file list into the parts list.aa, list.ab, ...
	parts() {
		lines=$(($(wc -l < "$1")))
		[ "$lines" -gt 0 ] || return 0
		per=$(((lines + ncpu - 1) / ncpu))
		[ "$per" -ge 100 ] || per=100
		split -l "$per" "$1" "$1." || exit 2
	}

	# file(1): one line per page, in the order of the list
	parts "$pages"
	for part in "$pages".??; do
		[ -f "$part" ] || continue
		file -b -f "$part" > "$part.types" 2> "$part.err" ||
		    echo "$part" >> "$work/failed" &
	done
	wait
	if [ -s "$work/failed" ]; then
		echo "$prog: file failed:" >&2
		cat "$pages".??.err >&2
		exit 2
	fi
	: > "$work/types" || exit 2
	for part in "$pages".??; do
		[ -f "$part" ] || continue
		cat "$part.types" >> "$work/types" || exit 2
	done
	if [ "$(($(wc -l < "$pages")))" -ne "$(($(wc -l < "$work/types")))" ]
	then
		echo "$prog: file failed: unexpected output" >&2
		exit 2
	fi

	# the pages that are troff
	awk '
		FILENAME == ARGV[1] { type[FNR] = $0; next }
		type[FNR] ~ /troff/
	' "$work/types" "$pages" > "$troff" || exit 2

	# mandoc(1) for many pages at once.  It runs in an empty
	# directory and gets full paths, so a page cannot include another
	# file of the source tree with a relative .so request.  Exit
	# status 0-4 is the lint result; 5: bad arguments, 6: system
	# error.
	MLR_MANDOC=$MANDOC MLR_W=$wlevel MLR_FAILED=$work/failed
	export MLR_MANDOC MLR_W MLR_FAILED
	parts "$troff"
	for part in "$troff".??; do
		[ -f "$part" ] || continue
		(cd "$work/empty" && tr '\n' '\0' < "$part" | xargs -0 sh -c '
			"$MLR_MANDOC" -T lint ${MLR_W:+-W "$MLR_W"} -- "$@"
			rc=$?
			[ "$rc" -lt 5 ] || echo "$rc" >> "$MLR_FAILED"
			exit 0
		' sh) > "$part.lint" 2>&1 || echo 1 >> "$work/failed" &
	done
	wait
	: > "$work/lint" || exit 2
	for part in "$troff".??; do
		[ -f "$part" ] || continue
		cat "$part.lint" >> "$work/lint" || exit 2
	done
	if [ -s "$work/failed" ]; then
		rc=$(sed -n '1p' "$work/failed")
		echo "$prog: $MANDOC failed with exit status $rc:" >&2
		grep -e SYSERR -e BADARG "$work/lint" >&2 ||
		    tail -n 5 "$work/lint" >&2
		exit 2
	fi

	# The report.  A message of mandoc starts with "mandoc: file:";
	# the full path is cut down to the path in the source tree again.
	# A line without a known file name belongs to the page before.
	MLR_BAD=$bad MLR_CLEAN=$ok_clean MLR_TOP=$sroot
	export MLR_BAD MLR_CLEAN MLR_TOP

	# URL of a page on the Git web server, in a FreeBSD repository:
	# the page as of the commit HEAD, so the line numbers of the
	# messages fit, also on a branch
	MLR_URL= MLR_ID=
	if [ "$showurl" = yes ] && [ "$debug" -ge 2 ]; then
		repo=$(freebsd_repo)
		MLR_ID=$(git log -1 --format=%h HEAD 2> /dev/null) || MLR_ID=
		[ -z "$repo" ] || [ -z "$MLR_ID" ] ||
		    MLR_URL=https://cgit.freebsd.org/$repo/tree/
	fi
	export MLR_URL MLR_ID
	awk -v debug="$debug" -v listfile="$list" -v typesfile="$work/types" \
	    -v exfile="$exclude" "$awk_exclude"'
		BEGIN {
			if (exfile != "")
				read_exclude(exfile)
			prefix = "mandoc: " ENVIRON["MLR_TOP"] "/"
			plen = length(prefix)
			while ((getline line < listfile) > 0) {
				n++
				kind[n] = substr(line, 1, 1)
				name[n] = substr(line, 3)
				if (kind[n] != "P")
					continue
				if ((getline type < typesfile) <= 0) {
					failed = 1
					exit
				}
				if (type ~ /troff/)
					known[name[n]] = 1
				else
					kind[n] = "N"
			}
		}
		{
			line = $0
			if (substr(line, 1, plen) == prefix) {
				rest = substr(line, plen + 1)
				line = "mandoc: " rest
				# the shortest part before a colon that is
				# the name of a page
				file = ""
				pos = 0
				while ((i = index(substr(rest, pos + 1), ":")) > 0) {
					pos += i
					if (substr(rest, 1, pos - 1) in known) {
						file = substr(rest, 1, pos - 1)
						break
					}
				}
				if (file != "")
					current = file
			}
			if (current == "")
				next
			if (exfile != "" && excluded(line)) {
				ign[current] = ign[current] "    ignored: " line "\n"
				next
			}
			count[current]++
			if (debug >= 2)
				msg[current] = msg[current] "    " line "\n"
		}
		END {
			if (failed)
				exit 2
			for (i = 1; i <= n; i++) {
				f = name[i]
				if (kind[i] == "V") {
					vendor++
					if (debug >= 3)
						print "  " f ": skipped, vendor code"
				} else if (kind[i] != "P") {
					skipped++
					if (debug >= 3)
						print "  " f ": skipped, not a troff file"
				} else if (count[f] == 0) {
					clean++
					if (debug >= 3)
						print ENVIRON["MLR_CLEAN"] f ": lint clean"
					if (debug >= 3)
						printf "%s", ign[f]
				} else {
					dirty++
					if (debug >= 1)
						print ENVIRON["MLR_BAD"] f ": " count[f] " warning(s)"
					if (debug >= 2 && ENVIRON["MLR_URL"] != "") {
						path = f
						gsub(/ /, "%20", path)
						print "    url: " ENVIRON["MLR_URL"] \
						    path "?id=" ENVIRON["MLR_ID"]
					}
					if (debug >= 2)
						printf "%s", msg[f]
					if (debug >= 3)
						printf "%s", ign[f]
				}
			}
			if (debug >= 1) {
				print ""
				print clean + dirty " manual page(s) checked: " \
				    clean + 0 " lint clean, " dirty + 0 " need fixing"
			}
			if (debug >= 3)
				print skipped + 0 " non-troff file(s) skipped, " \
				    vendor + 0 " vendor file(s) ignored"
			exit (dirty > 0)
		}
	' "$work/lint"
	exit
fi

# check
# Check the manual pages in $changes, see setup().
check() {
	while IFS=$tab read -r status old new; do
		# A/M/T lines have one path, R/C lines have old and new path
		[ -n "$new" ] || new=$old
		is_manpage "$new" || continue

		if [ "$nocontrib" = yes ] && is_vendor "$new"; then
			if [ "$debug" -ge 3 ]; then
				echo "==> $new ($info): skipped, vendor code"
				echo
			fi
			vendor=$((vendor + 1))
			continue
		fi

		n=$((n + 1))
		shown=no
		dir=$work/$n
		mkdir -p "$dir" || exit 2
		echo "$new" > "$dir/name"

		lint "$newrev" "$new" "$new" "$dir/new"

		# skip files like foo.1 that are not troff, e.g. data or test input
		if ! is_troff "$dir/new/$new" "$new"; then
			if [ "$debug" -ge 3 ]; then
				echo "==> $new ($info): skipped, not a troff file"
				echo
			fi
			skipped=$((skipped + 1))
			continue
		fi
		pages=$((pages + 1))

		case $status in
		A*) : > "$dir/old.lint" ;;
		*) lint "$oldrev" "$old" "$new" "$dir/old" ;;
		esac

		added=$(compare "$dir/old.lint" "$dir/new.lint")
		fixed=$(compare "$dir/new.lint" "$dir/old.lint")

		[ -z "$added" ] || regressions=$((regressions + 1))
		[ -z "$fixed" ] || fixedpages=$((fixedpages + 1))
		left=$(($(wc -l < "$dir/new.lint")))
		if [ "$left" -eq 0 ] && [ -s "$dir/old.lint" ]; then
			nowclean=$((nowclean + 1))
		fi

		if [ -n "$added" ] && [ "$debug" -ge 1 ]; then
			header
			echo "${bad}new warnings:"
			echo "$added"
		fi
		if [ -n "$fixed" ] && [ "$debug" -ge 2 ]; then
			header
			echo "fixed warnings:"
			echo "$fixed"
			if [ "$left" -eq 0 ]; then
				echo "  ${ok_clean}manual page is now lint clean"
			else
				echo "  ${ok_left}$left warning(s) left"
			fi
		fi
		if [ -z "$added$fixed" ] && [ "$debug" -ge 3 ]; then
			header
			if [ "$left" -eq 0 ]; then
				echo "  ${ok_clean}lint clean"
			else
				echo "  ${ok_left}no change in lint output, $left warning(s) left"
			fi
		fi
		# -F: the ignored messages of the new version
		if [ -s "$dir/new.ignored" ] && [ "$debug" -ge 3 ]; then
			header
			echo "ignored (-F):"
			sed 's/^/  /' "$dir/new.ignored"
		fi
		[ "$shown" = no ] || echo
	done <<EOF
$changes
EOF
}

commits=0
for rev in $revs; do
	commits=$((commits + 1))
	setup "$rev"
	check
done

# summary: at level 3; for a list of commits and with -D or -n, where the
# output is long, already at level 1
summary=no
[ "$debug" -lt 3 ] || summary=yes
if [ "$debug" -ge 1 ]; then
	[ $commits -le 1 ] && [ "$mode" != days ] || summary=yes
fi
if [ "$summary" = no ]; then
	[ $regressions -eq 0 ]
	exit
fi

# for a list of commits, the totals
[ $commits -eq 1 ] || info="$commits commits"
if [ $pages -eq 0 ]; then
	echo "$prog: no manual pages changed in $info"
	exit 0
fi

[ $commits -eq 1 ] || printf '%s' "$commits commits: "
echo "$pages manual page(s) checked"
echo "  $regressions with new warnings"
echo "  $fixedpages with fixed warnings"
echo "  $nowclean now lint clean"
echo "  $skipped non-troff file(s) skipped"
echo "  $vendor vendor file(s) ignored"
[ $regressions -eq 0 ]

#EOF
