-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
executable file
·305 lines (242 loc) · 7.89 KB
/
index.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
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
#!/usr/bin/env node
const fs = require('fs');
const child = require('child_process');
const inquirer = require('inquirer');
const fullImageNameRx = /^([a-z0-9]+)\/([a-z0-9-]+)(?::([a-z0-9._-]+))?$/i;
let packageInfo = null;
let releaseInfo = null;
try {
packageInfo = JSON.parse(fs.readFileSync('package.json', 'utf-8'));
} catch (err) {
console.error('No package.json found');
process.exit(1);
}
try {
releaseInfo = JSON.parse(fs.readFileSync('.docker-release.json', 'utf-8'));
} catch {}
async function run() {
await checkRepositoryState();
const updateType = await promptUpdateType();
let version;
if (updateType) {
version = await updateVersion(updateType);
} else {
version = packageInfo.version;
}
try {
const imageName = getLocalImageName();
console.log('Start image building...');
const imageId = await buildImage(imageName);
const info = await getDockerHubInfo(version);
if (info) {
await tagImage(info, imageId);
await pushImage(info);
}
if (updateType) {
await gitPush(version);
}
console.log(`Operation have done, package version: ${version}`);
} catch (err) {
try {
await asyncExec('git checkout -- package.json');
await asyncExec('git checkout -- package-lock.json');
} catch {}
throw err;
}
}
function asyncExec(command) {
return new Promise((resolve, reject) => {
child.exec(command, (err, stdout, stderr) => {
if (err) {
reject(err);
} else {
resolve({ stdout: stdout.trim(), stderr: stderr.trim() });
}
});
});
}
function asyncExec2(command, args) {
return new Promise((resolve, reject) => {
const proc = child.spawn(command, args, {
stdio: ['inherit', 'pipe', 'pipe'],
});
proc.stdout.pipe(process.stdout);
proc.stderr.pipe(process.stderr);
const stdoutChunks = [];
const stderrChunks = [];
proc.stdout.on('data', data => {
stdoutChunks.push(data);
});
proc.stderr.on('data', data => {
stderrChunks.push(data);
});
proc.on('error', err => {
err.stdout = stdoutChunks.join('').trim();
err.stderr = stderrChunks.join('').trim();
reject(err);
});
proc.on('close', code => {
const stdout = stdoutChunks.join('').trim();
const stderr = stderrChunks.join('').trim();
if (code !== 0) {
const error = new Error('Closed with error');
error.code = code;
error.stdout = stdout;
error.stderr = stderr;
reject(error);
return;
}
resolve({ stdout, stderr });
});
});
}
async function checkRepositoryState() {
const { stdout } = await asyncExec('git status');
if (!stdout.endsWith('\nnothing to commit, working tree clean')) {
console.error(stdout);
console.error(
'\nError: Repository working tree is not clean!\n Please commit changes and try again.'
);
process.exit(1);
}
}
async function updateVersion(updateType) {
const { stdout } = await asyncExec(
`npm version --no-git-tag-version ${updateType} -m 'version %s'`
);
return stdout.replace(/^v/, '');
}
async function promptUpdateType() {
const { version } = await inquirer.prompt({
type: 'list',
name: 'version',
message: `What type of update is it (current version: ${packageInfo.version})?`,
choices: ['major', 'minor', 'patch', 'no (skip update)'],
default: 'patch',
});
if (version === 'no (skip update)') {
return null;
}
return version;
}
function getLocalImageName() {
return (
(releaseInfo && releaseInfo.imageName) ||
(packageInfo.dockerRelease && packageInfo.dockerRelease.imageName) ||
packageInfo.name
);
}
async function getDockerHubInfo(version) {
const info = {
user:
(releaseInfo && releaseInfo.user) ||
(packageInfo.dockerRelease && packageInfo.dockerRelease.user),
imageName:
(releaseInfo && releaseInfo.imageName) ||
(packageInfo.dockerRelease &&
packageInfo.dockerRelease.imageName) ||
packageInfo.name,
version,
tags: [],
};
const publishChoices = [];
if (info.user && info.imageName) {
publishChoices.push(`As "${info.user}/${info.imageName}:${version}"`);
}
publishChoices.push('Enter manually', `No, don't publish`);
const { publish } = await inquirer.prompt({
type: 'list',
name: 'publish',
message: 'Do you want to publish image to hub.docker.com?',
choices: publishChoices,
default: "No, don't publish",
});
if (publish === "No, don't publish") {
return;
}
if (publish === 'Enter manually') {
const { fullImageName } = await inquirer.prompt([
{
type: 'input',
name: 'fullImageName',
message: `Enter docker hub image (if version won't be specified, ${version} will be used):\n `,
validate(msg) {
if (msg.length === 0) {
return 'Required';
}
if (!fullImageNameRx.test(msg)) {
return 'Invalid format. Pattern: "user/image" or "user/image:version"';
}
return true;
},
},
]);
const [, user, imageName, imageVersion] = fullImageName.match(
fullImageNameRx
);
info.user = user;
info.imageName = imageName;
if (imageVersion) {
info.version = imageVersion;
}
}
info.tags = await askAboutAboutAdditionalTags(info);
return info;
}
async function buildImage(imageName) {
const { stdout } = await asyncExec2('docker', [
'build',
'-t',
imageName,
'.',
]);
const match = stdout
.substr(-100)
.match(/\nSuccessfully built ([0-9a-f]+)\n/);
return match[1];
}
async function tagImage({ user, imageName, version, tags }, imageId) {
await asyncExec(`docker tag ${imageId} ${user}/${imageName}:${version}`);
for (const tag of tags) {
await asyncExec(`docker tag ${imageId} ${user}/${imageName}:${tag}`);
}
}
async function pushImage({ user, imageName, version, tags }) {
await asyncExec2('docker', ['push', `${user}/${imageName}:${version}`]);
for (const tag of tags) {
await asyncExec2('docker', ['push', `${user}/${imageName}:${tag}`]);
}
}
async function gitPush(version) {
await asyncExec('git add -- package.json');
try {
await asyncExec('git add -- package-lock.json');
} catch {}
await asyncExec(`git commit -m 'version ${version}'`);
await asyncExec(`git tag v${version} -m 'version ${version}'`);
await asyncExec('git push');
await asyncExec(`git push --tags origin v${version}`);
}
async function askAboutAboutAdditionalTags(info) {
const parts = info.version.split('.');
const choices = [];
if (parts.length > 2) {
choices.push(`also tag as :${parts[0]}.${parts[1]}`);
}
if (parts.length > 1 && parts[0] !== '0') {
choices.push(`also tag as :${parts[0]}`);
}
choices.push('also tag as :latest', 'also tag as :develop');
const { tags } = await inquirer.prompt([
{
type: 'checkbox',
name: 'tags',
message: 'Do you want to make additional tags?',
choices,
},
]);
return tags.map(tag => tag.replace(/^also tag as :/, ''));
}
run().catch(err => {
console.error(err);
});