-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·97 lines (84 loc) · 2.66 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
#!/usr/bin/env node
const path = require('path');
const mkdirp = require('mkdirp');
const tar = require('tar-fs');
const as = require('async');
const program = require('commander');
const git = require('simple-git');
const Docker = require('dockerode');
const ciOptions = require('rc')('jsci', {
workspace: __dirname,
docker: {
socketPath: '/var/run/docker.sock'
},
auth: {
hub: {
username: 'hubuser',
password: 'changeme'
}
}
});
program
.option('--config', 'Config path for rc to use (not used directly)')
.option('-f, --file [file]', 'Path to the json build file', './example.json')
.parse(process.argv);
const instructions = require(path.resolve(program.file));
const buildNumber = Date.now().toString();
const workdir = path.join(ciOptions.workspace, instructions.name, buildNumber);
const docker = new Docker(ciOptions.docker);
function start() {
as.series([
initWorkspace.bind(null, workdir),
checkout.bind(null, instructions.git.repo),
build.bind(null, instructions.build.image, instructions.build.steps),
publish.bind(null, instructions.publish)
], (err) => {
if (err) throw err;
console.log(`Job Complete. (${instructions.name} #${buildNumber})`);
});
}
/* Checkout (clone) functions */
function initWorkspace(path, cb) {
mkdirp(path, cb);
}
function checkout(repo, cb) {
git().outputHandler((command, stdout, stderr) => {
console.log(`RUNNING GIT COMMAND: ${command}`);
stdout.pipe(process.stdout);
stderr.pipe(process.stdout);
}).clone(repo, workdir, null, cb);
}
/* Build Functions */
function build(image, steps, cb) {
as.eachSeries(steps, runStep.bind(null, image), cb);
}
function runStep(image, step, cb) {
console.log('RUNNING BUILD STEP:', 'Image:', image, 'Step:', step);
docker.run(image, ['sh', '-c', step], process.stdout, { HostConfig: {Binds: [`${workdir}:/build`]}, WorkingDir: '/build' },
(err, data, container) => {
if (err) return cb(err);
container.remove(cb);
});
}
/* Publish Functions */
function buildImage(tag, cb) {
console.log(`Building Image: ${tag}`);
docker.buildImage(tar.pack(workdir), { t: tag }, cb);
}
function pushImage (tag, authRef, cb) {
console.log(`Pushing Image: ${tag}`);
docker.getImage(tag).push({ authconfig: ciOptions.auth[authRef], stream: true }, cb);
}
function handleStream(stream, cb) {
stream.on('error', cb).on('end', cb).pipe(process.stdout);
}
function publish(dockerOptions, cb) {
const tag = `${dockerOptions.registry}/${dockerOptions.repo}:${buildNumber}`;
as.waterfall([
buildImage.bind(null, tag),
handleStream,
pushImage.bind(null, tag, dockerOptions.authRef),
handleStream
], cb);
}
start();