-
Notifications
You must be signed in to change notification settings - Fork 1
/
stage.js
133 lines (106 loc) · 2.65 KB
/
stage.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
const ADAPTERS = {};
class Stage {
static get ADAPTERS () {
return ADAPTERS;
}
static reset (empty = false) {
for (const key in ADAPTERS) {
delete ADAPTERS[key];
}
if (!empty) {
Stage.putAdapter('stack', require('./adapters/stack'));
Stage.putAdapter('compose', require('./adapters/compose'));
Stage.putAdapter('docker', require('./adapters/docker'));
Stage.putAdapter('build', require('./adapters/build'));
}
}
static putAdapter (type, Adapter) {
ADAPTERS[type] = Adapter;
}
static findSuitableAdapterType (config) {
for (const type in ADAPTERS) {
const Adapter = ADAPTERS[type];
if (Adapter.test(config)) {
return type;
}
}
}
static validate (config) {
const { name, type = Stage.findSuitableAdapterType(config) } = config;
if (!name) {
throw new Error('Name must be specified');
}
const Adapter = ADAPTERS[type];
if (!type || !Adapter) {
throw new Error('Unknown adapter type');
}
return {
name,
type,
...Adapter.validate(config),
};
}
constructor (pipeline, config) {
config = Stage.validate(config);
this.name = config.name;
this.type = config.type;
this.detach = !!config.detach;
Object.assign(this, config);
const Adapter = ADAPTERS[this.type];
const adapter = new Adapter(this);
Object.defineProperties(this, {
pipeline: {
get () {
return pipeline;
},
},
adapter: {
get () {
return adapter;
},
},
});
}
get workDir () {
return this.pipeline.workDir;
}
dump () {
const config = {
...this,
};
delete config.pipeline;
delete config.name;
return config;
}
async run ({ env, labels, attach = false, logger = () => undefined } = {}) {
const stageLogger = log => {
log.pipeline = this.pipeline.name;
log.stage = this.name;
logger(log);
};
if (attach) {
this.detach = false;
}
labels = {
...labels,
'id.sagara.cicd.pipeline': this.pipeline.name,
'id.sagara.cicd.stage': this.name,
};
await this.adapter.run({ env, labels, logger: stageLogger });
}
async abort ({ env, labels, logger = () => undefined } = {}) {
const stageLogger = log => {
log.pipeline = this.pipeline.name;
log.stage = this.name;
logger(log);
};
labels = {
...labels,
'id.sagara.cicd.pipeline': this.pipeline.name,
'id.sagara.cicd.stage': this.name,
};
await this.adapter.abort({ env, labels, logger: stageLogger });
}
}
Stage.reset();
module.exports = { Stage };