-
Notifications
You must be signed in to change notification settings - Fork 3k
Expand file tree
/
Copy pathutils.ts
More file actions
192 lines (174 loc) · 5.45 KB
/
utils.ts
File metadata and controls
192 lines (174 loc) · 5.45 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
// SEE for the reference https://github.com/renovatebot/renovate/blob/c3e9e572b225085448d94aa121c7ec81c14d3955/lib/platform/bitbucket/utils.js
import { isNonEmptyString } from '@sindresorhus/is';
import { CONFIG_GIT_URL_UNAVAILABLE } from '../../../constants/error-messages.ts';
import { logger } from '../../../logger/index.ts';
import type { GitOptions, GitProtocol } from '../../../types/git.ts';
import type { HostRule } from '../../../types/index.ts';
import * as git from '../../../util/git/index.ts';
import { regEx } from '../../../util/regex.ts';
import { ensureTrailingSlash, parseUrl } from '../../../util/url.ts';
import { getPrBodyStruct } from '../pr-body.ts';
import type { GitUrlOption } from '../types.ts';
import type { BbsPr, BbsRestPr, BbsRestRepo, BitbucketError } from './types.ts';
export const BITBUCKET_INVALID_REVIEWERS_EXCEPTION =
'com.atlassian.bitbucket.pull.InvalidPullRequestReviewersException';
// https://docs.atlassian.com/bitbucket-server/rest/6.0.0/bitbucket-rest.html#idp250
const prStateMapping: any = {
MERGED: 'merged',
DECLINED: 'closed',
OPEN: 'open',
};
export function prInfo(pr: BbsRestPr): BbsPr {
return {
version: pr.version,
number: pr.id,
bodyStruct: getPrBodyStruct(pr.description),
sourceBranch: pr.fromRef.displayId,
targetBranch: pr.toRef.displayId,
title: pr.title,
state: prStateMapping[pr.state],
createdAt: pr.createdDate,
};
}
export interface BitbucketCommitStatus {
failed: number;
inProgress: number;
successful: number;
}
export type BitbucketBranchState =
| 'SUCCESSFUL'
| 'FAILED'
| 'INPROGRESS'
| 'STOPPED';
export interface BitbucketStatus {
key: string;
state: BitbucketBranchState;
}
export function isInvalidReviewersResponse(err: BitbucketError): boolean {
const errors = err?.response?.body?.errors ?? [];
return (
errors.length > 0 &&
errors.every(
(error) => error.exceptionName === BITBUCKET_INVALID_REVIEWERS_EXCEPTION,
)
);
}
export function getInvalidReviewers(err: BitbucketError): string[] {
const errors = err?.response?.body?.errors ?? [];
let invalidReviewers: string[] = [];
for (const error of errors) {
// v8 ignore else -- TODO: add test #40625
if (error.exceptionName === BITBUCKET_INVALID_REVIEWERS_EXCEPTION) {
invalidReviewers = invalidReviewers.concat(
error.reviewerErrors
?.map(({ context }) => context)
.filter(isNonEmptyString) ?? [],
);
}
}
return invalidReviewers;
}
function generateUrlFromEndpoint(
defaultEndpoint: string,
opts: HostRule,
repository: string,
): string {
const url = new URL(defaultEndpoint);
const authString =
opts.username && opts.password
? `${opts.username}:${opts.password}`
: (opts.username ?? '');
const generatedUrl = git.getUrl({
protocol: url.protocol as GitProtocol,
// TODO: types (#22198)
auth: authString,
host: `${url.host}${ensureTrailingSlash(url.pathname)}scm`,
repository,
});
logger.debug(`Using generated endpoint URL: ${generatedUrl}`);
return generatedUrl;
}
function injectAuth(url: string, opts: HostRule): string {
const repoUrl = parseUrl(url)!;
if (!repoUrl) {
logger.debug(`Invalid url: ${url}`);
throw new Error(CONFIG_GIT_URL_UNAVAILABLE);
}
// v8 ignore else -- TODO: add test #40625
if (!opts.token && opts.username && opts.password) {
repoUrl.username = opts.username;
repoUrl.password = opts.password;
}
return repoUrl.toString();
}
export function getRepoGitUrl(
repository: string,
defaultEndpoint: string,
gitUrl: GitUrlOption | undefined,
info: BbsRestRepo,
opts: HostRule,
): string {
switch (gitUrl) {
case 'endpoint': {
const generatedUrl = generateUrlFromEndpoint(
defaultEndpoint,
opts,
repository,
);
logger.debug(`Using endpoint URL: ${generatedUrl}`);
return generatedUrl;
}
case 'ssh': {
const sshUrl = info.links.clone?.find(({ name }) => name === 'ssh');
if (sshUrl === undefined) {
throw new Error(CONFIG_GIT_URL_UNAVAILABLE);
}
logger.debug(`Using ssh URL: ${sshUrl.href}`);
return sshUrl.href;
}
case undefined:
case 'default': {
let cloneUrl = info.links.clone?.find(({ name }) => name === 'http');
if (cloneUrl) {
// Inject auth into the API provided URL
return injectAuth(cloneUrl.href, opts);
}
// Http access might be disabled, try to find ssh url in this case
cloneUrl = info.links.clone?.find(({ name }) => name === 'ssh');
if (cloneUrl) {
return cloneUrl.href;
}
// SSH urls can be used directly
return generateUrlFromEndpoint(defaultEndpoint, opts, repository);
}
}
}
export function getExtraCloneOpts(opts: HostRule): GitOptions {
if (opts.token) {
return {
'-c': `http.extraHeader=Authorization: Bearer ${opts.token}`,
};
}
return {};
}
export function splitEscapedSpaces(str: string): string[] {
const parts = str.split(' ');
const result: string[] = [];
let last: string | undefined;
for (const part of parts) {
if (last?.endsWith('\\\\')) {
result[result.length - 1] = last.slice(0, -2) + ' ' + part;
} else {
result.push(part);
}
last = result.at(-1);
}
return result;
}
export function parseModifier(value: string): number | null {
const match = regEx('^random(?:\\((\\d+)\\))?$').exec(value);
if (!match) {
return null;
}
return parseInt(match[1] ?? '1', 10);
}