-
Notifications
You must be signed in to change notification settings - Fork 192
/
Copy pathtransform-pull-request.ts
263 lines (230 loc) · 9.7 KB
/
transform-pull-request.ts
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
import { isEmpty, omit } from "lodash";
import { getJiraId } from "../jira/util/id";
import { Octokit } from "@octokit/rest";
import Logger from "bunyan";
import { getJiraAuthor, jiraIssueKeyParser } from "utils/jira-utils";
import { getGithubUser } from "services/github/user";
import { generateCreatePullRequestUrl } from "./util/pull-request-link-generator";
import { GitHubInstallationClient } from "../github/client/github-installation-client";
import { JiraReview } from "../interfaces/jira";
import { transformRepositoryDevInfoBulk } from "~/src/transforms/transform-repository";
import { pullRequestNode } from "~/src/github/client/github-queries";
const mapStatus = (status: string, merged_at?: string, draft?:boolean) => {
if (status.toLowerCase() === "merged") return "MERGED";
if (status.toLowerCase() === "open")
if (draft) return "DRAFT";
else return "OPEN";
if (status.toLowerCase() === "closed" && merged_at) return "MERGED";
if (status.toLowerCase() === "closed" && !merged_at) return "DECLINED";
if (status.toLowerCase() === "declined") return "DECLINED";
return "UNKNOWN";
};
interface JiraReviewer extends JiraReview {
login: string;
}
const STATE_APPROVED = "APPROVED";
const STATE_UNAPPROVED = "UNAPPROVED";
const mapReviewsRest = async (reviews: Array<{ state?: string, user: Octokit.PullsUpdateResponseRequestedReviewersItem }> = [], gitHubInstallationClient: GitHubInstallationClient): Promise<JiraReview[]> => {
const usernames: Record<string, JiraReviewer> = {};
// The reduce function goes through all the reviews and creates an array of unique users
// (so users' avatars won't be duplicated on the dev panel in Jira)
// and it considers 'APPROVED' as the main approval status for that user.
const reviewsReduced: JiraReviewer[] = reviews.reduce((acc: JiraReviewer[], review) => {
// Adds user to the usernames object if user is not yet added, then it adds that unique user to the accumulator.
const reviewer = review?.user;
const reviewerUsername = reviewer?.login;
const haveWeSeenThisReviewerAlready = usernames[reviewerUsername];
if (!haveWeSeenThisReviewerAlready) {
usernames[reviewerUsername] = {
...getJiraAuthor(reviewer),
login: reviewerUsername,
approvalStatus: review.state === STATE_APPROVED ? STATE_APPROVED : STATE_UNAPPROVED
};
acc.push(usernames[reviewerUsername]);
} else {
usernames[reviewerUsername].approvalStatus = review.state === STATE_APPROVED ? STATE_APPROVED : STATE_UNAPPROVED;
}
// Returns the reviews' array with unique users
return acc;
}, []);
// Get GitHub user email, so it can be matched to an AAID
return Promise.all(reviewsReduced.map(async reviewer => {
const mappedReviewer = {
...omit(reviewer, "login")
};
const isDeletedUser = !reviewer.login;
if (!isDeletedUser) {
const gitHubUser = await getGithubUser(gitHubInstallationClient, reviewer.login);
mappedReviewer.email = gitHubUser?.email || `${reviewer.login}@noreply.user.github.com`;
}
return mappedReviewer;
}));
};
export const extractIssueKeysFromPrRest = (pullRequest: Octokit.PullsListResponseItem) => {
const { title: prTitle, head, body } = pullRequest;
return jiraIssueKeyParser(`${prTitle}\n${head?.ref}\n${body}`);
};
export const extractIssueKeysFromPr = (pullRequest: pullRequestNode) => {
const { title, headRef, body } = pullRequest;
return jiraIssueKeyParser(`${title}\n${headRef?.name}\n${body}`);
};
export const transformPullRequestRest = async (
gitHubInstallationClient: GitHubInstallationClient,
pullRequest: Octokit.PullsGetResponse,
reviews?: Array<{ state?: string, user: Octokit.PullsUpdateResponseRequestedReviewersItem }>,
log?: Logger
) =>
{
const {
id,
user,
comments,
base,
number: pullRequestNumber,
updated_at,
head,
state,
merged_at,
title,
html_url,
draft
} = pullRequest;
const issueKeys = extractIssueKeysFromPrRest(pullRequest);
// This is the same thing we do in sync, concatenating these values
if (isEmpty(issueKeys) || !head?.repo) {
log?.info({
pullRequestNumber: pullRequestNumber,
pullRequestId: id
}, "Ignoring pullrequest since it has no issue keys or repo");
return undefined;
}
const branches = await getBranches(gitHubInstallationClient, pullRequest, issueKeys);
// Need to get full name from a REST call as `pullRequest.user.login` doesn't have it
const author = getJiraAuthor(user, await getGithubUser(gitHubInstallationClient, user?.login));
const reviewers = await mapReviewsRest(reviews, gitHubInstallationClient);
const status = mapStatus(state, merged_at, draft);
return {
...transformRepositoryDevInfoBulk(base.repo, gitHubInstallationClient.baseUrl),
branches,
pullRequests: [
{
author,
commentCount: comments || 0,
destinationBranch: base.ref || "",
destinationBranchUrl: `${base.repo.html_url}/tree/${base.ref}`,
displayId: `#${pullRequestNumber}`,
id: pullRequestNumber,
issueKeys,
lastUpdate: updated_at,
reviewers: reviewers,
sourceBranch: head.ref || "",
sourceBranchUrl: `${head.repo.html_url}/tree/${head.ref}`,
status,
timestamp: updated_at,
title: title,
url: html_url,
updateSequenceId: Date.now()
}
]
};
};
// Do not send the branch on the payload when the Pull Request Merged event is called.
// Reason: If "Automatically delete head branches" is enabled, the branch deleted and PR merged events might be sent out “at the same time” and received out of order, which causes the branch being created again.
const getBranches = async (gitHubInstallationClient: GitHubInstallationClient, pullRequest: Octokit.PullsGetResponse, issueKeys: string[]) => {
if (mapStatus(pullRequest.state, pullRequest.merged_at, pullRequest.draft) === "MERGED") {
return [];
}
return [
{
createPullRequestUrl: generateCreatePullRequestUrl(pullRequest?.head?.repo?.html_url, pullRequest?.head?.ref, issueKeys),
lastCommit: {
// Need to get full name from a REST call as `pullRequest.head.user` doesn't have it
author: getJiraAuthor(pullRequest.head?.user, await getGithubUser(gitHubInstallationClient, pullRequest.head?.user?.login)),
authorTimestamp: pullRequest.updated_at,
displayId: pullRequest?.head?.sha?.substring(0, 6),
fileCount: 0,
hash: pullRequest.head.sha,
id: pullRequest.head.sha,
issueKeys,
message: "n/a",
updateSequenceId: Date.now(),
url: `${pullRequest.head.repo.html_url}/commit/${pullRequest.head.sha}`
},
id: getJiraId(pullRequest.head.ref),
issueKeys,
name: pullRequest.head.ref,
url: `${pullRequest.head.repo.html_url}/tree/${pullRequest.head.ref}`,
updateSequenceId: Date.now()
}
];
};
export const transformPullRequest = (_jiraHost: string, pullRequest: pullRequestNode, log: Logger) => {
const issueKeys = extractIssueKeysFromPr(pullRequest);
if (isEmpty(issueKeys) || !pullRequest.headRef?.repository) {
log?.info({
pullRequestNumber: pullRequest.number,
pullRequestId: pullRequest.id
}, "Ignoring pullrequest since it has no issue keys or repo");
return undefined;
}
const status = mapStatus(pullRequest.state, pullRequest.mergedAt, pullRequest.draft);
try {
return {
author: getJiraAuthor(pullRequest.author),
commentCount: pullRequest.comments.totalCount || 0,
destinationBranch: pullRequest.baseRef?.name || "",
destinationBranchUrl: `https://github.com/${pullRequest.baseRef?.repository?.owner?.login}/${pullRequest.baseRef?.repository?.name}/tree/${pullRequest.baseRef?.name}`,
displayId: `#${pullRequest.number}`,
id: pullRequest.number,
issueKeys,
lastUpdate: pullRequest.updatedAt,
reviewers: mapReviews(pullRequest.reviews?.nodes, pullRequest.reviewRequests?.nodes),
sourceBranch: pullRequest.headRef?.name || "",
sourceBranchUrl: `https://github.com/${pullRequest.headRef?.repository?.owner?.login}/${pullRequest.headRef?.repository?.name}/tree/${pullRequest.headRef?.name}`,
status: status,
timestamp: pullRequest.updatedAt,
title: pullRequest.title,
url: pullRequest.url,
updateSequenceId: Date.now()
};
} catch (err) {
throw new Error();
}
};
const mapReviews = (reviews: pullRequestNode["reviews"]["nodes"] = [], reviewRequests: pullRequestNode["reviewRequests"]["nodes"] = []): JiraReview[] => {
const allReviews = [...reviewRequests || [], ...reviews || []] as pullRequestNode["reviews"]["nodes"];
const usernames: Record<string, any> = {};
// The reduce function goes through all the reviews and creates an array of unique users
// (so users' avatars won't be duplicated on the dev panel in Jira)
// and it considers 'APPROVED' as the main approval status for that user.
const reviewsReduced: JiraReviewer[] = allReviews.reduce((acc: JiraReviewer[], review) => {
// Adds user to the usernames object if user is not yet added, then it adds that unique user to the accumulator.
const reviewer = review?.author;
const reviewerUsername = reviewer?.login;
const haveWeSeenThisReviewerAlready = usernames[reviewerUsername];
if (!haveWeSeenThisReviewerAlready) {
usernames[reviewerUsername] = {
...getJiraAuthor(reviewer),
login: reviewerUsername,
approvalStatus: review.state === STATE_APPROVED ? STATE_APPROVED : STATE_UNAPPROVED
};
acc.push(usernames[reviewerUsername]);
} else {
usernames[reviewerUsername].approvalStatus = review.state === STATE_APPROVED ? STATE_APPROVED : STATE_UNAPPROVED;
}
// Returns the reviews' array with unique users
return acc;
}, []);
// Get GitHub user email, so it can be matched to an AAID
return reviewsReduced.map(reviewer => {
const mappedReviewer = {
...omit(reviewer, "login")
};
const isDeletedUser = !reviewer.login;
if (!isDeletedUser) {
const gitHubUser = getJiraAuthor(reviewer);
mappedReviewer.email = gitHubUser?.email || `${reviewer.login}@noreply.user.github.com`;
}
return mappedReviewer;
});
};