1const { classify } = require('../supportedBranches.js')
2const { postReview } = require('./reviews.js')
3
4module.exports = async ({ github, context, core, dry }) => {
5 const pull_number = context.payload.pull_request.number
6
7 for (const retryInterval of [5, 10, 20, 40, 80]) {
8 core.info('Checking whether the pull request can be merged...')
9 const prInfo = (
10 await github.rest.pulls.get({
11 ...context.repo,
12 pull_number,
13 })
14 ).data
15
16 if (prInfo.state !== 'open') throw new Error('PR is not open anymore.')
17
18 if (prInfo.mergeable == null) {
19 core.info(
20 `GitHub is still computing whether this PR can be merged, waiting ${retryInterval} seconds before trying again...`,
21 )
22 await new Promise((resolve) => setTimeout(resolve, retryInterval * 1000))
23 continue
24 }
25
26 const { base, head } = prInfo
27
28 const baseClassification = classify(base.ref)
29 core.setOutput('base', baseClassification)
30 console.log('base classification:', baseClassification)
31
32 const headClassification =
33 base.repo.full_name === head.repo.full_name
34 ? classify(head.ref)
35 : // PRs from forks are always considered WIP.
36 { type: ['wip'] }
37 core.setOutput('head', headClassification)
38 console.log('head classification:', headClassification)
39
40 if (baseClassification.type.includes('channel')) {
41 const { stable, version } = baseClassification
42 const correctBranch = stable ? `release-${version}` : 'master'
43 const body = [
44 'The `nixos-*` and `nixpkgs-*` branches are pushed to by the channel release script and should not be merged into directly.',
45 '',
46 `Please target \`${correctBranch}\` instead.`,
47 ].join('\n')
48
49 await postReview({ github, context, core, dry, body })
50
51 throw new Error('The PR targets a channel branch.')
52 }
53
54 if (headClassification.type.includes('wip')) {
55 // In the following, we look at the git history to determine the base branch that
56 // this Pull Request branched off of. This is *supposed* to be the branch that it
57 // merges into, but humans make mistakes. Once that happens we want to error out as
58 // early as possible.
59
60 // To determine the "real base", we are looking at the merge-base of primary development
61 // branches and the head of the PR. The merge-base which results in the least number of
62 // commits between that base and head is the real base. We can query for this via GitHub's
63 // REST API. There can be multiple candidates for the real base with the same number of
64 // commits. In this case we pick the "best" candidate by a fixed ordering of branches,
65 // as defined in ci/supportedBranches.js.
66 //
67 // These requests take a while, when comparing against the wrong release - they need
68 // to look at way more than 10k commits in that case. Thus, we try to minimize the
69 // number of requests across releases:
70 // - First, we look at the primary development branches only: master and release-xx.yy.
71 // The branch with the fewest commits gives us the release this PR belongs to.
72 // - We then compare this number against the relevant staging branches for this release
73 // to find the exact branch that this belongs to.
74
75 // All potential development branches
76 const branches = (
77 await github.paginate(github.rest.repos.listBranches, {
78 ...context.repo,
79 per_page: 100,
80 })
81 ).map(({ name }) => classify(name))
82
83 // All stable primary development branches from latest to oldest.
84 const releases = branches
85 .filter(({ stable, type }) => type.includes('primary') && stable)
86 .sort((a, b) => b.version.localeCompare(a.version))
87
88 async function mergeBase({ branch, order, version }) {
89 const { data } = await github.rest.repos.compareCommitsWithBasehead({
90 ...context.repo,
91 basehead: `${branch}...${head.sha}`,
92 // Pagination for this endpoint is about the commits listed, which we don't care about.
93 per_page: 1,
94 // Taking the second page skips the list of files of this changeset.
95 page: 2,
96 })
97 return {
98 branch,
99 order,
100 version,
101 commits: data.total_commits,
102 sha: data.merge_base_commit.sha,
103 }
104 }
105
106 // Multiple branches can be OK at the same time, if the PR was created of a merge-base,
107 // thus storing as array.
108 let candidates = [await mergeBase(classify('master'))]
109 for (const release of releases) {
110 const nextCandidate = await mergeBase(release)
111 if (candidates[0].commits === nextCandidate.commits)
112 candidates.push(nextCandidate)
113 if (candidates[0].commits > nextCandidate.commits)
114 candidates = [nextCandidate]
115 // The number 10000 is principally arbitrary, but the GitHub API returns this value
116 // when the number of commits exceeds it in reality. The difference between two stable releases
117 // is certainly more than 10k commits, thus this works for us as well: If we're targeting
118 // a wrong release, the number *will* be 10000.
119 if (candidates[0].commits < 10000) break
120 }
121
122 core.info(`This PR is for NixOS ${candidates[0].version}.`)
123
124 // Secondary development branches for the selected version only.
125 const secondary = branches.filter(
126 ({ branch, type, version }) =>
127 type.includes('secondary') && version === candidates[0].version,
128 )
129
130 // Make sure that we always check the current target as well, even if its a WIP branch.
131 // If it's not a WIP branch, it was already included in either releases or secondary.
132 if (classify(base.ref).type.includes('wip')) {
133 secondary.push(classify(base.ref))
134 }
135
136 for (const branch of secondary) {
137 const nextCandidate = await mergeBase(branch)
138 if (candidates[0].commits === nextCandidate.commits)
139 candidates.push(nextCandidate)
140 if (candidates[0].commits > nextCandidate.commits)
141 candidates = [nextCandidate]
142 }
143
144 // If the current branch is among the candidates, this is always better than any other,
145 // thus sorting at -1.
146 candidates = candidates
147 .map((candidate) =>
148 candidate.branch === base.ref
149 ? { ...candidate, order: -1 }
150 : candidate,
151 )
152 .sort((a, b) => a.order - b.order)
153
154 const best = candidates.at(0)
155
156 core.info('The base branches for this PR are:')
157 core.info(`github: ${base.ref}`)
158 core.info(
159 `candidates: ${candidates.map(({ branch }) => branch).join(',')}`,
160 )
161 core.info(`best candidate: ${best.branch}`)
162
163 if (best.branch !== base.ref) {
164 const current = await mergeBase(classify(base.ref))
165 const body = [
166 `The PR's base branch is set to \`${current.branch}\`, but ${current.commits === 10000 ? 'at least 10000' : current.commits - best.commits} commits from the \`${best.branch}\` branch are included. Make sure you know the [right base branch for your changes](https://github.com/NixOS/nixpkgs/blob/master/CONTRIBUTING.md#branch-conventions), then:`,
167 `- If the changes should go to the \`${best.branch}\` branch, [change the base branch](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-base-branch-of-a-pull-request).`,
168 `- If the changes should go to the \`${current.branch}\` branch, rebase your PR onto the correct merge-base:`,
169 ' ```bash',
170 ` # git rebase --onto $(git merge-base upstream/${current.branch} HEAD) $(git merge-base upstream/${best.branch} HEAD)`,
171 ` git rebase --onto ${current.sha} ${best.sha}`,
172 ` git push --force-with-lease`,
173 ' ```',
174 ].join('\n')
175
176 await postReview({ github, context, core, dry, body })
177
178 throw new Error(`The PR contains commits from a different base.`)
179 }
180 }
181
182 let mergedSha, targetSha
183
184 if (prInfo.mergeable) {
185 core.info('The PR can be merged.')
186
187 mergedSha = prInfo.merge_commit_sha
188 targetSha = (
189 await github.rest.repos.getCommit({
190 ...context.repo,
191 ref: prInfo.merge_commit_sha,
192 })
193 ).data.parents[0].sha
194 } else {
195 core.warning('The PR has a merge conflict.')
196
197 mergedSha = head.sha
198 targetSha = (
199 await github.rest.repos.compareCommitsWithBasehead({
200 ...context.repo,
201 basehead: `${base.sha}...${head.sha}`,
202 })
203 ).data.merge_base_commit.sha
204 }
205
206 core.info(
207 `Checking the commits:\nmerged: ${mergedSha}\ntarget: ${targetSha}`,
208 )
209 core.setOutput('mergedSha', mergedSha)
210 core.setOutput('targetSha', targetSha)
211
212 core.setOutput('systems', require('../supportedSystems.json'))
213
214 const files = (
215 await github.paginate(github.rest.pulls.listFiles, {
216 ...context.repo,
217 pull_number: context.payload.pull_request.number,
218 per_page: 100,
219 })
220 ).map((file) => file.filename)
221
222 const touched = []
223 if (files.includes('ci/pinned.json')) touched.push('pinned')
224 core.setOutput('touched', touched)
225
226 return
227 }
228 throw new Error(
229 "Not retrying anymore. It's likely that GitHub is having internal issues: check https://www.githubstatus.com.",
230 )
231}