-
Notifications
You must be signed in to change notification settings - Fork 731
Expand file tree
/
Copy pathissueModel.ts
More file actions
417 lines (363 loc) · 11.9 KB
/
issueModel.ts
File metadata and controls
417 lines (363 loc) · 11.9 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
/*---------------------------------------------------------------------------------------------
* 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 { IComment } from '../common/comment';
import Logger from '../common/logger';
import { Remote } from '../common/remote';
import { TimelineEvent } from '../common/timelineEvent';
import { formatError } from '../common/utils';
import { GitHubRepository } from './githubRepository';
import {
AddIssueCommentResponse,
AddPullRequestToProjectResponse,
EditIssueCommentResponse,
TimelineEventsResponse,
UpdateIssueResponse,
} from './graphql';
import { GithubItemStateEnum, IAccount, IIssueEditData, IMilestone, IProject, IProjectItem, Issue } from './interface';
import { parseGraphQlIssueComment, parseGraphQLTimelineEvents, parsePullRequestState } from './utils';
export class IssueModel<TItem extends Issue = Issue> {
static ID = 'IssueModel';
public id: number;
public graphNodeId: string;
public number: number;
public title: string;
public titleHTML: string;
public html_url: string;
public state: GithubItemStateEnum = GithubItemStateEnum.Open;
public author: IAccount;
public assignees?: IAccount[];
public createdAt: string;
public updatedAt: string;
public milestone?: IMilestone;
public readonly githubRepository: GitHubRepository;
public readonly remote: Remote;
public item: TItem;
public bodyHTML?: string;
private _onDidInvalidate = new vscode.EventEmitter<void>();
public onDidInvalidate = this._onDidInvalidate.event;
constructor(githubRepository: GitHubRepository, remote: Remote, item: TItem, skipUpdate: boolean = false) {
this.githubRepository = githubRepository;
this.remote = remote;
this.item = item;
if (!skipUpdate) {
this.update(item);
}
}
public invalidate() {
// Something about the PR data is stale
this._onDidInvalidate.fire();
}
public get isOpen(): boolean {
return this.state === GithubItemStateEnum.Open;
}
public get isClosed(): boolean {
return this.state === GithubItemStateEnum.Closed;
}
public get isMerged(): boolean {
return this.state === GithubItemStateEnum.Merged;
}
public get userAvatar(): string | undefined {
if (this.item) {
return this.item.user.avatarUrl;
}
return undefined;
}
public get userAvatarUri(): vscode.Uri | undefined {
if (this.item) {
const key = this.userAvatar;
if (key) {
const uri = vscode.Uri.parse(`${key}&s=${64}`);
// hack, to ensure queries are not wrongly encoded.
const originalToStringFn = uri.toString;
uri.toString = function (_skipEncoding?: boolean | undefined) {
return originalToStringFn.call(uri, true);
};
return uri;
}
}
return undefined;
}
public get body(): string {
if (this.item) {
return this.item.body;
}
return '';
}
protected updateState(state: string) {
this.state = parsePullRequestState(state);
}
update(issue: TItem): void {
this.id = issue.id;
this.graphNodeId = issue.graphNodeId;
this.number = issue.number;
this.title = issue.title;
if (issue.titleHTML) {
this.titleHTML = issue.titleHTML;
}
if (!this.bodyHTML || (issue.body !== this.body)) {
this.bodyHTML = issue.bodyHTML;
}
this.html_url = issue.url;
this.author = issue.user;
this.milestone = issue.milestone;
this.createdAt = issue.createdAt;
this.updatedAt = issue.updatedAt;
this.updateState(issue.state);
if (issue.assignees) {
this.assignees = issue.assignees;
}
this.item = issue;
}
equals(other: IssueModel<TItem> | undefined): boolean {
if (!other) {
return false;
}
if (this.number !== other.number) {
return false;
}
if (this.html_url !== other.html_url) {
return false;
}
return true;
}
protected updateIssueInput(id: string): Object {
return {
id
};
}
protected updateIssueSchema(schema: any): any {
return schema.UpdateIssue;
}
async edit(toEdit: IIssueEditData): Promise<{ body: string; bodyHTML: string; title: string; titleHTML: string }> {
try {
const { mutate, schema } = await this.githubRepository.ensure();
const { data } = await mutate<UpdateIssueResponse>({
mutation: this.updateIssueSchema(schema),
variables: {
input: {
...this.updateIssueInput(this.graphNodeId),
body: toEdit.body,
title: toEdit.title,
},
},
});
if (data?.updateIssue.issue) {
this.item.body = data.updateIssue.issue.body;
this.bodyHTML = data.updateIssue.issue.bodyHTML;
this.title = data.updateIssue.issue.title;
this.titleHTML = data.updateIssue.issue.titleHTML;
this.invalidate();
}
return data!.updateIssue.issue;
} catch (e) {
throw new Error(formatError(e));
}
}
canEdit(): Promise<boolean> {
const username = this.author && this.author.login;
return this.githubRepository.isCurrentUser(username);
}
async createIssueComment(text: string): Promise<IComment> {
const { mutate, schema } = await this.githubRepository.ensure();
const { data } = await mutate<AddIssueCommentResponse>({
mutation: schema.AddIssueComment,
variables: {
input: {
subjectId: this.graphNodeId,
body: text,
},
},
});
return parseGraphQlIssueComment(data!.addComment.commentEdge.node, this.githubRepository);
}
async editIssueComment(comment: IComment, text: string): Promise<IComment> {
try {
const { mutate, schema } = await this.githubRepository.ensure();
const { data } = await mutate<EditIssueCommentResponse>({
mutation: schema.EditIssueComment,
variables: {
input: {
id: comment.graphNodeId,
body: text,
},
},
});
return parseGraphQlIssueComment(data!.updateIssueComment.issueComment, this.githubRepository);
} catch (e) {
throw new Error(formatError(e));
}
}
async deleteIssueComment(commentId: string): Promise<void> {
try {
const { octokit, remote } = await this.githubRepository.ensure();
await octokit.call(octokit.api.issues.deleteComment, {
owner: remote.owner,
repo: remote.repositoryName,
comment_id: Number(commentId),
});
} catch (e) {
throw new Error(formatError(e));
}
}
async setLabels(labels: string[]): Promise<void> {
const { octokit, remote } = await this.githubRepository.ensure();
try {
await octokit.call(octokit.api.issues.setLabels, {
owner: remote.owner,
repo: remote.repositoryName,
issue_number: this.number,
labels,
});
} catch (e) {
// We don't get a nice error message from the API when setting labels fails.
// Since adding labels isn't a critical part of the PR creation path it's safe to catch all errors that come from setting labels.
Logger.error(`Failed to add labels to PR #${this.number}`, IssueModel.ID);
vscode.window.showWarningMessage(vscode.l10n.t('Some, or all, labels could not be added to the pull request.'));
}
}
async removeLabel(label: string): Promise<void> {
const { octokit, remote } = await this.githubRepository.ensure();
await octokit.call(octokit.api.issues.removeLabel, {
owner: remote.owner,
repo: remote.repositoryName,
issue_number: this.number,
name: label,
});
}
public async removeProjects(projectItems: IProjectItem[]): Promise<void> {
const { mutate, schema } = await this.githubRepository.ensure();
try {
await Promise.all(projectItems.map(project =>
mutate<void>({
mutation: schema.RemovePullRequestFromProject,
variables: {
input: {
itemId: project.id,
projectId: project.project.id
},
},
})));
this.item.projectItems = this.item.projectItems?.filter(project => !projectItems.find(p => p.project.id === project.project.id));
} catch (err) {
Logger.error(err, IssueModel.ID);
}
}
private async addProjects(projects: IProject[]): Promise<void> {
const { mutate, schema } = await this.githubRepository.ensure();
try {
const itemIds = await Promise.all(projects.map(project =>
mutate<AddPullRequestToProjectResponse>({
mutation: schema.AddPullRequestToProject,
variables: {
input: {
contentId: this.item.graphNodeId,
projectId: project.id
},
},
})));
if (!this.item.projectItems) {
this.item.projectItems = [];
}
this.item.projectItems.push(...projects.map((project, index) => { return { project, id: itemIds[index].data!.addProjectV2ItemById.item.id }; }));
} catch (err) {
Logger.error(err, IssueModel.ID);
}
}
async updateProjects(projects: IProject[]): Promise<IProjectItem[] | undefined> {
const projectsToAdd: IProject[] = projects.filter(project => !this.item.projectItems?.find(p => p.project.id === project.id));
const projectsToRemove: IProjectItem[] = this.item.projectItems?.filter(project => !projects.find(p => p.id === project.project.id)) ?? [];
await this.removeProjects(projectsToRemove);
await this.addProjects(projectsToAdd);
return this.item.projectItems;
}
async getIssueTimelineEvents(): Promise<TimelineEvent[]> {
Logger.debug(`Fetch timeline events of issue #${this.number} - enter`, IssueModel.ID);
const githubRepository = this.githubRepository;
const { query, remote, schema } = await githubRepository.ensure();
try {
const { data } = await query<TimelineEventsResponse>({
query: schema.IssueTimelineEvents,
variables: {
owner: remote.owner,
name: remote.repositoryName,
number: this.number,
},
});
if (data.repository === null) {
Logger.error('Unexpected null repository when getting issue timeline events', IssueModel.ID);
return [];
}
const ret = data.repository.pullRequest.timelineItems.nodes;
const events = parseGraphQLTimelineEvents(ret, githubRepository);
return events;
} catch (e) {
console.log(e);
return [];
}
}
async updateMilestone(id: string): Promise<void> {
const { mutate, schema } = await this.githubRepository.ensure();
const finalId = id === 'null' ? null : id;
try {
await mutate<UpdateIssueResponse>({
mutation: this.updateIssueSchema(schema),
variables: {
input: {
...this.updateIssueInput(this.graphNodeId),
milestoneId: finalId,
},
},
});
} catch (err) {
Logger.error(err, IssueModel.ID);
}
}
async replaceAssignees(allAssignees: IAccount[]): Promise<void> {
Logger.debug(`Replace assignees of issue #${this.number} - enter`, IssueModel.ID);
const { mutate, schema } = await this.githubRepository.ensure();
try {
if (schema.ReplaceActorsForAssignable) {
const assigneeIds = allAssignees.map(assignee => assignee.id);
await mutate({
mutation: schema.ReplaceActorsForAssignable,
variables: {
input: {
actorIds: assigneeIds,
assignableId: this.graphNodeId
}
}
});
} else {
const addAssignees = allAssignees.map(assignee => assignee.login);
const removeAssignees = (this.assignees?.filter(currentAssignee => !allAssignees.find(newAssignee => newAssignee.login === currentAssignee.login)) ?? []).map(assignee => assignee.login);
await this.addAssignees(addAssignees);
await this.deleteAssignees(removeAssignees);
}
this.assignees = allAssignees;
} catch (e) {
Logger.error(e, IssueModel.ID);
}
Logger.debug(`Replace assignees of issue #${this.number} - done`, IssueModel.ID);
}
async addAssignees(assigneesToAdd: string[]): Promise<void> {
const { octokit, remote } = await this.githubRepository.ensure();
await octokit.call(octokit.api.issues.addAssignees, {
owner: remote.owner,
repo: remote.repositoryName,
issue_number: this.number,
assignees: assigneesToAdd,
});
}
private async deleteAssignees(assignees: string[]): Promise<void> {
const { octokit, remote } = await this.githubRepository.ensure();
await octokit.call(octokit.api.issues.removeAssignees, {
owner: remote.owner,
repo: remote.repositoryName,
issue_number: this.number,
assignees,
});
}
}