-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathgitlab.ts
389 lines (344 loc) · 12.7 KB
/
gitlab.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
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
import type { Range, Uri } from 'vscode';
import type { Autolink, AutolinkReference, DynamicAutolinkReference, MaybeEnrichedAutolink } from '../../autolinks';
import { GlyphChars } from '../../constants';
import type { GkProviderId } from '../../gk/models/repositoryIdentities';
import type { GitLabRepositoryDescriptor } from '../../plus/integrations/providers/gitlab';
import type { Brand, Unbrand } from '../../system/brand';
import { fromNow } from '../../system/date';
import { memoize } from '../../system/decorators/memoize';
import { encodeUrl } from '../../system/encoding';
import { escapeMarkdown, unescapeMarkdown } from '../../system/markdown';
import { equalsIgnoreCase } from '../../system/string';
import { getIssueOrPullRequestMarkdownIcon } from '../models/issue';
import { isSha } from '../models/reference';
import type { Repository } from '../models/repository';
import type { RemoteProviderId } from './remoteProvider';
import { RemoteProvider } from './remoteProvider';
const autolinkFullIssuesRegex = /\b([^/\s]+\/[^/\s]+?)(?:\\)?#([0-9]+)\b(?!]\()/g;
const autolinkFullMergeRequestsRegex = /\b([^/\s]+\/[^/\s]+?)(?:\\)?!([0-9]+)\b(?!]\()/g;
const fileRegex = /^\/([^/]+)\/([^/]+?)\/-\/blob(.+)$/i;
const rangeRegex = /^L(\d+)(?:-(\d+))?$/;
function isGitLabDotCom(domain: string): boolean {
return equalsIgnoreCase(domain, 'gitlab.com');
}
export class GitLabRemote extends RemoteProvider<GitLabRepositoryDescriptor> {
constructor(domain: string, path: string, protocol?: string, name?: string, custom: boolean = false) {
super(domain, path, protocol, name, custom);
}
get apiBaseUrl() {
return this.custom ? `${this.protocol}://${this.domain}/api` : `https://${this.domain}/api`;
}
private _autolinks: (AutolinkReference | DynamicAutolinkReference)[] | undefined;
override get autolinks(): (AutolinkReference | DynamicAutolinkReference)[] {
if (this._autolinks === undefined) {
this._autolinks = [
{
prefix: '#',
url: `${this.baseUrl}/-/issues/<num>`,
alphanumeric: false,
ignoreCase: false,
title: `Open Issue #<num> on ${this.name}`,
type: 'issue',
description: `${this.name} Issue #<num>`,
},
{
prefix: '!',
url: `${this.baseUrl}/-/merge_requests/<num>`,
alphanumeric: false,
ignoreCase: false,
title: `Open Merge Request !<num> on ${this.name}`,
type: 'pullrequest',
description: `${this.name} Merge Request !<num>`,
},
{
tokenize: (
text: string,
outputFormat: 'html' | 'markdown' | 'plaintext',
tokenMapping: Map<string, string>,
enrichedAutolinks?: Map<string, MaybeEnrichedAutolink>,
prs?: Set<string>,
footnotes?: Map<number, string>,
) => {
return outputFormat === 'plaintext'
? text
: text.replace(autolinkFullIssuesRegex, (linkText: string, repo: string, num: string) => {
const url = encodeUrl(
`${this.protocol}://${this.domain}/${unescapeMarkdown(repo)}/-/issues/${num}`,
);
const title = ` "Open Issue #${num} from ${repo} on ${this.name}"`;
const token = `\x00${tokenMapping.size}\x00`;
if (outputFormat === 'markdown') {
tokenMapping.set(token, `[${linkText}](${url}${title})`);
} else if (outputFormat === 'html') {
tokenMapping.set(token, `<a href="${url}" title=${title}>${linkText}</a>`);
}
let footnoteIndex: number;
const issueResult = enrichedAutolinks?.get(num)?.[0];
if (issueResult?.value != null) {
if (issueResult.paused) {
if (footnotes != null && !prs?.has(num)) {
footnoteIndex = footnotes.size + 1;
footnotes.set(
footnoteIndex,
`[${getIssueOrPullRequestMarkdownIcon()} GitLab Issue ${repo}#${num} $(loading~spin)](${url}${title}")`,
);
}
} else {
const issue = issueResult.value;
const issueTitle = escapeMarkdown(issue.title.trim());
if (footnotes != null && !prs?.has(num)) {
footnoteIndex = footnotes.size + 1;
footnotes.set(
footnoteIndex,
`[${getIssueOrPullRequestMarkdownIcon(
issue,
)} **${issueTitle}**](${url}${title})\\\n${GlyphChars.Space.repeat(
5,
)}${linkText} ${issue.state} ${fromNow(
issue.closedDate ?? issue.createdDate,
)}`,
);
}
}
} else if (footnotes != null && !prs?.has(num)) {
footnoteIndex = footnotes.size + 1;
footnotes.set(
footnoteIndex,
`[${getIssueOrPullRequestMarkdownIcon()} GitLab Issue ${repo}#${num}](${url}${title})`,
);
}
return token;
});
},
parse: (text: string, autolinks: Map<string, Autolink>) => {
let ownerAndRepo: string;
let num: string;
let match;
do {
match = autolinkFullIssuesRegex.exec(text);
if (match == null) break;
[, ownerAndRepo, num] = match;
const [owner, repo] = ownerAndRepo.split('/', 2);
autolinks.set(num, {
provider: this,
id: num,
prefix: `${ownerAndRepo}#`,
url: `${this.protocol}://${this.domain}/${ownerAndRepo}/-/issues/${num}`,
alphanumeric: false,
ignoreCase: true,
title: `Open Issue #<num> from ${ownerAndRepo} on ${this.name}`,
type: 'issue',
description: `${this.name} Issue ${ownerAndRepo}#${num}`,
descriptor: {
key: this.remoteKey,
owner: owner,
name: repo,
} satisfies GitLabRepositoryDescriptor,
});
} while (true);
},
},
{
tokenize: (
text: string,
outputFormat: 'html' | 'markdown' | 'plaintext',
tokenMapping: Map<string, string>,
enrichedAutolinks?: Map<string, MaybeEnrichedAutolink>,
prs?: Set<string>,
footnotes?: Map<number, string>,
) => {
return outputFormat === 'plaintext'
? text
: text.replace(
autolinkFullMergeRequestsRegex,
(linkText: string, repo: string, num: string) => {
const url = encodeUrl(
`${this.protocol}://${this.domain}/${repo}/-/merge_requests/${num}`,
);
const title = ` "Open Merge Request !${num} from ${repo} on ${this.name}"`;
const token = `\x00${tokenMapping.size}\x00`;
if (outputFormat === 'markdown') {
tokenMapping.set(token, `[${linkText}](${url}${title})`);
} else if (outputFormat === 'html') {
tokenMapping.set(token, `<a href="${url}" title=${title}>${linkText}</a>`);
}
let footnoteIndex: number;
const issueResult = enrichedAutolinks?.get(num)?.[0];
if (issueResult?.value != null) {
if (issueResult.paused) {
if (footnotes != null && !prs?.has(num)) {
footnoteIndex = footnotes.size + 1;
footnotes.set(
footnoteIndex,
`[${getIssueOrPullRequestMarkdownIcon()} ${
this.name
} Merge Request ${repo}!${num} $(loading~spin)](${url}${title}")`,
);
}
} else {
const issue = issueResult.value;
const issueTitle = escapeMarkdown(issue.title.trim());
if (footnotes != null && !prs?.has(num)) {
footnoteIndex = footnotes.size + 1;
footnotes.set(
footnoteIndex,
`[${getIssueOrPullRequestMarkdownIcon(
issue,
)} **${issueTitle}**](${url}${title})\\\n${GlyphChars.Space.repeat(
5,
)}${linkText} ${issue.state} ${fromNow(
issue.closedDate ?? issue.createdDate,
)}`,
);
}
}
} else if (footnotes != null && !prs?.has(num)) {
footnoteIndex = footnotes.size + 1;
footnotes.set(
footnoteIndex,
`[${getIssueOrPullRequestMarkdownIcon()} ${
this.name
} Merge Request ${repo}!${num}](${url}${title})`,
);
}
return token;
},
);
},
parse: (text: string, autolinks: Map<string, Autolink>) => {
let ownerAndRepo: string;
let num: string;
let match;
do {
match = autolinkFullMergeRequestsRegex.exec(text);
if (match == null) break;
[, ownerAndRepo, num] = match;
const [owner, repo] = ownerAndRepo.split('/', 2);
autolinks.set(num, {
provider: this,
id: num,
prefix: `${ownerAndRepo}!`,
url: `${this.protocol}://${this.domain}/${ownerAndRepo}/-/merge_requests/${num}`,
alphanumeric: false,
ignoreCase: true,
title: `Open Merge Request !<num> from ${ownerAndRepo} on ${this.name}`,
type: 'pullrequest',
description: `${this.name} Merge Request !${num} from ${ownerAndRepo}`,
descriptor: {
key: this.remoteKey,
owner: owner,
name: repo,
} satisfies GitLabRepositoryDescriptor,
});
} while (true);
},
},
];
}
return this._autolinks;
}
override get icon() {
return 'gitlab';
}
get id(): RemoteProviderId {
return 'gitlab';
}
get gkProviderId(): GkProviderId {
return (!isGitLabDotCom(this.domain)
? 'gitlabSelfHosted'
: 'gitlab') satisfies Unbrand<GkProviderId> as Brand<GkProviderId>;
}
get name() {
return this.formatName('GitLab');
}
@memoize()
override get repoDesc(): GitLabRepositoryDescriptor {
const [owner, repo] = this.splitPath();
return { key: this.remoteKey, owner: owner, name: repo };
}
async getLocalInfoFromRemoteUri(
repository: Repository,
uri: Uri,
options?: { validate?: boolean },
): Promise<{ uri: Uri; startLine?: number; endLine?: number } | undefined> {
if (uri.authority !== this.domain) return undefined;
if ((options?.validate ?? true) && !uri.path.startsWith(`/${this.path}/`)) return undefined;
let startLine;
let endLine;
if (uri.fragment) {
const match = rangeRegex.exec(uri.fragment);
if (match != null) {
const [, start, end] = match;
if (start) {
startLine = parseInt(start, 10);
if (end) {
endLine = parseInt(end, 10);
}
}
}
}
const match = fileRegex.exec(uri.path);
if (match == null) return undefined;
const [, , , path] = match;
// Check for a permalink
let index = path.indexOf('/', 1);
if (index !== -1) {
const sha = path.substring(1, index);
if (isSha(sha)) {
const uri = repository.toAbsoluteUri(path.substring(index), { validate: options?.validate });
if (uri != null) return { uri: uri, startLine: startLine, endLine: endLine };
}
}
// Check for a link with branch (and deal with branch names with /)
let branch;
const possibleBranches = new Map<string, string>();
index = path.length;
do {
index = path.lastIndexOf('/', index - 1);
branch = path.substring(1, index);
possibleBranches.set(branch, path.substring(index));
} while (index > 0);
if (possibleBranches.size !== 0) {
const { values: branches } = await repository.git.getBranches({
filter: b => b.remote && possibleBranches.has(b.getNameWithoutRemote()),
});
for (const branch of branches) {
const path = possibleBranches.get(branch.getNameWithoutRemote());
if (path == null) continue;
const uri = repository.toAbsoluteUri(path, { validate: options?.validate });
if (uri != null) return { uri: uri, startLine: startLine, endLine: endLine };
}
}
return undefined;
}
protected getUrlForBranches(): string {
return this.encodeUrl(`${this.baseUrl}/-/branches`);
}
protected getUrlForBranch(branch: string): string {
return this.encodeUrl(`${this.baseUrl}/-/tree/${branch}`);
}
protected getUrlForCommit(sha: string): string {
return this.encodeUrl(`${this.baseUrl}/-/commit/${sha}`);
}
protected override getUrlForComparison(base: string, compare: string, notation: '..' | '...'): string {
return this.encodeUrl(`${this.baseUrl}/-/compare/${base}${notation}${compare}`);
}
protected getUrlForFile(fileName: string, branch?: string, sha?: string, range?: Range): string {
let line;
if (range != null) {
if (range.start.line === range.end.line) {
line = `#L${range.start.line}`;
} else {
line = `#L${range.start.line}-${range.end.line}`;
}
} else {
line = '';
}
if (sha) return `${this.encodeUrl(`${this.baseUrl}/-/blob/${sha}/${fileName}`)}${line}`;
if (branch) return `${this.encodeUrl(`${this.baseUrl}/-/blob/${branch}/${fileName}`)}${line}`;
return `${this.encodeUrl(`${this.baseUrl}?path=${fileName}`)}${line}`;
}
protected override getUrlForTag(tag: string) {
return this.encodeUrl(`${this.baseUrl}/-/tags/${tag}`);
}
}