git-check-assertions/git-check-assertions

64 lines
2.3 KiB
Bash
Executable file

#!/usr/bin/env bash
# Copyright (c) 2026 Sven van Heugten
#
# Repository: https://codeberg.org/svenvanheugten/git-check-assertions
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
set -euo pipefail
assert_fails() {
! "$@" || { echo "Expected command to fail, but it succeeded."; exit 1; }
}
export -f assert_fails
orig_ref="$(git symbolic-ref --quiet --short HEAD || git rev-parse HEAD)"
base="$(git merge-base main HEAD)"
mapfile -t commits < <(git rev-list --reverse "${base}..HEAD")
echo "Base: $base"
echo "Commits to visit: ${#commits[@]}"
echo
for commit_hash in "${commits[@]}"; do
echo "Checking out $commit_hash"
git -c advice.detachedHead=false checkout -q "$commit_hash"
commit_msg="$(git log -1 --format=%B "$commit_hash")"
# shellcheck disable=SC2016
block="$(printf '%s\n' "$commit_msg" \
| sed -n '/^```git-check-assertions[[:space:]]*$/,/^```[[:space:]]*$/p' \
| sed '1d;$d')"
if [ -n "$block" ]; then
echo "git-check-assertions block in $commit_hash:"
printf '%s\n' "$block" | sed 's/^/> /'
if ! bash -euo pipefail -c "$block"; then
echo "git-check-assertions block failed in $commit_hash" >&2
echo "Returning to $orig_ref"
git checkout -q "$orig_ref"
exit 1
fi
git restore -q .
fi
echo
done
echo
echo "Returning to $orig_ref"
git checkout -q "$orig_ref"