Skip to content
Open
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
4 changes: 3 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ sonarqube {

// Install git hooks
tasks.register('installLocalGitHook', Copy) {
from new File(rootProject.rootDir, 'scripts/pre-commit')
from(new File(rootProject.rootDir, 'scripts')) {
include 'pre-commit', 'pre-push'
}
into new File(rootProject.rootDir, '.git/hooks')
filePermissions {
unix("rwxrwxr-x")
Expand Down
69 changes: 69 additions & 0 deletions scripts/pre-push
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#!/bin/sh
# pre-push hook: blocks history-rewriting pushes to branches whose open PR
# already has reviews. Bypass deliberately with: git push --no-verify

UPSTREAM_REPO="Together-Java/TJ-Bot"
ZERO_OID="0000000000000000000000000000000000000000"

log() {
printf '[pre-push] %s\n' "$*" >&2
}

# number of open PRs from branch $1 that have at least one review.
# </dev/null so github can't swallow the ref lines we're reading from stdin.
count_reviewed_prs() {
gh pr list --repo "$UPSTREAM_REPO" --head "$1" --state open \
--json reviews,headRepositoryOwner \
--jq --arg owner "$owner" '[.[] | select(.headRepositoryOwner.login == $owner and (.reviews | length > 0))] | length'
}
Comment on lines +14 to +18

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very technically, I think this could fail if 2 PRs exist from the same branch name (but different remote)

At the start of the project, we have had cases where 2 branches exist with the same name, but that was very particular with some bigger stuff, thats not an issue anymore so I personally dont think this is an issue (one can just ignore the check)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, it's rare and fails in the safe direction with --no-verify as the escape trick. I've documented the limitation in the readme file ive added today, rather than adding more complexity to the script, what do you think?


# Returns 0 if the ref may be pushed, 1 if it must be blocked.
check_ref() {
local_oid=$1
remote_ref=$2
remote_oid=$3

case "$remote_ref" in refs/heads/*) ;; *) return 0 ;; esac
[ "$local_oid" = "$ZERO_OID" ] && return 0
[ "$remote_oid" = "$ZERO_OID" ] && return 0
# exit 0 = fast-forward. Any other code (1 = diverged, 128 = e.g. remote-commit not fetched locally)
# intentionally falls through to the PR check
git merge-base --is-ancestor "$remote_oid" "$local_oid" 2>/dev/null && return 0

Comment on lines +31 to +32

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
git merge-base --is-ancestor "$remote_oid" "$local_oid" 2>/dev/null && return 0
git merge-base --is-ancestor "$remote_oid" "$local_oid" 2>/dev/null
case "$?" in
0) return 0 ;;
1) ;; # Non-fast-forward, continue checking
*)
log "Could not determine commit ancestry, skipping check."
return 0
;;
esac

If the command returns an error a non 0 number, it would run the Git Hook even if it is a fast-forward merge

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A real fastforward exits 0, so it never reaches the check. The only case that falls through is an error (exit 128), typically when the remote commit isn't in the local object db because the branchh wasn't fetched. That's the situation where over-writing remote work is most likely, so I'd rather run the pr check there than skipit

The cost is one extra gh call, and gh failures already fail open. I've added a comment in the script to make this explicit, check it out

branch=${remote_ref#refs/heads/}
log "Non-fast-forward push to '$branch', checking for reviewed PRs..."

if ! command -v gh >/dev/null 2>&1; then
log "'gh' not found, skipping check."
return 0
fi

if ! reviewed=$(count_reviewed_prs "$branch"); then
log "Could not query GitHub (offline or not authenticated), skipping check."
return 0
fi

if [ "${reviewed:-0}" -gt 0 ]; then
log "BLOCKED: '$branch' has an open PR with existing reviews."
log "Rewriting history can make review comments outdated and make it harder for reviewers, and you to track changes."
log "Consider pushing an additional commit instead."
log "To intentionally bypass this check, use git push --no-verify"
return 1
fi

log "No reviewed PR found for '$branch', OK."
return 0
}

log "Starting history-rewrite check..."
status=0
while read -r _local_ref local_oid remote_ref remote_oid; do
check_ref "$local_oid" "$remote_ref" "$remote_oid" || status=1
done

if [ "$status" -eq 0 ]; then
log "Check finished: push allowed."
else
log "Check finished: push blocked."
fi
exit "$status"
67 changes: 67 additions & 0 deletions scripts/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Local Git hooks

This repository installs a pre-commit hook for formatting and linting checks and
a pre-push hook that protects reviewed pull requests.

## Pre-commit hook: check your changes

Before each commit, this hook formats the staged Java changes with Spotless and
runs SonarLint. Formatting fixes are staged automatically; if either check fails,
the commit is stopped. Your unstaged changes are kept separate.

To skip the checks for one commit:

```bash
git commit --no-verify
```

## Pre-push hook: protect reviewed PRs

Rebasing, amending or squashing and then force pushing rewrites history, which
detaches review comments on an open PR. This hook blocks that push.

### How it works

On `git push`, for each ref:

1. Skip tags, branch deletions and new branches.
2. Skip **fast-forward** pushes (remote tip is an ancestor of your commit), so
normal pushes never hit the API.
3. For **non-fast-forward** pushes, ask GitHub if the branch has an open PR with
at least one review:
```sh
gh pr list --repo Together-Java/TJ-Bot --head "<branch>" --state open \
--json reviews --jq '[.[] | select(.reviews | length > 0)] | length'
```
4. Block if the count is above `0`, otherwise allow.

If `gh` is missing or the query fails, it **fails open** and logs why.

### Bypass

```bash
git push --force-with-lease --no-verify
```

### Good practice instead

Add `git commit --fixup` commits, merge the base branch instead of rebasing,
and squash at merge time.

### Notes

- `--force-with-lease` doesn't know about reviews, so it doesn't replace this hook.
- `--head` matches by branch name only, so same-named branches from other forks
can cause a false block.
- It can't tell a harmless force push from a destructive one, so it errs on the
side of blocking.

## Install the hooks

The hooks are installed as part of the build. To install them manually:

```bash
./gradlew installLocalGitHook
```

Requires an authenticated [`gh`](https://cli.github.com/) and LF line endings.
Loading