Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/actions/setup-bazel-ci/fetch-targets.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
@tbhb_rules//lint:gitleaks_text
@tbhb_rules//lint:commit_identity
@tbhb_rules//lint:commit_messages
@tbhb_rules//lint:pr_merge_base
@tbhb_rules//lint:trailing_newline
@tbhb_rules//lint:codeowners_errors
@tbhb_rules_go//tools:go_sdk_checksums
@tbhb_rules//lint:job_timeouts
Expand Down
27 changes: 20 additions & 7 deletions .github/workflows/repo-checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -406,24 +406,28 @@ jobs:
printf '%s\n\n%s\n' "${PR_TITLE}" "${PR_BODY}" >"${text}"
bazelisk run @tbhb_rules//lint:gitleaks_text <"${text}"

# A pull request's own commits, base to head, must each carry an
# allowed (author, committer) pair; the list is in tbhb_rules. The
# merge commit a merge writes is not in the range.
# The full checkout includes the base branch. Use the PR head for the
# merge base because checkout's HEAD is GitHub's test merge commit.
# Each non-merge commit in that range needs an allowed identity pair.
- name: Check the pull request's commit identities
if: github.event_name == 'pull_request'
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
BASE_REF: ${{ github.event.pull_request.base.ref }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: bazelisk run @tbhb_rules//lint:commit_identity -- "${BASE_SHA}" "${HEAD_SHA}"
run: |
base=$(bazelisk run @tbhb_rules//lint:pr_merge_base -- "${BASE_REF}" "${HEAD_SHA}")
bazelisk run @tbhb_rules//lint:commit_identity -- "${base}" "${HEAD_SHA}"

# Every commit on the branch lands on main, so each subject must read
# well on its own. Merge commits are skipped.
- name: Check the pull request's commit messages
if: github.event_name == 'pull_request'
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
BASE_REF: ${{ github.event.pull_request.base.ref }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: bazelisk run @tbhb_rules//lint:commit_messages -- "${BASE_SHA}" "${HEAD_SHA}"
run: |
base=$(bazelisk run @tbhb_rules//lint:pr_merge_base -- "${BASE_REF}" "${HEAD_SHA}")
bazelisk run @tbhb_rules//lint:commit_messages -- "${base}" "${HEAD_SHA}"

- name: Check the pull request size
if: github.event_name == 'pull_request'
Expand All @@ -441,6 +445,15 @@ jobs:
export MAIN_TIP
bazelisk run @tbhb_rules//lint:pr_size -- "${BASE_SHA}" "${HEAD_SHA}"

- name: Check trailing newlines in changed files
if: github.event_name == 'pull_request'
env:
BASE_REF: ${{ github.event.pull_request.base.ref }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: |
base=$(bazelisk run @tbhb_rules//lint:pr_merge_base -- "${BASE_REF}" "${HEAD_SHA}")
bazelisk run @tbhb_rules//lint:trailing_newline -- "${base}" "${HEAD_SHA}"

# Advisories change without any input changing, so the audit is never
# a cached test. External index failures must not block pull requests.
- name: Audit the locked Python dependencies
Expand Down
32 changes: 32 additions & 0 deletions lint/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,32 @@ gitleaks_text(
visibility = ["//visibility:public"],
)

# Checks new and changed text blobs with `bazel run //lint:trailing_newline -- BASE HEAD`.
python_tool(
name = "trailing_newline",
main = "//lint/private:check_trailing_newline.py",
python_env = "@tbhb_rules_python_runtime//:env",
visibility = ["//visibility:public"],
)

sh_test(
name = "trailing_newline_test",
srcs = ["trailing_newline_test.sh"],
data = [
":trailing_newline",
"@tbhb_rules_git//:git",
],
env = {
"CHECKER_RLOCATIONPATH": "$(rlocationpath :trailing_newline)",
"GIT_RLOCATIONPATH": "$(rlocationpath @tbhb_rules_git//:git)",
},
# Tech debt: enable this Git subprocess test on Windows and remove the exclusion.
target_compatible_with = select({
"@platforms//os:windows": ["@platforms//:incompatible"],
"//conditions:default": [],
}),
)

# Checks the commits in a range against the allowed (author, committer)
# pairs and require valid identity trailers for agent emails:
# `bazel run @tbhb_rules//lint:commit_identity -- BASE HEAD`.
Expand All @@ -87,6 +113,12 @@ commit_messages(
visibility = ["//visibility:public"],
)

sh_binary(
name = "pr_merge_base",
srcs = ["pr_merge_base.sh"],
visibility = ["//visibility:public"],
)

bzl_library(
name = "defs",
srcs = ["defs.bzl"],
Expand Down
15 changes: 15 additions & 0 deletions lint/pr_merge_base.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: Apache-2.0
# Copyright Tony Burns

set -euo pipefail

if (($# != 2)); then
echo 'usage: pr_merge_base BASE_REF HEAD' >&2
exit 2
fi

cd "${BUILD_WORKSPACE_DIRECTORY:?run this target with bazel run}"
base="refs/remotes/origin/$1"
git cat-file -e "$base^{commit}" 2>/dev/null || git fetch origin "refs/heads/$1:$base" >&2
exec git merge-base -- "$base" "$2"
5 changes: 4 additions & 1 deletion lint/private/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ load(":gitleaks_tool.bzl", "gitleaks_tool")

repo_files()

exports_files(["gitleaks_guard.py"])
exports_files([
"check_trailing_newline.py",
"gitleaks_guard.py",
])

exports_files([
"codeowners.sh",
Expand Down
85 changes: 85 additions & 0 deletions lint/private/check_trailing_newline.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright Tony Burns

# ruff: noqa: INP001
"""Require a trailing newline in each changed text file in a Git range."""

import argparse
import os
import re
import subprocess # nosec B404
import sys
from pathlib import Path

# The top-level exclude and the end-of-file-fixer exclude in .pre-commit-config.yaml.
HOOK_EXCLUDE = re.compile(
rb"""(?x)^(
\.vale/(Google|write-good|proselint|ai-tells.*)/
|\.bazel-.*/|bazel-.*/|tmp/|\.worktrees/
|(.*/)?(mutants|testdata)/
|.*\.d2\.(svg|png|sha256)$
|(.*/)?structurizr-[^/]*\.(svg|png)$
|(.*/)?workspace\.json$
|(.*/)?worker-configuration\.d\.ts$
|lint/gitleaks/(base|upstream)\.toml$
)"""
)
# The remaining path expression in the Bedrock allowlist in .gitleaks.toml.
BEDROCK_EXCLUDE = re.compile(rb"(^|/)\.gitleaks-rules\.toml$")
TEXT_SAMPLE_SIZE = 8192


def _git(root: Path, *args: str) -> bytes:
return subprocess.check_output( # noqa: S603 # nosec B603, B607
["git", *args], # noqa: S607
cwd=root,
)


def check(root: Path, base: str, head: str) -> int:
# Treat a rename as an addition at its new path. Raw output gives us
# both the mode and the object ID of the committed file.
records = _git(
root,
"diff",
"--raw",
"-z",
"--no-abbrev",
"--no-ext-diff",
"--no-renames",
"--diff-filter=AMT",
"--end-of-options",
base,
head,
"--",
).split(b"\0")[:-1]
status = 0
for metadata, path in zip(records[0::2], records[1::2], strict=True):
_, mode, _, object_id, _ = metadata.split()
if (
HOOK_EXCLUDE.match(path)
or BEDROCK_EXCLUDE.search(path)
or not mode.startswith(b"100")
):
continue
blob = _git(root, "cat-file", "blob", object_id.decode("ascii"))
if blob and b"\0" not in blob[:TEXT_SAMPLE_SIZE] and not blob.endswith(b"\n"):
sys.stderr.write(f"{os.fsdecode(path)!r}: missing trailing newline\n")
status = 1
return status


def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("base")
parser.add_argument("head")
args = parser.parse_args()
root = Path(os.environ.get("BUILD_WORKSPACE_DIRECTORY", "."))
try:
return check(root, args.base, args.head)
except subprocess.CalledProcessError:
return 2


if __name__ == "__main__":
sys.exit(main())
23 changes: 23 additions & 0 deletions lint/tests/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright Tony Burns

load("@rules_shell//shell:sh_test.bzl", "sh_test")
load("//lint:defs.bzl", "cspell_test", "gitleaks_history", "gitleaks_test", "rumdl_test", "shellcheck_test", "shfmt_test", "vale_test", "workflow_lint_test")
load("//lint/private:gitleaks_tool.bzl", "gitleaks_tool")
load("//lint/private:review_policy.bzl", "review_policy_test")
Expand Down Expand Up @@ -121,6 +122,28 @@ gitleaks_tool(name = "gitleaks_optional")

PROOF_TAGS = ["manual"]

sh_test(
name = "pr_merge_base_test",
srcs = ["pr_merge_base_test.sh"],
data = [
"//lint:commit_identity",
"//lint:commit_messages",
"//lint:pr_merge_base",
"@tbhb_rules_git//:git",
],
env = {
"GIT_RLOCATIONPATH": "$(rlocationpath @tbhb_rules_git//:git)",
"IDENTITY_RLOCATIONPATH": "$(rlocationpath //lint:commit_identity)",
"MERGE_BASE_RLOCATIONPATH": "$(rlocationpath //lint:pr_merge_base)",
"MESSAGES_RLOCATIONPATH": "$(rlocationpath //lint:commit_messages)",
},
# Tech debt (AGENTS.md): run this Git fixture on windows-2025 and remove the exclusion.
target_compatible_with = select({
"@platforms//os:windows": ["@platforms//:incompatible"],
"//conditions:default": [],
}),
)

# commit_identity against throwaway repositories.

commit_identity_crlf_test(name = "commit_identity_crlf_test")
Expand Down
82 changes: 82 additions & 0 deletions lint/tests/pr_merge_base_test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: Apache-2.0
# Copyright Tony Burns

set -euo pipefail

git="$TEST_SRCDIR/$GIT_RLOCATIONPATH"
identity="$TEST_SRCDIR/$IDENTITY_RLOCATIONPATH"
merge_base="$TEST_SRCDIR/$MERGE_BASE_RLOCATIONPATH"
messages="$TEST_SRCDIR/$MESSAGES_RLOCATIONPATH"
repo="$TEST_TMPDIR/repo"
export PATH="${git%/*}:$PATH" BUILD_WORKSPACE_DIRECTORY="$repo" LC_ALL=C
export GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null GIT_TEMPLATE_DIR=

in_repo() { "$git" -C "$repo" "$@"; }

as_agent_on_github() {
GIT_AUTHOR_NAME='tbhb.dev Agent' GIT_AUTHOR_EMAIL=agent@tonyburns.net \
GIT_COMMITTER_NAME=GitHub GIT_COMMITTER_EMAIL=noreply@github.com in_repo "$@"
}

expect_failure() {
local expected_status=$1 expected_text=$2 actual_status=0 output
shift 2
output=$("$@" 2>&1) || actual_status=$?
if [[ $actual_status != "$expected_status" || $output != *"$expected_text"* ]]; then
printf 'Expected status %s and output containing %s, received status %s and output:\n%s\n' \
"$expected_status" "$expected_text" "$actual_status" "$output" >&2
exit 1
fi
}

mkdir "$repo"
in_repo init -q -b main
in_repo config user.name 'Tony Burns'
in_repo config user.email tony@tonyburns.net
in_repo commit -qm 'chore: start the fixture' --allow-empty
stored_base=$(in_repo rev-parse HEAD)
in_repo switch -qc topic
in_repo commit -qm 'fix: check the topic commit' --allow-empty
in_repo switch -qc upstream "$stored_base"
# Both checkers skip merge commits. The non-merge commit brought in by the
# upstream merge supplies the stale range's identity and subject failures.
as_agent_on_github commit -qm 'fixup! upstream change' --allow-empty
upstream=$(in_repo rev-parse HEAD)
in_repo switch -q main
as_agent_on_github merge -q --no-ff -m 'Merge upstream' upstream
merged_main=$(in_repo rev-parse HEAD)
in_repo switch -q topic
as_agent_on_github merge -q --no-ff -m 'Merge main' main
head=$(in_repo rev-parse HEAD)
in_repo switch -q main
in_repo commit -qm 'chore: advance main again' --allow-empty
"$git" clone -q --bare "$repo" "$TEST_TMPDIR/origin"
in_repo remote add origin "$TEST_TMPDIR/origin"
in_repo fetch -q origin

# A pull request workflow checks out a synthetic merge with current main.
in_repo switch -q --detach main
as_agent_on_github merge -q --no-ff -m 'Merge topic for CI' topic

base=$("$merge_base" main "$head")
[[ $base == "$merged_main" ]]
identity_output=$("$identity" "$base" "$head")
messages_output=$("$messages" "$base" "$head")
[[ $identity_output == 'commit_identity: 1 commits checked' ]]
[[ $messages_output == 'commit_messages: 1 commits checked' ]]
expect_failure 1 "commit_identity: FAIL: $upstream author and committer are not an allowed pair" \
"$identity" "$stored_base" "$head"
expect_failure 1 "commit_messages: FAIL: $upstream fixup!, squash! and amend! subjects must be reworded" \
"$messages" "$stored_base" "$head"

in_repo update-ref -d refs/remotes/origin/main
fetched_base=$("$merge_base" main "$head")
[[ $fetched_base == "$merged_main" ]]
origin_tip=$(in_repo rev-parse refs/remotes/origin/main)
main_tip=$(in_repo rev-parse main)
[[ $origin_tip == "$main_tip" ]]
expect_failure 2 'usage: pr_merge_base BASE_REF HEAD' "$merge_base" main
expect_failure 1 'run this target with bazel run' env -u BUILD_WORKSPACE_DIRECTORY "$merge_base" main "$head"
expect_failure 128 "couldn't find remote ref refs/heads/missing" "$merge_base" missing "$head"
expect_failure 128 'Not a valid object name missing' "$merge_base" main missing
Loading
Loading