Files
lucisv/tools/lucisv-changed.sh

61 lines
2.1 KiB
Bash
Executable File

#!/usr/bin/env bash
# Format only the lines a git diff touched — lucisv's answer to Verible's
# `git-verible-verilog-format.sh`.
#
# This is what makes lucisv adoptable in a dirty legacy tree: your patch comes
# out formatted, and not one byte outside it moves, so review sees the change
# you made rather than a reflow of the whole file.
#
# Usage: tools/lucisv-changed.sh [--check|--diff] [<rev>] [-- <pathspec>...]
#
# <rev> what to diff against; default: unstaged+staged work, i.e. HEAD.
# `tools/lucisv-changed.sh origin/main` formats a whole branch.
# --check / --diff are passed through to lucisv, so this works in CI.
#
# Exit status is lucisv's, per the frozen contract: 0 nothing to do, 1
# --check/--diff found changes, 2 an error (that file was left untouched).
#
# Only *added* lines are formatted: `git diff -U0` hunk headers give
# `@@ -old +first,count @@`, and a `count` of 0 means the hunk only deleted,
# so there is nothing on the new side to format.
set -eu
lucisv=${LUCISV:-target/release/lucisv}
mode=""
rev="HEAD"
have_rev=0
while [ $# -gt 0 ]; do
case $1 in
--check|--diff) mode=$1; shift ;;
--) shift; break ;;
-*) echo "usage: $0 [--check|--diff] [<rev>] [-- <pathspec>...]" >&2; exit 2 ;;
*) rev=$1; have_rev=1; shift ;;
esac
done
[ "$have_rev" = 1 ] || rev=HEAD
command -v "$lucisv" >/dev/null 2>&1 || [ -x "$lucisv" ] || {
echo "no lucisv binary at $lucisv (cargo build --release? or set LUCISV=)" >&2
exit 2
}
status=0
files=$(git diff --name-only --diff-filter=d "$rev" -- "$@" \
| grep -E '\.(sv|svh|v|vh)$' || true)
[ -n "$files" ] || exit 0
for file in $files; do
# `first,count` from every hunk header, as `first-last`, comma-joined.
ranges=$(git diff -U0 "$rev" -- "$file" \
| sed -n 's/^@@ -[0-9,]* +\([0-9]*\)\(,\([0-9]*\)\)\{0,1\} @@.*/\1 \3/p' \
| awk '{ count = ($2 == "" ? 1 : $2); if (count > 0) printf "%s%d-%d", sep, $1, $1 + count - 1; sep = "," }')
[ -n "$ranges" ] || continue
# shellcheck disable=SC2086 # $mode is one optional flag, deliberately split.
"$lucisv" $mode --lines "$ranges" "$file" || status=$?
done
exit $status