summaryrefslogtreecommitdiffstats
path: root/ci/github-script/reviews.js
blob: 584a035160f13470973800a14cc9be1cf99b5e03 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
const eventToState = {
  COMMENT: 'COMMENTED',
  REQUEST_CHANGES: 'CHANGES_REQUESTED',
}

// Use substring checks in order to allow testing in forks
// Usernames must also end in "[bot]"
const reviewUsers = [
  'github-actions',
  'nixpkgs-ci',
  'branch-check',
  'commit-check',
  'manual-edit',
]

/**
 * @typedef {InstanceType<typeof import('@actions/github/lib/utils').GitHub>} GitHub
 * @typedef {typeof import('@actions/github').context} Context
 *
 * @typedef {Awaited<ReturnType<GitHub['rest']['pulls']['listReviews']>>['data'][number]} Review
 * @typedef {Review & { user: NonNullable<Review['user']> }} ReviewWithNonNullUser
 */

/**
 * @param {{
 *  github: GitHub,
 *  context: Context,
 *  core: typeof import('@actions/core'),
 *  dry: boolean,
 *  reviewKey?: string,
 * }} DismissReviewsProps
 */
export async function dismissReviews({
  github,
  context,
  core,
  dry,
  reviewKey,
}) {
  const pull_number = context.payload.pull_request?.number
  if (!pull_number) {
    core.warning('dismissReviews called outside of pull_request context')
    return
  }

  if (dry) {
    return
  }

  const allReviews = await github.paginate(github.rest.pulls.listReviews, {
    ...context.repo,
    pull_number,
  })

  const reviews = /** @type {ReviewWithNonNullUser[]} */ (
    allReviews.filter(
      (review) =>
        review.user &&
        review.state !== 'DISMISSED' &&
        review.user.login.endsWith('[bot]') &&
        reviewUsers.some((substr) => review.user?.login.includes(substr)),
    )
  )

  const reviewsByUser = reviews.reduce(
    (prev, curr) => {
      if (!(curr.user.login in prev)) {
        prev[curr.user.login] = []
      }

      prev[curr.user.login].push(curr)

      return prev
    },
    /** @type {Record<string, ReviewWithNonNullUser[]> } */ ({}),
  )

  const commentRegex = new RegExp(
    /<!-- nixpkgs review key: (.*)(?:; resolved: .*)? -->/,
  )
  const reviewKeyRegex = new RegExp(
    `<!-- (nixpkgs review key: ${reviewKey})(?:; resolved: .*)? -->`,
  )
  const commentResolvedRegex = new RegExp(
    /<!-- nixpkgs review key: .*; resolved: true -->/,
  )

  let reviewsToMinimize = reviews
  const /** @type {ReviewWithNonNullUser[]} */ reviewsToDismiss = []
  const /** @type {ReviewWithNonNullUser[]} */ reviewsToResolve = []

  if (reviewKey && reviews.every((review) => commentRegex.test(review.body))) {
    reviewsToMinimize = reviews.filter((review) =>
      reviewKeyRegex.test(review.body),
    )
  }

  for (const reviewsForUser of Object.values(reviewsByUser)) {
    // Make sure that we don't dismiss all reviews by a user if they
    // have any reviews we don't want to dismiss.
    if (
      reviewsForUser.every(
        (review) =>
          commentResolvedRegex.test(review.body) ||
          (reviewKey && reviewKeyRegex.test(review.body)) ||
          // If we are called by check-commits and the review body is clearly
          // from `commits.js`, then we can safely dismiss the review.
          // This helps with pre-existing reviews (before the comments were added).
          (reviewKey &&
            reviewKey === 'check-commits' &&
            review.body.includes('PR / Check / cherry-pick')),
      )
    ) {
      reviewsToDismiss.push(
        ...reviewsForUser.filter(
          (review) => review.state === 'CHANGES_REQUESTED',
        ),
      )
    } else {
      reviewsToResolve.push(
        ...reviewsForUser.filter(
          (review) =>
            review.state === 'CHANGES_REQUESTED' &&
            !commentResolvedRegex.test(review.body) &&
            reviewsToMinimize.some(
              (toMinimize) => toMinimize.node_id === review.node_id,
            ),
        ),
      )
    }
  }

  await Promise.all([
    ...reviewsToMinimize.map(async (review) =>
      github.graphql(
        `mutation($node_id:ID!) {
              minimizeComment(input: {
                classifier: OUTDATED,
                subjectId: $node_id
              })
              { clientMutationId }
            }`,
        { node_id: review.node_id },
      ),
    ),
    ...reviewsToDismiss.map(async (review) =>
      github.rest.pulls.dismissReview({
        ...context.repo,
        pull_number,
        review_id: review.id,
        message: 'Review dismissed automatically',
      }),
    ),
    ...reviewsToResolve.map(async (review) =>
      github.rest.pulls.updateReview({
        ...context.repo,
        pull_number,
        review_id: review.id,
        body: review.body.replace(
          reviewKeyRegex,
          `<!-- nixpkgs review key: ${reviewKey}; resolved: true -->`,
        ),
      }),
    ),
  ])
}

/**
 * @param {{
 *  github: GitHub,
 *  context: Context,
 *  core: typeof import('@actions/core'),
 *  dry: boolean,
 *  body: string,
 *  event: keyof typeof eventToState,
 *  reviewKey: string,
 * }} PostReviewProps
 */
export async function postReview({
  github,
  context,
  core,
  dry,
  body,
  event = 'REQUEST_CHANGES',
  reviewKey,
}) {
  const pull_number = context.payload.pull_request?.number
  if (!pull_number) {
    core.warning('postReview called outside of pull_request context')
    return
  }

  const reviewKeyRegex = new RegExp(
    `<!-- (nixpkgs review key: ${reviewKey})(?:; resolved: .*)? -->`,
  )
  const reviewKeyComment = `<!-- nixpkgs review key: ${reviewKey}; resolved: false -->`
  body = body + '\n\n' + reviewKeyComment

  const reviews = (
    await github.paginate(github.rest.pulls.listReviews, {
      ...context.repo,
      pull_number,
    })
  ).filter(
    (review) =>
      review.user &&
      review.state !== 'DISMISSED' &&
      review.user.login.endsWith('[bot]') &&
      reviewUsers.some((substr) => review.user?.login.includes(substr)),
  )

  /** @type {null | Review} */
  let pendingReview
  const matchingReviews = reviews.filter((review) =>
    reviewKeyRegex.test(review.body),
  )

  if (matchingReviews.length === 0) {
    pendingReview = null
  } else if (
    matchingReviews.length === 1 &&
    matchingReviews[0].state === eventToState[event]
  ) {
    pendingReview = matchingReviews[0]
  } else {
    await dismissReviews({
      github,
      context,
      core,
      dry,
      reviewKey,
    })
    pendingReview = null
  }

  if (dry) {
    if (pendingReview)
      core.info(`pending review found: ${pendingReview.html_url}`)
    else core.info('no pending review found')
    core.info(body)
  } else {
    if (pendingReview) {
      await Promise.all([
        github.rest.pulls.updateReview({
          ...context.repo,
          pull_number,
          review_id: pendingReview.id,
          body,
        }),
        github.graphql(
          `mutation($node_id:ID!) {
              unminimizeComment(input: {
                subjectId: $node_id
              })
              { clientMutationId }
            }`,
          { node_id: pendingReview.node_id },
        ),
      ])
    } else {
      await github.rest.pulls.createReview({
        ...context.repo,
        pull_number,
        event,
        body,
      })
    }
  }
}