-
Notifications
You must be signed in to change notification settings - Fork 341
/
gitlab.js
271 lines (216 loc) · 7.3 KB
/
gitlab.js
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
const fetch = require('node-fetch');
const FormData = require('form-data');
const { URL, URLSearchParams } = require('url');
const { spawn } = require('child_process');
const fs = require('fs').promises;
const fse = require('fs-extra');
const { resolve } = require('path');
const { fetchUploadData, download, exec } = require('../utils');
const {
IN_DOCKER,
CI_BUILD_REF_NAME,
CI_COMMIT_SHA,
GITLAB_USER_EMAIL,
GITLAB_USER_NAME
} = process.env;
const API_VER = 'v4';
class Gitlab {
constructor(opts = {}) {
const { repo, token } = opts;
if (!token) throw new Error('token not found');
if (!repo) throw new Error('repo not found');
this.token = token;
this.repo = repo;
}
async projectPath() {
const repoBase = await this.repoBase();
const projectPath = encodeURIComponent(
this.repo.replace(repoBase, '').substr(1)
);
return projectPath;
}
async repoBase() {
if (this.detectedBase) return this.detectedBase;
const { origin, pathname } = new URL(this.repo);
const possibleBases = await Promise.all(
pathname
.split('/')
.filter(Boolean)
.map(async (_, index, array) => {
const components = [origin, ...array.slice(0, index)];
const path = components.join('/');
try {
if (
(await this.request({ url: `${path}/api/${API_VER}/version` }))
.version
)
return path;
} catch (error) {
return error;
}
})
);
this.detectedBase = possibleBases.find(
(base) => base.constructor !== Error
);
if (!this.detectedBase) {
if (possibleBases.length) throw possibleBases[0];
throw new Error('Invalid repository address');
}
return this.detectedBase;
}
async commentCreate(opts = {}) {
const { commitSha, report, update } = opts;
if (update) throw new Error('GitLab does not support comment updates!');
const projectPath = await this.projectPath();
const endpoint = `/projects/${projectPath}/repository/commits/${commitSha}/comments`;
const body = new URLSearchParams();
body.append('note', report);
const output = await this.request({ endpoint, method: 'POST', body });
return output;
}
async checkCreate() {
throw new Error('Gitlab does not support check!');
}
async upload(opts = {}) {
const { repo } = this;
const projectPath = await this.projectPath();
const endpoint = `/projects/${projectPath}/uploads`;
const { size, mime, data } = await fetchUploadData(opts);
const body = new FormData();
body.append('file', data);
const { url } = await this.request({ endpoint, method: 'POST', body });
return { uri: `${repo}${url}`, mime, size };
}
async runnerToken() {
const projectPath = await this.projectPath();
const endpoint = `/projects/${projectPath}`;
const { runners_token: runnersToken } = await this.request({ endpoint });
return runnersToken;
}
async registerRunner(opts = {}) {
const { tags, name } = opts;
const token = await this.runnerToken();
const endpoint = `/runners`;
const body = new URLSearchParams();
body.append('description', name);
body.append('tag_list', tags);
body.append('token', token);
body.append('locked', 'true');
body.append('run_untagged', 'true');
body.append('access_level', 'not_protected');
return await this.request({ endpoint, method: 'POST', body });
}
async unregisterRunner(opts = {}) {
const { name } = opts;
const { id } = await this.runnerByName({ name });
const endpoint = `/runners/${id}`;
return await this.request({ endpoint, method: 'DELETE', raw: true });
}
async startRunner(opts) {
const { workdir, idleTimeout, single, labels, name } = opts;
let gpu = true;
try {
await exec('nvidia-smi');
} catch (err) {
gpu = false;
}
try {
const bin = resolve(workdir, 'gitlab-runner');
if (!(await fse.pathExists(bin))) {
const url =
'https://gitlab-runner-downloads.s3.amazonaws.com/latest/binaries/gitlab-runner-linux-amd64';
await download({ url, path: bin });
await fs.chmod(bin, '777');
}
const { protocol, host } = new URL(this.repo);
const { token } = await this.registerRunner({ tags: labels, name });
const command = `${bin} --log-format="json" run-single \
--builds-dir "${workdir}" \
--cache-dir "${workdir}" \
--url "${protocol}//${host}" \
--name "${name}" \
--token "${token}" \
--wait-timeout ${idleTimeout} \
--executor "${IN_DOCKER ? 'shell' : 'docker'}" \
--docker-image "dvcorg/cml:latest" \
--docker-runtime "${gpu ? 'nvidia' : ''}" \
${single ? '--max-builds 1' : ''}`;
return spawn(command, { shell: true });
} catch (err) {
throw new Error(`Failed preparing Gitlab runner: ${err.message}`);
}
}
async runnerByName(opts = {}) {
const { name } = opts;
const endpoint = `/runners?per_page=100`;
const runners = await this.request({ endpoint, method: 'GET' });
const runner = runners.filter(
(runner) => runner.name === name || runner.description === name
)[0];
if (runner) return { id: runner.id, name: runner.name };
}
async runnersByLabels(opts = {}) {
const { labels } = opts;
const endpoint = `/runners?per_page=100?tag_list=${labels}`;
const runners = await this.request({ endpoint, method: 'GET' });
return runners.map((runner) => ({ id: runner.id, name: runner.name }));
}
async prCreate(opts = {}) {
const projectPath = await this.projectPath();
const { source, target, title, description } = opts;
const endpoint = `/projects/${projectPath}/merge_requests`;
const body = new URLSearchParams();
body.append('source_branch', source);
body.append('target_branch', target);
body.append('title', title);
body.append('description', description);
const { web_url: url } = await this.request({
endpoint,
method: 'POST',
body
});
return url;
}
async prs(opts = {}) {
const projectPath = await this.projectPath();
const { state = 'opened' } = opts;
const endpoint = `/projects/${projectPath}/merge_requests?state=${state}`;
const prs = await this.request({ endpoint, method: 'GET' });
return prs.map((pr) => {
const { web_url: url, source_branch: source, target_branch: target } = pr;
return {
url,
source,
target
};
});
}
async request(opts = {}) {
const { token } = this;
const { endpoint, method = 'GET', body, raw } = opts;
let { url } = opts;
if (endpoint) {
url = `${await this.repoBase()}/api/${API_VER}${endpoint}`;
}
if (!url) throw new Error('Gitlab API endpoint not found');
const headers = { 'PRIVATE-TOKEN': token, Accept: 'application/json' };
const response = await fetch(url, { method, headers, body });
if (response.status > 300) throw new Error(response.statusText);
if (raw) return response;
return await response.json();
}
get sha() {
return CI_COMMIT_SHA;
}
get branch() {
return CI_BUILD_REF_NAME;
}
get userEmail() {
return GITLAB_USER_EMAIL;
}
get userName() {
return GITLAB_USER_NAME;
}
}
module.exports = Gitlab;