forked from microsoft/vscode-pull-request-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpullRequestModel.ts
More file actions
820 lines (708 loc) · 25 KB
/
pullRequestModel.ts
File metadata and controls
820 lines (708 loc) · 25 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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import * as OctokitTypes from '@octokit/types';
import { GitHubRef } from '../common/githubRef';
import { Remote } from '../common/remote';
import { GitHubRepository } from './githubRepository';
import { PullRequest, GithubItemStateEnum, ISuggestedReviewer, PullRequestChecks, IAccount, IRawFileChange, PullRequestMergeability } from './interface';
import { IssueModel } from './issueModel';
import { isReviewEvent, ReviewEvent as CommonReviewEvent, TimelineEvent } from '../common/timelineEvent';
import { ReviewEvent } from './interface';
import { convertPullRequestsGetCommentsResponseItemToComment, convertRESTPullRequestToRawPullRequest, convertRESTReviewEvent, convertRESTUserToAccount, parseGraphQLComment, parseGraphQLReviewEvent, parseGraphQLTimelineEvents, parseMergeability } from './utils';
import { AddCommentResponse, DeleteReviewResponse, EditCommentResponse, GetChecksResponse, isCheckRun, MarkPullRequestReadyForReviewResponse, PendingReviewIdResponse, PullRequestCommentsResponse, PullRequestResponse, StartReviewResponse, SubmitReviewResponse, TimelineEventsResponse } from './graphql';
import Logger from '../common/logger';
import { IComment } from '../common/comment';
import { formatError } from '../common/utils';
import { ITelemetry } from '../common/telemetry';
interface IPullRequestModel {
head: GitHubRef | null;
}
export interface IResolvedPullRequestModel extends IPullRequestModel {
head: GitHubRef;
}
interface NewCommentPosition {
path: string;
position: number;
}
interface ReplyCommentPosition {
inReplyTo: string;
}
export class PullRequestModel extends IssueModel implements IPullRequestModel {
static ID = 'PullRequestModel';
public isDraft?: boolean;
public item: PullRequest;
public localBranchName?: string;
public mergeBase?: string;
public suggestedReviewers?: ISuggestedReviewer[];
private _hasPendingReview: boolean = false;
private _onDidChangePendingReviewState: vscode.EventEmitter<boolean> = new vscode.EventEmitter<boolean>();
public onDidChangePendingReviewState = this._onDidChangePendingReviewState.event;
// Whether the pull request is currently checked out locally
public isActive: boolean;
_telemetry: ITelemetry;
constructor(telemetry: ITelemetry, githubRepository: GitHubRepository, remote: Remote, item: PullRequest, isActive?: boolean) {
super(githubRepository, remote, item);
this._telemetry = telemetry;
this.isActive = !!isActive;
}
public get isMerged(): boolean {
return this.state === GithubItemStateEnum.Merged;
}
public get hasPendingReview(): boolean {
return this._hasPendingReview;
}
public set hasPendingReview(hasPendingReview: boolean) {
if (this._hasPendingReview !== hasPendingReview) {
this._hasPendingReview = hasPendingReview;
this._onDidChangePendingReviewState.fire(this._hasPendingReview);
}
}
public head: GitHubRef | null;
public base: GitHubRef;
protected updateState(state: string) {
if (state.toLowerCase() === 'open') {
this.state = GithubItemStateEnum.Open;
} else {
this.state = this.item.merged ? GithubItemStateEnum.Merged : GithubItemStateEnum.Closed;
}
}
update(item: PullRequest): void {
super.update(item);
this.isDraft = item.isDraft;
this.suggestedReviewers = item.suggestedReviewers;
if (item.head) {
this.head = new GitHubRef(item.head.ref, item.head.label, item.head.sha, item.head.repo.cloneUrl);
}
if (item.base) {
this.base = new GitHubRef(item.base.ref, item.base!.label, item.base!.sha, item.base!.repo.cloneUrl);
}
}
/**
* Validate if the pull request has a valid HEAD.
* Use only when the method can fail silently, otherwise use `validatePullRequestModel`
*/
isResolved(): this is IResolvedPullRequestModel {
return !!this.head;
}
/**
* Validate if the pull request has a valid HEAD. Show a warning message to users when the pull request is invalid.
* @param message Human readable action execution failure message.
*/
validatePullRequestModel(message?: string): this is IResolvedPullRequestModel {
if (!!this.head) {
return true;
}
const reason = `There is no upstream branch for Pull Request #${this.number}. View it on GitHub for more details`;
if (message) {
message += `: ${reason}`;
} else {
message = reason;
}
vscode.window.showWarningMessage(message, 'Open in GitHub').then(action => {
if (action && action === 'Open in GitHub') {
vscode.commands.executeCommand('vscode.open', vscode.Uri.parse(this.html_url));
}
});
return false;
}
/**
* Approve the pull request.
* @param message Optional approval comment text.
*/
async approve(message?: string): Promise<CommonReviewEvent> {
const action: Promise<CommonReviewEvent> = await this.getPendingReviewId()
? this.submitReview(ReviewEvent.Approve, message)
: this.createReview(ReviewEvent.Approve, message);
return action.then(x => {
/* __GDPR__
"pr.approve" : {}
*/
this._telemetry.sendTelemetryEvent('pr.approve');
return x;
});
}
/**
* Request changes on the pull request.
* @param message Optional comment text to leave with the review.
*/
async requestChanges(message?: string): Promise<CommonReviewEvent> {
const action: Promise<CommonReviewEvent> = await this.getPendingReviewId()
? this.submitReview(ReviewEvent.RequestChanges, message)
: this.createReview(ReviewEvent.RequestChanges, message);
return action
.then(x => {
/* __GDPR__
"pr.requestChanges" : {}
*/
this._telemetry.sendTelemetryEvent('pr.requestChanges');
return x;
});
}
/**
* Close the pull request.
*/
async close(): Promise<PullRequest> {
const { octokit, remote } = await this.githubRepository.ensure();
const ret = await octokit.pulls.update({
owner: remote.owner,
repo: remote.repositoryName,
pull_number: this.number,
state: 'closed'
});
/* __GDPR__
"pr.close" : {}
*/
this._telemetry.sendTelemetryEvent('pr.close');
return convertRESTPullRequestToRawPullRequest(ret.data, this.githubRepository);
}
/**
* Create a new review.
* @param event The type of review to create, an approval, request for changes, or comment.
* @param message The summary comment text.
*/
private async createReview(event: ReviewEvent, message?: string): Promise<CommonReviewEvent> {
const { octokit, remote } = await this.githubRepository.ensure();
const { data } = await octokit.pulls.createReview({
owner: remote.owner,
repo: remote.repositoryName,
pull_number: this.number,
event: event,
body: message,
});
return convertRESTReviewEvent(data, this.githubRepository);
}
/**
* Submit an existing review.
* @param event The type of review to create, an approval, request for changes, or comment.
* @param body The summary comment text.
*/
async submitReview(event?: ReviewEvent, body?: string): Promise<CommonReviewEvent> {
const pendingReviewId = await this.getPendingReviewId();
const { mutate, schema } = await this.githubRepository.ensure();
if (pendingReviewId) {
const { data } = await mutate<SubmitReviewResponse>({
mutation: schema.SubmitReview,
variables: {
id: pendingReviewId,
event: event || ReviewEvent.Comment,
body
}
});
this.hasPendingReview = false;
await this.updateDraftModeContext();
return parseGraphQLReviewEvent(data!.submitPullRequestReview.pullRequestReview, this.githubRepository);
} else {
throw new Error(`Submitting review failed, no pending review for current pull request: ${this.number}.`);
}
}
/**
* Query to see if there is an existing review.
*/
async getPendingReviewId(): Promise<string | undefined> {
const { query, schema } = await this.githubRepository.ensure();
const currentUser = await this.githubRepository.getAuthenticatedUser();
try {
const { data } = await query<PendingReviewIdResponse>({
query: schema.GetPendingReviewId,
variables: {
pullRequestId: this.item.graphNodeId,
author: currentUser
}
});
return data.node.reviews.nodes[0].id;
} catch (error) {
return;
}
}
/**
* Delete an existing in progress review.
*/
async deleteReview(): Promise<{ deletedReviewId: number, deletedReviewComments: IComment[] }> {
const pendingReviewId = await this.getPendingReviewId();
const { mutate, schema } = await this.githubRepository.ensure();
const { data } = await mutate<DeleteReviewResponse>({
mutation: schema.DeleteReview,
variables: {
input: { pullRequestReviewId: pendingReviewId }
}
});
const { comments, databaseId } = data!.deletePullRequestReview.pullRequestReview;
this.hasPendingReview = false;
await this.updateDraftModeContext();
return {
deletedReviewId: databaseId,
deletedReviewComments: comments.nodes.map(parseGraphQLComment)
};
}
/**
* Start a new review.
* @param initialComment The comment text and position information to begin the review with
*/
async startReview(initialComment: { body: string, path: string, position: number }): Promise<IComment> {
const { mutate, schema } = await this.githubRepository.ensure();
const { data } = await mutate<StartReviewResponse>({
mutation: schema.StartReview,
variables: {
input: {
body: '',
pullRequestId: this.item.graphNodeId,
comments: initialComment
}
}
});
if (!data) {
throw new Error('Failed to start review');
}
this.hasPendingReview = true;
await this.updateDraftModeContext();
return parseGraphQLComment(data.addPullRequestReview.pullRequestReview.comments.nodes[0]);
}
/**
* Create a new review comment. Adds to an existing review if there is one or creates a single review comment.
* @param body The text of the new comment
* @param commentPath The file path where the comment should be made
* @param position The line number within the file to add the comment
*/
async createReviewComment(body: string, commentPath: string, position: number): Promise<IComment | undefined> {
if (!this.validatePullRequestModel('Creating comment failed')) {
return;
}
const pendingReviewId = await this.getPendingReviewId();
if (pendingReviewId) {
return this.addCommentToPendingReview(pendingReviewId, body, { path: commentPath, position });
}
const githubRepository = this.githubRepository;
const { octokit, remote } = await githubRepository.ensure();
try {
const ret = await octokit.pulls.createReviewComment({
owner: remote.owner,
repo: remote.repositoryName,
pull_number: this.number,
body: body,
commit_id: this.head.sha,
path: commentPath,
position: position
});
return this.addCommentPermissions(convertPullRequestsGetCommentsResponseItemToComment(ret.data, githubRepository));
} catch (e) {
throw formatError(e);
}
}
/**
* Creates a review comment in reply to an existing review comment.
* @param body The text of the new comment
* @param reply_to The comment to reply to
*/
async createReviewCommentReply(body: string, reply_to: IComment): Promise<IComment | undefined> {
const pendingReviewId = await this.getPendingReviewId();
if (pendingReviewId) {
return this.addCommentToPendingReview(pendingReviewId, body, { inReplyTo: reply_to.graphNodeId });
}
const { octokit, remote } = await this.githubRepository.ensure();
try {
const ret = await octokit.pulls.createReplyForReviewComment({
owner: remote.owner,
repo: remote.repositoryName,
pull_number: this.number,
body: body,
comment_id: Number(reply_to.id)
});
return this.addCommentPermissions(convertPullRequestsGetCommentsResponseItemToComment(ret.data, this.githubRepository));
} catch (e) {
throw formatError(e);
}
}
private async addCommentToPendingReview(reviewId: string, body: string, position: NewCommentPosition | ReplyCommentPosition): Promise<IComment> {
const { mutate, schema } = await this.githubRepository.ensure();
const { data } = await mutate<AddCommentResponse>({
mutation: schema.AddComment,
variables: {
input: {
pullRequestReviewId: reviewId,
body,
...position
}
}
});
const { comment } = data!.addPullRequestReviewComment;
return parseGraphQLComment(comment);
}
/**
* Check whether there is an existing pending review and update the context key to control what comment actions are shown.
*/
async validateDraftMode(): Promise<boolean> {
const inDraftMode = !!await this.getPendingReviewId();
if (inDraftMode !== this.hasPendingReview) {
this.hasPendingReview = inDraftMode;
}
await this.updateDraftModeContext();
return inDraftMode;
}
private async updateDraftModeContext() {
if (this.isActive) {
await vscode.commands.executeCommand('setContext', 'reviewInDraftMode', this.hasPendingReview);
}
}
private addCommentPermissions(rawComment: IComment): IComment {
const isCurrentUser = this.githubRepository.isCurrentUser(rawComment.user!.login);
const notOutdated = rawComment.position !== null;
rawComment.canEdit = isCurrentUser && notOutdated;
rawComment.canDelete = isCurrentUser && notOutdated;
return rawComment;
}
/**
* Edit an existing review comment.
* @param comment The comment to edit
* @param text The new comment text
*/
async editReviewComment(comment: IComment, text: string): Promise<IComment> {
const { mutate, schema } = await this.githubRepository.ensure();
const { data } = await mutate<EditCommentResponse>({
mutation: schema.EditComment,
variables: {
input: {
pullRequestReviewCommentId: comment.graphNodeId,
body: text
}
}
});
return parseGraphQLComment(data!.updatePullRequestReviewComment.pullRequestReviewComment);
}
/**
* Deletes a review comment.
* @param commentId The comment id to delete
*/
async deleteReviewComment(commentId: string): Promise<void> {
try {
const { octokit, remote } = await this.githubRepository.ensure();
await octokit.pulls.deleteReviewComment({
owner: remote.owner,
repo: remote.repositoryName,
comment_id: Number(commentId)
});
} catch (e) {
throw new Error(formatError(e));
}
}
/**
* Get existing requests to review.
*/
async getReviewRequests(): Promise<IAccount[]> {
const githubRepository = this.githubRepository;
const { remote, octokit } = await githubRepository.ensure();
const result = await octokit.pulls.listRequestedReviewers({
owner: remote.owner,
repo: remote.repositoryName,
pull_number: this.number
});
return result.data.users.map((user: any) => convertRESTUserToAccount(user, githubRepository));
}
/**
* Add reviewers to a pull request
* @param reviewers A list of GitHub logins
*/
async requestReview(reviewers: string[]): Promise<void> {
const { octokit, remote } = await this.githubRepository.ensure();
await octokit.pulls.requestReviewers({
owner: remote.owner,
repo: remote.repositoryName,
pull_number: this.number,
reviewers
});
}
/**
* Remove a review request that has not yet been completed
* @param reviewer A GitHub Login
*/
async deleteReviewRequest(reviewer: string): Promise<void> {
const { octokit, remote } = await this.githubRepository.ensure();
await octokit.pulls.removeRequestedReviewers({
owner: remote.owner,
repo: remote.repositoryName,
pull_number: this.number,
reviewers: [reviewer]
});
}
/**
* Get all review comments.
*/
async getReviewComments(): Promise<IComment[]> {
const { remote, query, schema } = await this.githubRepository.ensure();
try {
const { data } = await query<PullRequestCommentsResponse>({
query: schema.PullRequestComments,
variables: {
owner: remote.owner,
name: remote.repositoryName,
number: this.number,
}
});
const comments = data.repository.pullRequest.reviews.nodes
.map((node: any) => node.comments.nodes.map((comment: any) => parseGraphQLComment(comment), remote))
.reduce((prev: any, curr: any) => prev.concat(curr), [])
.sort((a: IComment, b: IComment) => { return a.createdAt > b.createdAt ? 1 : -1; });
return comments;
} catch (e) {
Logger.appendLine(`Failed to get pull request review comments: ${e}`);
return [];
}
}
/**
* Get a list of the commits within a pull request.
*/
async getCommits(): Promise<OctokitTypes.PullsListCommitsResponseData> {
try {
Logger.debug(`Fetch commits of PR #${this.number} - enter`, PullRequestModel.ID);
const { remote, octokit } = await this.githubRepository.ensure();
const commitData = await octokit.pulls.listCommits({
pull_number: this.number,
owner: remote.owner,
repo: remote.repositoryName
});
Logger.debug(`Fetch commits of PR #${this.number} - done`, PullRequestModel.ID);
return commitData.data;
} catch (e) {
vscode.window.showErrorMessage(`Fetching commits failed: ${formatError(e)}`);
return [];
}
}
/**
* Get all changed files within a commit
* @param commit The commit
*/
async getCommitChangedFiles(commit: OctokitTypes.PullsListCommitsResponseData[0]): Promise<OctokitTypes.ReposGetCommitResponseData['files']> {
try {
Logger.debug(`Fetch file changes of commit ${commit.sha} in PR #${this.number} - enter`, PullRequestModel.ID);
const { octokit, remote } = await this.githubRepository.ensure();
const fullCommit = await octokit.repos.getCommit({
owner: remote.owner,
repo: remote.repositoryName,
ref: commit.sha
});
Logger.debug(`Fetch file changes of commit ${commit.sha} in PR #${this.number} - done`, PullRequestModel.ID);
return fullCommit.data.files.filter(file => !!file.patch);
} catch (e) {
vscode.window.showErrorMessage(`Fetching commit file changes failed: ${formatError(e)}`);
return [];
}
}
/**
* Gets file content for a file at the specified commit
* @param filePath The file path
* @param commit The commit
*/
async getFile(filePath: string, commit: string) {
const { octokit, remote } = await this.githubRepository.ensure();
const fileContent = await octokit.repos.getContent({
owner: remote.owner,
repo: remote.repositoryName,
path: filePath,
ref: commit
});
if (Array.isArray(fileContent.data)) {
throw new Error(`Unexpected array response when getting file ${filePath}`);
}
const contents = fileContent.data.content ?? '';
const buff = new Buffer(contents, <any>fileContent.data.encoding);
return buff.toString();
}
/**
* Get the timeline events of a pull request, including comments, reviews, commits, merges, deletes, and assigns.
*/
async getTimelineEvents(): Promise<TimelineEvent[]> {
Logger.debug(`Fetch timeline events of PR #${this.number} - enter`, PullRequestModel.ID);
const { query, remote, schema } = await this.githubRepository.ensure();
try {
const { data } = await query<TimelineEventsResponse>({
query: schema.TimelineEvents,
variables: {
owner: remote.owner,
name: remote.repositoryName,
number: this.number
}
});
const ret = data.repository.pullRequest.timelineItems.nodes;
const events = parseGraphQLTimelineEvents(ret, this.githubRepository);
await this.addReviewTimelineEventComments(events);
return events;
} catch (e) {
console.log(e);
return [];
}
}
private async addReviewTimelineEventComments(events: TimelineEvent[]): Promise<void> {
interface CommentNode extends IComment {
childComments?: CommentNode[];
}
const reviewEvents = events.filter(isReviewEvent);
const reviewComments = await this.getReviewComments() as CommentNode[];
const reviewEventsById = reviewEvents.reduce((index, evt) => {
index[evt.id] = evt;
evt.comments = [];
return index;
}, {} as { [key: number]: CommonReviewEvent });
const commentsById = reviewComments.reduce((index, evt) => {
index[evt.id] = evt;
return index;
}, {} as { [key: number]: CommentNode });
const roots: CommentNode[] = [];
let i = reviewComments.length; while (i-- > 0) {
const c: CommentNode = reviewComments[i];
if (!c.inReplyToId) {
roots.unshift(c);
continue;
}
const parent = commentsById[c.inReplyToId];
parent.childComments = parent.childComments || [];
parent.childComments = [c, ...(c.childComments || []), ...parent.childComments];
}
roots.forEach(c => {
const review = reviewEventsById[c.pullRequestReviewId!];
if (review) {
review.comments = review.comments.concat(c).concat(c.childComments || []);
}
});
const pendingReview = reviewEvents.filter(r => r.state.toLowerCase() === 'pending')[0];
if (pendingReview) {
// Ensures that pending comments made in reply to other reviews are included for the pending review
pendingReview.comments = reviewComments.filter(c => c.isDraft);
}
}
/**
* Get the status checks of the pull request, those for the last commit.
*/
async getStatusChecks(): Promise<PullRequestChecks> {
const { query, remote, schema } = await this.githubRepository.ensure();
const result = await query<GetChecksResponse>({
query: schema.GetChecks,
variables: {
owner: remote.owner,
name: remote.repositoryName,
number: this.number
}
});
// We always fetch the status checks for only the last commit, so there should only be one node present
const statusCheckRollup = result.data.repository.pullRequest.commits.nodes[0].commit.statusCheckRollup;
if (!statusCheckRollup) {
return {
state: 'pending',
statuses: []
};
}
return {
state: statusCheckRollup.state.toLowerCase(),
statuses: statusCheckRollup.contexts.nodes.map(context => {
if (isCheckRun(context)) {
return {
id: context.id,
url: context.checkSuite.app?.url,
avatar_url: context.checkSuite.app?.logoUrl,
state: context.conclusion?.toLowerCase() || 'pending',
description: context.title,
context: context.name,
target_url: context.detailsUrl
};
} else {
return {
id: context.id,
url: context.targetUrl,
avatar_url: context.avatarUrl,
state: context.state?.toLowerCase(),
description: context.description,
context: context.context,
target_url: context.targetUrl
};
}
})
};
}
/**
* List the changed files in a pull request.
*/
async getFileChangesInfo(): Promise<IRawFileChange[]> {
Logger.debug(`Fetch file changes, base, head and merge base of PR #${this.number} - enter`, PullRequestModel.ID);
const githubRepository = this.githubRepository;
const { octokit, remote } = await githubRepository.ensure();
if (!this.base) {
const info = await octokit.pulls.get({
owner: remote.owner,
repo: remote.repositoryName,
pull_number: this.number
});
this.update(convertRESTPullRequestToRawPullRequest(info.data, githubRepository));
}
if (this.item.merged) {
const repsonse = await octokit.pulls.listFiles({
repo: remote.repositoryName,
owner: remote.owner,
pull_number: this.number
});
// Use the original base to compare against for merged PRs
this.mergeBase = this.base.sha;
return repsonse.data;
}
const { data } = await octokit.repos.compareCommits({
repo: remote.repositoryName,
owner: remote.owner,
base: `${this.base.repositoryCloneUrl.owner}:${this.base.ref}`,
head: `${this.head!.repositoryCloneUrl.owner}:${this.head!.ref}`,
});
this.mergeBase = data.merge_base_commit.sha;
Logger.debug(`Fetch file changes and merge base of PR #${this.number} - done`, PullRequestModel.ID);
return data.files;
}
/**
* Get the current mergability of the pull request.
*/
async getMergability(): Promise<PullRequestMergeability> {
try {
Logger.debug(`Fetch pull request mergeability ${this.number} - enter`, PullRequestModel.ID);
const { query, remote, schema } = await this.githubRepository.ensure();
const { data } = await query<PullRequestResponse>({
query: schema.PullRequestMergeability,
variables: {
owner: remote.owner,
name: remote.repositoryName,
number: this.number
}
});
Logger.debug(`Fetch pull request mergeability ${this.number} - done`, PullRequestModel.ID);
return parseMergeability(data.repository.pullRequest.mergeable);
} catch (e) {
Logger.appendLine(`PullRequestModel> Unable to fetch PR Mergeability: ${e}`);
return PullRequestMergeability.Unknown;
}
}
/**
* Set a draft pull request as ready to be reviewed.
*/
async setReadyForReview(): Promise<any> {
try {
const { mutate, schema } = await this.githubRepository.ensure();
const { data } = await mutate<MarkPullRequestReadyForReviewResponse>({
mutation: schema.ReadyForReview,
variables: {
input: {
pullRequestId: this.graphNodeId,
}
}
});
/* __GDPR__
"pr.readyForReview.success" : {}
*/
this._telemetry.sendTelemetryEvent('pr.readyForReview.success');
return data!.markPullRequestReadyForReview.pullRequest.isDraft;
} catch (e) {
/* __GDPR__
"pr.readyForReview.failure" : {
"message" : { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" }
}
*/
this._telemetry.sendTelemetryErrorEvent('pr.readyForReview.failure', { message: formatError(e) });
throw e;
}
}
}