-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathbitbucket-api.ts
345 lines (313 loc) · 9.74 KB
/
bitbucket-api.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
import type { HttpsProxyAgent } from 'https-proxy-agent';
import type { CancellationToken, Disposable } from 'vscode';
import { window } from 'vscode';
import type { RequestInit, Response } from '@env/fetch';
import { fetch, getProxyAgent, wrapForForcedInsecureSSL } from '@env/fetch';
import { isWeb } from '@env/platform';
import type { Container } from '../../../../container';
import {
AuthenticationError,
AuthenticationErrorReason,
CancellationError,
ProviderFetchError,
RequestClientError,
RequestNotFoundError,
} from '../../../../errors';
import type { IssueOrPullRequest, IssueOrPullRequestType } from '../../../../git/models/issueOrPullRequest';
import type { PullRequest } from '../../../../git/models/pullRequest';
import type { Provider } from '../../../../git/models/remoteProvider';
import type { RepositoryMetadata } from '../../../../git/models/repositoryMetadata';
import { showIntegrationRequestFailed500WarningMessage } from '../../../../messages';
import { configuration } from '../../../../system/-webview/configuration';
import { debug } from '../../../../system/decorators/log';
import { Logger } from '../../../../system/logger';
import type { LogScope } from '../../../../system/logger.scope';
import { getLogScope } from '../../../../system/logger.scope';
import { maybeStopWatch } from '../../../../system/stopwatch';
import type { BitbucketIssue, BitbucketPullRequest, BitbucketRepository } from './models';
import { bitbucketIssueStateToState, fromBitbucketPullRequest } from './models';
export class BitbucketApi implements Disposable {
private readonly _disposable: Disposable;
constructor(_container: Container) {
this._disposable = configuration.onDidChangeAny(e => {
if (
configuration.changedCore(e, ['http.proxy', 'http.proxyStrictSSL']) ||
configuration.changed(e, ['outputLevel', 'proxy'])
) {
this.resetCaches();
}
});
}
dispose(): void {
this._disposable.dispose();
}
private _proxyAgent: HttpsProxyAgent | null | undefined = null;
private get proxyAgent(): HttpsProxyAgent | undefined {
if (isWeb) return undefined;
if (this._proxyAgent === null) {
this._proxyAgent = getProxyAgent();
}
return this._proxyAgent;
}
private resetCaches(): void {
this._proxyAgent = null;
}
@debug<BitbucketApi['getPullRequestForBranch']>({ args: { 0: p => p.name, 1: '<token>' } })
public async getPullRequestForBranch(
provider: Provider,
token: string,
owner: string,
repo: string,
branch: string,
options: {
baseUrl: string;
},
): Promise<PullRequest | undefined> {
const scope = getLogScope();
const response = await this.request<{
values: BitbucketPullRequest[];
pagelen: number;
size: number;
page: number;
}>(
provider,
token,
options.baseUrl,
`repositories/${owner}/${repo}/pullrequests?q=source.branch.name="${branch}"&fields=values.*`, // TODO: be more precise on additional fields. look at getRepositoriesForWorkspace
{
method: 'GET',
},
scope,
);
if (!response?.values?.length) {
return undefined;
}
return fromBitbucketPullRequest(response.values[0], provider);
}
@debug<BitbucketApi['getIssueOrPullRequest']>({ args: { 0: p => p.name, 1: '<token>' } })
public async getIssueOrPullRequest(
provider: Provider,
token: string,
owner: string,
repo: string,
id: string,
options: {
baseUrl: string;
type?: IssueOrPullRequestType;
},
): Promise<IssueOrPullRequest | undefined> {
const scope = getLogScope();
if (options?.type !== 'issue') {
try {
const prResponse = await this.request<BitbucketPullRequest>(
provider,
token,
options.baseUrl,
`repositories/${owner}/${repo}/pullrequests/${id}?fields=*`, // TODO: be more precise on additional fields. look at getRepositoriesForWorkspace
{
method: 'GET',
},
scope,
);
if (prResponse) {
return fromBitbucketPullRequest(prResponse, provider);
}
} catch (ex) {
if (ex.original?.status !== 404) {
Logger.error(ex, scope);
return undefined;
}
}
}
if (options?.type !== 'pullrequest') {
try {
const issueResponse = await this.request<BitbucketIssue>(
provider,
token,
options.baseUrl,
`repositories/${owner}/${repo}/issues/${id}`,
{
method: 'GET',
},
scope,
);
if (issueResponse) {
return {
id: issueResponse.id.toString(),
type: 'issue',
nodeId: issueResponse.id.toString(),
provider: provider,
createdDate: new Date(issueResponse.created_on),
updatedDate: new Date(issueResponse.updated_on),
state: bitbucketIssueStateToState(issueResponse.state),
closed: issueResponse.state === 'closed',
title: issueResponse.title,
url: issueResponse.links.html.href,
};
}
} catch (ex) {
Logger.error(ex, scope);
return undefined;
}
}
return undefined;
}
@debug<BitbucketApi['getRepositoriesForWorkspace']>({ args: { 0: p => p.name, 1: '<token>' } })
public async getRepositoriesForWorkspace(
provider: Provider,
token: string,
workspace: string,
options: {
baseUrl: string;
},
): Promise<RepositoryMetadata[] | undefined> {
const scope = getLogScope();
try {
interface BitbucketRepositoriesResponse {
size: number;
page: number;
pagelen: number;
next?: string;
previous?: string;
values: BitbucketRepository[];
}
const response = await this.request<BitbucketRepositoriesResponse>(
provider,
token,
options.baseUrl,
`repositories/${workspace}?role=contributor&fields=%2Bvalues.parent.workspace`, // field=+<field> must be encoded as field=%2B<field>
{
method: 'GET',
},
scope,
);
if (response) {
return response.values.map(repo => {
return {
provider: provider,
owner: repo.workspace.slug,
name: repo.slug,
isFork: Boolean(repo.parent),
parent: repo.parent
? {
owner: repo.parent.workspace.slug,
name: repo.parent.slug,
}
: undefined,
};
});
}
return undefined;
} catch (ex) {
Logger.error(ex, scope);
return undefined;
}
}
private async request<T>(
provider: Provider,
token: string,
baseUrl: string,
route: string,
options: { method: RequestInit['method'] } & Record<string, unknown>,
scope: LogScope | undefined,
cancellation?: CancellationToken | undefined,
): Promise<T | undefined> {
const url = `${baseUrl}/${route}`;
let rsp: Response;
try {
const sw = maybeStopWatch(`[BITBUCKET] ${options?.method ?? 'GET'} ${url}`, { log: false });
const agent = this.proxyAgent;
try {
let aborter: AbortController | undefined;
if (cancellation != null) {
if (cancellation.isCancellationRequested) throw new CancellationError();
aborter = new AbortController();
cancellation.onCancellationRequested(() => aborter!.abort());
}
rsp = await wrapForForcedInsecureSSL(provider.getIgnoreSSLErrors(), () =>
fetch(url, {
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
agent: agent,
signal: aborter?.signal,
...options,
}),
);
if (rsp.ok) {
const data: T = await rsp.json();
return data;
}
throw new ProviderFetchError('Bitbucket', rsp);
} finally {
sw?.stop();
}
} catch (ex) {
if (ex instanceof ProviderFetchError || ex.name === 'AbortError') {
this.handleRequestError(provider, token, ex, scope);
} else if (Logger.isDebugging) {
void window.showErrorMessage(`Bitbucket request failed: ${ex.message}`);
}
throw ex;
}
}
private handleRequestError(
provider: Provider | undefined,
_token: string,
ex: ProviderFetchError | (Error & { name: 'AbortError' }),
scope: LogScope | undefined,
): void {
if (ex.name === 'AbortError' || !(ex instanceof ProviderFetchError)) throw new CancellationError(ex);
switch (ex.status) {
case 404: // Not found
case 410: // Gone
case 422: // Unprocessable Entity
throw new RequestNotFoundError(ex);
case 401: // Unauthorized
throw new AuthenticationError('bitbucket', AuthenticationErrorReason.Unauthorized, ex);
case 403: // Forbidden
// TODO: Learn the Bitbucket API docs and put it in order:
// if (ex.message.includes('rate limit')) {
// let resetAt: number | undefined;
// const reset = ex.response?.headers?.get('x-ratelimit-reset');
// if (reset != null) {
// resetAt = parseInt(reset, 10);
// if (Number.isNaN(resetAt)) {
// resetAt = undefined;
// }
// }
// throw new RequestRateLimitError(ex, token, resetAt);
// }
throw new AuthenticationError('bitbucket', AuthenticationErrorReason.Forbidden, ex);
case 500: // Internal Server Error
Logger.error(ex, scope);
if (ex.response != null) {
provider?.trackRequestException();
void showIntegrationRequestFailed500WarningMessage(
`${provider?.name ?? 'Bitbucket'} failed to respond and might be experiencing issues.${
provider == null || provider.id === 'bitbucket'
? ' Please visit the [Bitbucket status page](https://bitbucket.status.atlassian.com/) for more information.'
: ''
}`,
);
}
return;
case 502: // Bad Gateway
Logger.error(ex, scope);
// TODO: Learn the Bitbucket API docs and put it in order:
// if (ex.message.includes('timeout')) {
// provider?.trackRequestException();
// void showIntegrationRequestTimedOutWarningMessage(provider?.name ?? 'Bitbucket');
// return;
// }
break;
default:
if (ex.status >= 400 && ex.status < 500) throw new RequestClientError(ex);
break;
}
Logger.error(ex, scope);
if (Logger.isDebugging) {
void window.showErrorMessage(
`Bitbucket request failed: ${(ex.response as any)?.errors?.[0]?.message ?? ex.message}`,
);
}
}
}