generated from simplify-framework/pets-project-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
355 lines (344 loc) · 17.9 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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
#!/usr/bin/env node
'use strict';
const YAML = require('yaml')
const path = require('path')
const fs = require('fs')
const fetch = require('node-fetch')
process.env.DISABLE_BOX_BANNER = true
const simplify = require('simplify-sdk')
const { options } = require('yargs');
const readlineSync = require('readline-sync');
const { OPT_COMMANDS } = require('./const')
const yargs = require('yargs');
const opName = `executePipeline`
const CERROR = '\x1b[31m'
const CGREEN = '\x1b[32m'
const CPROMPT = '\x1b[33m'
const CNOTIF = '\x1b[33m'
const CRESET = '\x1b[0m'
const CDONE = '\x1b[37m'
const CBRIGHT = '\x1b[37m'
const CUNDERLINE = '\x1b[4m'
const COLORS = function (name) {
const colorCodes = ["\x1b[31m", "\x1b[32m", "\x1b[33m", "\x1b[34m", "\x1b[35m", "\x1b[36m", "\x1b[31m", "\x1b[32m", "\x1b[33m", "\x1b[34m", "\x1b[35m", "\x1b[36m", "\x1b[31m", "\x1b[32m", "\x1b[33m", "\x1b[34m", "\x1b[35m", "\x1b[36m", "\x1b[31m", "\x1b[32m", "\x1b[33m", "\x1b[34m", "\x1b[35m", "\x1b[36m", "\x1b[31m", "\x1b[32m", "\x1b[33m", "\x1b[34m", "\x1b[35m", "\x1b[36m"]
return colorCodes[(name.toUpperCase().charCodeAt(0) - 65) % colorCodes.length]
}
const envFilePath = path.resolve('.env')
if (fs.existsSync(envFilePath)) {
require('dotenv').config({ path: envFilePath })
}
const showBoxBanner = function () {
console.log("╓───────────────────────────────────────────────────────────────╖")
console.log(`║ Simplify Pipeline - Version ${require('./package.json').version} ║`)
console.log("╙───────────────────────────────────────────────────────────────╜")
}
const getErrorMessage = function (error) {
return error.message ? error.message : JSON.stringify(error)
}
const getOptionDesc = function (cmdOpt, optName) {
const options = (OPT_COMMANDS.find(cmd => cmd.name == cmdOpt) || { options: [] }).options
return (options.find(opt => opt.name == optName) || { desc: '' }).desc
}
var argv = yargs.usage('simplify-pipeline create|list [stage] [options]')
.string('help').describe('help', 'display help for a specific command')
.string('project').alias('p', 'project').describe('project', getOptionDesc('create', 'project'))
.string('file').alias('f', 'file').describe('file', getOptionDesc('list', 'file')).default('.gitlab-ci.yml')
.demandCommand(1).argv;
showBoxBanner()
var cmdOPS = (argv._[0] || 'create').toUpperCase()
var optCMD = (argv._.length > 1 ? argv._[1] : undefined)
var index = -1
const filename = argv['file'] || '.gitlab-ci.yml'
const projectName = argv['project'] || '.simplify-pipeline'
if (!fs.existsSync(path.resolve(`${filename}`))) {
console.error(path.resolve(`${filename}`) + ' not found!')
process.exit()
}
const file = fs.readFileSync(path.resolve(`${filename}`), 'utf8')
let yamlObject = YAML.parse(file)
function getVolumeName(projectName) {
return projectName.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '')
}
function getImageName(image) {
return typeof image === 'object' ? image.name : image
}
const getContentArgs = function (...args) {
var template = args.shift()
function parseVariables(v) {
args.forEach(function (a) {
if (typeof a === 'object') {
Object.keys(a).map(function (i) {
if (a[i]) {
v = v.replace(new RegExp('\\${' + i + '}', 'g'), a[i])
const regxMatches = new RegExp('\\$' + i, 'g')
const valueMatches = ('$' + i).match(regxMatches)
if (valueMatches && valueMatches[0] === ('$' + i)) {
v = v.replace(regxMatches, a[i])
}
}
})
} else {
v = v.replace(new RegExp('\\${' + a + '}', 'g'), a)
const regxMatches = new RegExp('^\\$' + a, 'g')
const valueMatches = ('$' + a).match(regxMatches)
if (valueMatches && valueMatches[0] === ('$' + a)) {
v = v.replace(regxMatches, a)
}
}
})
Object.keys(process.env).map(function (e) {
v = v.replace(new RegExp('\\${' + e + '}', 'g'), process.env[e])
v = v.replace(new RegExp('\\$' + e, 'g'), process.env[e])
})
if (typeof args[args.length - 1] === 'boolean' && args[args.length - 1] === true) {
v = v.replace(new RegExp(/ *\{[^)]*\} */, 'g'), `(not set)`).replace(new RegExp('\\$', 'g'), '')
v = v.replace(new RegExp(/ *\[^)]*\ */, 'g'), `(not set)`).replace(new RegExp('\\$', 'g'), '')
}
return v
}
function parseKeyValue(obj) {
if (typeof obj !== 'object') {
obj = parseVariables(obj)
} else {
Object.keys(obj).map(function (k, i) {
if (typeof obj[k] === 'string') {
obj[k] = parseVariables(obj[k])
} else if (Array.isArray(obj)) {
obj[i] = parseKeyValue(obj[i])
} else if (typeof obj[k] === 'object') obj[k] = parseKeyValue(obj[k])
})
}
return obj
}
return parseKeyValue(template)
}
function objectMerges(...sources) {
let acc = {}
for (const source of sources) {
if (source instanceof Array) {
if (!(acc instanceof Array)) {
acc = []
}
acc = [...acc, ...source]
} else if (source instanceof Object) {
for (let [key, value] of Object.entries(source)) {
if (value instanceof Object && key in acc) {
value = objectMerges(acc[key], value)
}
acc = { ...acc, [key]: value }
}
}
}
return acc
}
function parseIncludes(yamlObject) {
return new Promise((resolve, reject) => {
let stages = [...yamlObject.stages]
let variables = { ...yamlObject.variables }
if (yamlObject.include) {
let remoteUrls = []
yamlObject.include.map(item => {
if (item.local) {
if (fs.existsSync(path.resolve(item.local))) {
const ymlObj = fs.readFileSync(path.resolve(item.local)).toString()
const includedObj = YAML.parse(ymlObj)
yamlObject = { ...yamlObject, ...includedObj }
if (includedObj.stages) {
stages = [...stages, ...includedObj.stages]
}
if (includedObj.variables) {
variables = objectMerges(variables, includedObj.variables)
}
}
} else if (item.template) {
remoteUrls.push(`https://gitlab.com/gitlab-org/gitlab/-/raw/master/lib/gitlab/ci/templates/${item.template}`)
} else if (item.remote) {
remoteUrls.push(item.remote)
} else if (typeof item === 'object') {
/** project ref: { file, project, ref } */
if (Array.isArray(item.file)) {
item.file.map(file => remoteUrls.push(`https://gitlab.com/${item.project}/-/raw/${item.ref}/${file}`))
} else {
remoteUrls.push(`https://gitlab.com/${item.project}/-/raw/${item.ref}/${item.file}`)
}
}
})
/** fetching templates from remoteUrls... */
if (remoteUrls.length > 0) {
Promise.all(remoteUrls.map((url) => fetch(url))).then((responses) => {
return Promise.all(responses.map((res) => res.text())).then((buffers) => {
return buffers.map((buffer) => {
return YAML.parse(buffer)
});
});
}).then((finalObjects) => {
yamlObject.stages = [...new Set(stages)]
finalObjects.map(m => {
if (m.stages) {
stages = [...stages, ...m.stages]
}
if (m.variables) {
variables = objectMerges(variables, m.variables)
}
yamlObject = { ...yamlObject, ...m }
})
yamlObject.stages = [...new Set(stages)]
yamlObject.variables = variables
resolve(yamlObject)
});
} else {
yamlObject.stages = [...new Set(stages)]
yamlObject.variables = variables
resolve(yamlObject)
}
} else {
resolve(yamlObject)
}
})
}
const yamlProcessor = function (yamlObject) {
if (cmdOPS == 'CREATE') {
if (!optCMD) {
index = readlineSync.keyInSelect(yamlObject.stages, `Select a stage to execute ?`, {
cancel: `${CBRIGHT}None${CRESET} - (Escape)`
})
optCMD = yamlObject.stages[index]
} else {
index = yamlObject.stages.indexOf(optCMD)
}
let dockerfileContent = ['FROM scratch']
if (index >= 0) {
const executedStage = yamlObject.stages[index]
let dockerComposeContent = { version: '3.8', services: {}, volumes: {} }
dockerComposeContent.volumes[`${getVolumeName(projectName)}`] = { external: true }
let stageExecutionChains = []
let dockerCacheVolumes = []
let dockerBaseContent = [`FROM ${getImageName(yamlObject.image)}`, 'WORKDIR /source', 'VOLUME /data', 'COPY . /source', 'CMD ls -la /source']
let dockerBasePath = `${projectName}/Dockerfile`
const baseImage = `base-${yamlObject.image.split(':')[0]}`
const baseDirName = path.dirname(path.resolve(dockerBasePath))
if (!fs.existsSync(baseDirName)) {
fs.mkdirSync(baseDirName, { recursive: true })
}
if (yamlObject.cache && yamlObject.cache.paths && yamlObject.cache.paths.length) {
dockerCacheVolumes.push()
}
fs.writeFileSync(dockerBasePath, dockerBaseContent.join('\n'))
dockerComposeContent.services[baseImage] = { build: { context: `../`, dockerfile: `${projectName}/Dockerfile`, args: {} } }
fs.writeFileSync(`${projectName}/docker-compose.yml`, YAML.stringify(dockerComposeContent))
dockerComposeContent.services = {} /** reset docker-compose services section */
delete dockerComposeContent.volumes /** remove docker-compose volumes section */
let variables = getContentArgs(yamlObject.variables || {}, { ...process.env })
function parseScriptContent(scriptLine, dockerCommands, dockerfileContent, service, localVariables) {
let scriptContent = scriptLine.startsWith('set ') ? scriptLine : getContentArgs(scriptLine, { ...process.env }, { ...localVariables })
if (scriptContent.startsWith('export ') || scriptContent.startsWith('set ')) {
let dockerOpts = scriptContent.startsWith('set ') ? 'ARG' : 'ENV'
scriptContent = scriptContent.replace('export ', '').replace('set ', '')
const argKeyValue = scriptContent.split('=')
service.build.args[`${argKeyValue[0].trim()}`] = `${argKeyValue[1].trim()}`
scriptContent = `${argKeyValue[0].trim()}="${argKeyValue[1].trim()}"`
dockerfileContent.push(`${dockerOpts} ${scriptContent}`)
} else {
dockerCommands.push(`${scriptContent}`)
}
}
Object.keys(yamlObject).map((key, idx) => {
if (yamlObject[key].extends) {
if (Array.isArray(yamlObject[key].extends)) {
} else {
yamlObject[yamlObject[key].extends].disabled = false
yamlObject[key] = { ...yamlObject[yamlObject[key].extends], ...yamlObject[key] }
yamlObject[yamlObject[key].extends].disabled = true
}
}
let localVariables = getContentArgs(yamlObject[key].variables || {}, variables)
yamlObject[key].secrets && Object.keys(yamlObject[key].secrets).map(secret => {
localVariables[secret] = "${" + secret + "}"
})
localVariables = objectMerges(variables, localVariables) /** merge global variables with local variables */
if (yamlObject[key].stage === executedStage && !yamlObject[key].disabled && !key.startsWith('.')) {
const stageName = `${idx}-${executedStage}.${key}`
dockerComposeContent.services[key] = { build: { context: `../`, dockerfile: `${projectName}/${stageName}.Dockerfile`, args: {} }, volumes: [`${getVolumeName(projectName)}:/data`] }
stageExecutionChains.push(`${stageName}`)
const localImage = `${yamlObject[key].image ? getContentArgs({ image: getImageName(yamlObject[key].image) }, localVariables).image : `${projectName.replace(/\./g, '')}_${baseImage}`}`
dockerfileContent = [`FROM ${localImage}`, 'WORKDIR /source']
yamlObject[key].dependencies && yamlObject[key].dependencies.map(deps => {
dockerfileContent.push(`FROM ${projectName.replace(/\./g, '')}_${deps}`)
})
let dockerCommands = []
let dockerBeforeCommands = []
let dockerAfterCommands = []
/**
* extends - inherit from another stage
* services - run another docker inside the build image
* needs - to execute jobs out-of-order (depend on other jobs)
*/
yamlObject[key].before_script && yamlObject[key].before_script.map(scriptLine => {
parseScriptContent(scriptLine, dockerBeforeCommands, dockerfileContent, dockerComposeContent.services[key], localVariables)
})
yamlObject[key].script && yamlObject[key].script.map(scriptLine => {
parseScriptContent(scriptLine, dockerCommands, dockerfileContent, dockerComposeContent.services[key], localVariables)
})
yamlObject[key].after_script && yamlObject[key].after_script.map(scriptLine => {
parseScriptContent(scriptLine, dockerAfterCommands, dockerfileContent, dockerComposeContent.services[key], localVariables)
})
dockerBeforeCommands.length && dockerfileContent.push(`RUN ${dockerBeforeCommands.join(' && ')}`)
dockerCommands.length && dockerfileContent.push(`RUN ${dockerCommands.join(' && ')}`)
dockerAfterCommands.length && dockerfileContent.push(`RUN ${dockerAfterCommands.join(' && ')}`)
let dockerfilePath = `${projectName}/${stageName}.Dockerfile`
const pathDirName = path.dirname(path.resolve(dockerfilePath))
if (!fs.existsSync(pathDirName)) {
fs.mkdirSync(pathDirName, { recursive: true })
}
dockerfileContent = getContentArgs(dockerfileContent, localVariables)
fs.writeFileSync(dockerfilePath, dockerfileContent.join('\n'))
}
})
let dockerComposePath = `${projectName}/docker-compose.${executedStage}.yml`
fs.writeFileSync(dockerComposePath, YAML.stringify(dockerComposeContent))
console.log(`Created ${projectName} docker-compose for stage '${optCMD}' cached to '${projectName}' volume`)
fs.writeFileSync(`pipeline.sh`, [
'#!/bin/bash',
`cd ${projectName}`,
`DOCKER_VOLUME=$(docker volume ls | grep -w "${getVolumeName(projectName)}")`,
'if [ -z "${DOCKER_VOLUME}" ]; then',
` echo "Creating new volume: ${getVolumeName(projectName)}"`,
` docker volume create --driver local --opt type=none --opt device=$PWD --opt o=bind ${getVolumeName(projectName)};`,
`fi`,
`if [ $? -eq 0 ]; then`,
` if [ -z "$1" ]; then echo "Missing argument: require stage argument to run - (ex bash pipeline.sh build [service])";`,
` elif [ -z "$2" ]; then echo "Missing argument: require stage argument to run - (ex bash pipeline.sh build eslint-sast)";`,
` else docker-compose -f docker-compose.yml -f docker-compose.$1.yml --project-name ${projectName} build $2; fi`,
`fi`
].join('\n'))
}
} else if (cmdOPS == 'LIST') {
if (!optCMD) {
yamlObject.stages.map((cmd, idx) => {
console.log(`\t- ${CPROMPT}${cmd.toLowerCase()}${CRESET}`)
})
} else {
Object.keys(yamlObject).map((key, idx) => {
if (yamlObject[key].stage === optCMD) {
const stageName = `[${optCMD}] ${key}`
console.log(`\t- ${CPROMPT}${stageName.toLowerCase()}${CRESET}`)
}
})
}
} else {
yargs.showHelp()
console.log(`\n`, ` * ${CBRIGHT}Supported command list${CRESET}:`, '\n')
OPT_COMMANDS.map((cmd, idx) => {
console.log(`\t- ${CPROMPT}${cmd.name.toLowerCase()}${CRESET} : ${cmd.desc}`)
})
console.log(`\n`)
process.exit(0)
}
}
if (yamlObject.include) {
parseIncludes(yamlObject).then(result => {
yamlProcessor(result)
})
} else {
yamlProcessor(yamlObject)
}