1#!/usr/bin/env bash
2
3# Requests reviews for a PR after verifying that the base branch is correct
4
5set -euo pipefail
6tmp=$(mktemp -d)
7trap 'rm -rf "$tmp"' exit
8SCRIPT_DIR=$(dirname "$0")
9
10log() {
11 echo "$@" >&2
12}
13
14effect() {
15 if [[ -n "${DRY_MODE:-}" ]]; then
16 log "Skipping in dry mode:" "${@@Q}"
17 else
18 "$@"
19 fi
20}
21
22if (( $# < 3 )); then
23 log "Usage: $0 GITHUB_REPO PR_NUMBER OWNERS_FILE"
24 exit 1
25fi
26baseRepo=$1
27prNumber=$2
28ownersFile=$3
29
30log "Fetching PR info"
31prInfo=$(gh api \
32 -H "Accept: application/vnd.github+json" \
33 -H "X-GitHub-Api-Version: 2022-11-28" \
34 "/repos/$baseRepo/pulls/$prNumber")
35
36baseBranch=$(jq -r .base.ref <<< "$prInfo")
37log "Base branch: $baseBranch"
38prRepo=$(jq -r .head.repo.full_name <<< "$prInfo")
39log "PR repo: $prRepo"
40prBranch=$(jq -r .head.ref <<< "$prInfo")
41log "PR branch: $prBranch"
42prAuthor=$(jq -r .user.login <<< "$prInfo")
43log "PR author: $prAuthor"
44
45extraArgs=()
46if pwdRepo=$(git rev-parse --show-toplevel 2>/dev/null); then
47 # Speedup for local runs
48 extraArgs+=(--reference-if-able "$pwdRepo")
49fi
50
51log "Fetching Nixpkgs commit history"
52# We only need the commit history, not the contents, so we can do a tree-less clone using tree:0
53# https://github.blog/open-source/git/get-up-to-speed-with-partial-clone-and-shallow-clone/#user-content-quick-summary
54git clone --bare --filter=tree:0 --no-tags --origin upstream "${extraArgs[@]}" https://github.com/"$baseRepo".git "$tmp"/nixpkgs.git
55
56log "Fetching the PR commit history"
57# Fetch the PR
58git -C "$tmp/nixpkgs.git" remote add fork https://github.com/"$prRepo".git
59# This remote config is the same as --filter=tree:0 when cloning
60git -C "$tmp/nixpkgs.git" config remote.fork.partialclonefilter tree:0
61git -C "$tmp/nixpkgs.git" config remote.fork.promisor true
62
63git -C "$tmp/nixpkgs.git" fetch --no-tags fork "$prBranch"
64headRef=$(git -C "$tmp/nixpkgs.git" rev-parse refs/remotes/fork/"$prBranch")
65
66log "Checking correctness of the base branch"
67if ! "$SCRIPT_DIR"/verify-base-branch.sh "$tmp/nixpkgs.git" "$headRef" "$baseRepo" "$baseBranch" "$prRepo" "$prBranch" | tee "$tmp/invalid-base-error" >&2; then
68 log "Posting error as comment"
69 if ! response=$(effect gh api \
70 --method POST \
71 -H "Accept: application/vnd.github+json" \
72 -H "X-GitHub-Api-Version: 2022-11-28" \
73 "/repos/$baseRepo/issues/$prNumber/comments" \
74 -F "body=@$tmp/invalid-base-error"); then
75 log "Failed to post the comment: $response"
76 fi
77 exit 1
78fi
79
80log "Requesting reviews from code owners"
81"$SCRIPT_DIR"/get-code-owners.sh "$tmp/nixpkgs.git" "$ownersFile" "$baseBranch" "$headRef" | \
82 "$SCRIPT_DIR"/request-reviewers.sh "$baseRepo" "$prNumber" "$prAuthor"