-
-
Notifications
You must be signed in to change notification settings - Fork 113
Expand file tree
/
Copy pathpullRequests.ts
More file actions
311 lines (267 loc) · 10.4 KB
/
Copy pathpullRequests.ts
File metadata and controls
311 lines (267 loc) · 10.4 KB
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
import * as core from '@actions/core'
import {RestEndpointMethodTypes} from '@octokit/rest'
import moment from 'moment'
import {Property, Sort} from './types'
import {Commits, DiffInfo, filterCommits} from './commits'
import {Options} from './prCollector'
import {BaseRepository} from '../repositories/BaseRepository'
export interface PullRequestInfo {
number: number
title: string
htmlURL: string
baseBranch: string
branch?: string
createdAt: moment.Moment
mergedAt: moment.Moment | undefined
mergeCommitSha: string
author: string
repoName: string
labels: string[]
milestone: string
body: string
assignees: string[]
requestedReviewers: string[]
approvedReviewers: string[]
reviews?: CommentInfo[]
status: 'open' | 'merged'
committers: string[]
}
export interface CommentInfo {
id: number
htmlURL: string
submittedAt: moment.Moment | undefined
author: string
body: string
state: string | undefined
}
export const EMPTY_PULL_REQUEST_INFO: PullRequestInfo = {
number: 0,
title: '',
htmlURL: '',
baseBranch: '',
mergedAt: undefined,
createdAt: moment(),
mergeCommitSha: '',
author: '',
repoName: '',
labels: [],
milestone: '',
body: '',
assignees: [],
requestedReviewers: [],
approvedReviewers: [],
status: 'open',
committers: []
}
export const EMPTY_COMMENT_INFO: CommentInfo = {
id: 0,
htmlURL: '',
submittedAt: undefined,
author: '',
body: '',
state: undefined
}
export type PullData = RestEndpointMethodTypes['pulls']['get']['response']['data']
export type PullsListData = RestEndpointMethodTypes['pulls']['list']['response']['data']
export type PullReviewsData = RestEndpointMethodTypes['pulls']['listReviews']['response']['data']
export class PullRequests {
constructor(
private repositoryUtils: BaseRepository,
private commits: Commits
) {}
async getForCommitHash(owner: string, repo: string, commit_sha: string, maxPullRequests: number): Promise<PullRequestInfo[]> {
return sortPrs(await this.repositoryUtils.getForCommitHash(owner, repo, commit_sha, maxPullRequests))
}
async getBetweenDates(
owner: string,
repo: string,
fromDate: moment.Moment,
toDate: moment.Moment,
maxPullRequests: number
): Promise<PullRequestInfo[]> {
return sortPrs(await this.repositoryUtils.getBetweenDates(owner, repo, fromDate, toDate, maxPullRequests))
}
async getOpen(owner: string, repo: string, maxPullRequests: number): Promise<PullRequestInfo[]> {
return sortPrs(await this.repositoryUtils.getOpen(owner, repo, maxPullRequests))
}
async getReviews(owner: string, repo: string, pr: PullRequestInfo): Promise<void> {
await this.repositoryUtils.getReviews(owner, repo, pr)
}
async getMergedPullRequests(options: Options): Promise<[DiffInfo, PullRequestInfo[]]> {
const {owner, repo, includeOpen, fetchReviewers, fetchReviews, configuration} = options
const diffInfo = await this.commits.getCommitHistory(options)
const commits = diffInfo.commitInfo
if (commits.length === 0) {
return [diffInfo, []]
}
const firstCommit = commits[0]
const lastCommit = commits[commits.length - 1]
let fromDate = moment.min(firstCommit.authorDate, firstCommit.commitDate) // get the lower date (e.g. if commits are modified)
const toDate = moment.max(lastCommit.authorDate, lastCommit.commitDate) // ensure we get the higher date (e.g. in case of rebases)
const maxDays = configuration.max_back_track_time_days
const maxFromDate = toDate.clone().subtract(maxDays, 'days')
if (maxFromDate.isAfter(fromDate)) {
core.info(`⚠️ Adjusted 'fromDate' to go max ${maxDays} back`)
fromDate = maxFromDate
}
core.info(`ℹ️ Fetching PRs between dates ${fromDate.toISOString()} to ${toDate.toISOString()} for ${owner}/${repo}`)
const prCommits = filterCommits(commits, configuration.exclude_merge_branches)
core.info(`ℹ️ Retrieved ${prCommits.length} release commits for ${owner}/${repo}`)
const prCommittersMap = new Map<string, string[]>();
const uniqueAuthors = new Set<string>();
// Iterate over each entry in prCommittersMap
for (const [commitSha, authors] of prCommittersMap.entries()) {
// Iterate over each author in the array and add to the set
authors.forEach(author => {
uniqueAuthors.add(author);
});
}
// Convert Set to array (if needed)
const uniqueAuthorsList = Array.from(uniqueAuthors);
// create array of commits for this release
const releaseCommitHashes = prCommits.map(commit => {
return commit.sha
})
let pullRequests: PullRequestInfo[]
if (options.fetchViaCommits) {
// fetch PRs based on commits instead (will get associated PRs per commit found)
const prsForReleaseCommits: Map<number, PullRequestInfo> = new Map()
for (const commit of prCommits) {
const result = await this.getForCommitHash(owner, repo, commit.sha, configuration.max_pull_requests)
for (const pr of result) {
prsForReleaseCommits.set(pr.number, pr)
}
}
const dedupedPrsForReleaseCommits = Array.from(prsForReleaseCommits.values())
if (!includeOpen) {
pullRequests = dedupedPrsForReleaseCommits.filter(pr => pr.status !== 'open')
core.info(`ℹ️ Retrieved ${pullRequests.length} PRs for ${owner}/${repo} based on the release commit hashes`)
} else {
pullRequests = dedupedPrsForReleaseCommits
core.info(`ℹ️ Retrieved ${pullRequests.length} PRs for ${owner}/${repo} based on the release commit hashes (including open)`)
}
} else {
// fetch PRs based on the date range identified
const pullRequestsBetweenDate = await this.getBetweenDates(owner, repo, fromDate, toDate, configuration.max_pull_requests)
core.info(`ℹ️ Retrieved ${pullRequestsBetweenDate.length} PRs for ${owner}/${repo} in date range from API`)
// filter out pull requests not associated with this release
const mergedPullRequests = pullRequestsBetweenDate.filter(pr => {
return releaseCommitHashes.includes(pr.mergeCommitSha)
})
core.info(`ℹ️ Retrieved ${mergedPullRequests.length} merged PRs for ${owner}/${repo}`)
let allPullRequests = mergedPullRequests
if (includeOpen) {
// retrieve all open pull requests
const openPullRequests = await this.getOpen(owner, repo, configuration.max_pull_requests)
core.info(`ℹ️ Retrieved ${openPullRequests.length} open PRs for ${owner}/${repo}`)
// all pull requests
allPullRequests = allPullRequests.concat(openPullRequests)
core.info(`ℹ️ Retrieved ${allPullRequests.length} total PRs for ${owner}/${repo}`)
}
pullRequests = allPullRequests
}
// Update each pull request with its committers
pullRequests.forEach(pr => {
if (prCommittersMap.has(pr.number)) {
pr.committers = prCommittersMap.get(pr.number);
} else {
pr.committers = [];
}
});
// retrieve base branches we allow
const baseBranches = configuration.base_branches
const baseBranchPatterns = baseBranches.map(baseBranch => {
return new RegExp(baseBranch.replace('\\\\', '\\'), 'gu')
})
// return only prs if the baseBranch is matching the configuration
const finalPrs = pullRequests.filter(pr => {
if (baseBranches.length !== 0) {
return baseBranchPatterns.some(pattern => {
return pr.baseBranch.match(pattern) !== null
})
}
return true
})
if (baseBranches.length !== 0) {
core.info(`ℹ️ Retrieved ${finalPrs.length} PRs for ${owner}/${repo} filtered by the 'base_branches' configuration.`)
}
// fetch reviewers only if enabled (requires an additional API request per PR)
if (fetchReviews || fetchReviewers) {
core.info(`ℹ️ Fetching reviews (or reviewers) was enabled`)
// update PR information with reviewers who approved
for (const pr of finalPrs) {
await this.getReviews(owner, repo, pr)
const reviews = pr.reviews
if (reviews && (reviews?.length || 0) > 0) {
core.info(`ℹ️ Retrieved ${reviews.length || 0} review(s) for PR ${owner}/${repo}/#${pr.number}`)
// backwards compatibility
pr.approvedReviewers = reviews.filter(r => r.state === 'APPROVED').map(r => r.author)
} else {
core.debug(`No reviewer(s) for PR ${owner}/${repo}/#${pr.number}`)
}
}
} else {
core.debug(`ℹ️ Fetching reviews (or reviewers) was disabled`)
}
return [diffInfo, finalPrs]
}
}
function sortPrs(pullRequests: PullRequestInfo[]): PullRequestInfo[] {
return sortPullRequests(pullRequests, {
order: 'ASC',
on_property: 'mergedAt'
})
}
export function sortPullRequests(pullRequests: PullRequestInfo[], sort: Sort | string): PullRequestInfo[] {
let sortConfig: Sort
// legacy handling to support string sort config
if (typeof sort === 'string') {
let order: 'ASC' | 'DESC' = 'ASC'
if (sort.toUpperCase() === 'DESC') order = 'DESC'
sortConfig = {order, on_property: 'mergedAt'}
} else {
sortConfig = sort
}
if (sortConfig.order === 'ASC') {
pullRequests.sort((a, b) => {
return compare(a, b, sortConfig)
})
} else {
pullRequests.sort((b, a) => {
return compare(a, b, sortConfig)
})
}
return pullRequests
}
export function compare(a: PullRequestInfo, b: PullRequestInfo, sort: Sort): number {
if (sort.on_property === 'mergedAt') {
const aa = a.mergedAt || a.createdAt
const bb = b.mergedAt || b.createdAt
if (aa.isBefore(bb)) {
return -1
} else if (bb.isBefore(aa)) {
return 1
}
return 0
} else {
// only else for now `label`
return a.title.localeCompare(b.title)
}
}
/**
* Helper function to retrieve a property from the PullRequestInfo
*/
export function retrieveProperty(pr: PullRequestInfo, property: Property, useCase: string): string {
let value: string | number | Set<string> | string[] | undefined = pr[property]
if (value === undefined) {
core.warning(`⚠️ the provided property '${property}' for \`${useCase}\` is not valid. Fallback to 'body'`)
value = pr['body']
} else if (value instanceof Set) {
value = Array.from(value).join(',') // join into single string
} else if (Array.isArray(value)) {
value = value.join(',') // join into single string
} else {
value = value.toString()
}
return value
}