/
utils.js
227 lines (201 loc) · 5.93 KB
/
utils.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
import shelljs from 'shelljs'
import chalk from 'chalk'
import path from 'path'
import ora from 'ora'
import { fileExists, createFile, readFile } from './file-utils'
async function inExistingProject(folderPath) {
const packageJsonExists = await fileExists(
path.join(process.projectDir, folderPath, 'package.json')
)
return packageJsonExists
}
export function diff(x, y) {
return x.filter((a) => !y.includes(a))
}
export async function createReactApp(folderPath) {
return new Promise(async (resolve, _) => {
createApp(folderPath, 'https://github.com/sasjs/react-seed-app.git')
return resolve()
})
}
export async function createAngularApp(folderPath) {
return new Promise(async (resolve, _) => {
createApp(folderPath, 'https://github.com/sasjs/angular-seed-app.git')
return resolve()
})
}
export async function createMinimalApp(folderPath) {
return new Promise(async (resolve, _) => {
createApp(folderPath, 'https://github.com/sasjs/minimal-seed-app.git')
return resolve()
})
}
function createApp(folderPath, repoUrl, installDependencies = true) {
const spinner = ora(
chalk.greenBright('Creating web app in', chalk.cyanBright(folderPath))
)
spinner.start()
shelljs.exec(`cd ${folderPath} && git clone ${repoUrl} . && rm -rf .git`, {
silent: true
})
spinner.stop()
if (installDependencies) {
spinner.text = chalk.greenBright('Installing dependencies...')
spinner.start()
shelljs.exec(`cd ${folderPath} && npm install`, {
silent: true
})
spinner.stop()
}
}
export async function setupNpmProject(folderPath) {
return new Promise(async (resolve, _) => {
const isExistingProject = await inExistingProject(folderPath)
if (!isExistingProject) {
console.log(
chalk.greenBright(
'Initialising NPM project in',
chalk.cyanBright(folderPath)
)
)
shelljs.exec(`cd ${folderPath} && npm init --yes`, {
silent: true
})
} else {
console.log(chalk.greenBright('Existing NPM project detected.\n'))
}
console.log(chalk.greenBright('Installing @sasjs/core'))
shelljs.exec(`cd ${folderPath} && npm i @sasjs/core --save`, {
silent: true
})
return resolve()
})
}
export async function setupGitIgnore(folderPath) {
const gitIgnoreFilePath = path.join(
process.projectDir,
folderPath,
'.gitignore'
)
const gitIgnoreExists = await fileExists(gitIgnoreFilePath)
if (gitIgnoreExists) {
const gitIgnoreContent = await readFile(gitIgnoreFilePath)
await createFile(gitIgnoreFilePath, `${gitIgnoreContent}\nsasjsbuild/\n`)
console.log(chalk.greenBright('Existing .gitignore has been updated.'))
} else {
shelljs.exec(`cd ${folderPath} && git init`, {
silent: true
})
await createFile(gitIgnoreFilePath, 'node_modules/\nsasjsbuild/\n.env\n')
console.log(chalk.greenBright('.gitignore file has been created.'))
}
}
export async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array)
}
}
/**
* Removes comments from a given block of text.
* Preserves single line block comments and inline comments.
* @param {string} text - the text to remove comments from.
*/
export function removeComments(text) {
if (!text) return ''
const lines = text
.replace(/\r\n/g, '\n')
.split('\n')
.map((l) => l.trimEnd())
const linesWithoutComment = []
let inCommentBlock = false
lines.forEach((line) => {
if (line.includes('/*') && line.includes('*/')) {
linesWithoutComment.push(line)
} else {
if (line.startsWith('/*') && !line.endsWith('*/')) {
inCommentBlock = true
}
if (!inCommentBlock) {
linesWithoutComment.push(line)
}
if (line.endsWith('*/') && !line.includes('/*') && inCommentBlock) {
inCommentBlock = false
}
}
})
return linesWithoutComment.filter((l) => !!l.trim()).join('\n')
}
export function getUniqServicesObj(services) {
let returnObj = {}
if (!services) return returnObj
services.forEach((service) => {
const serviceName = service.split('/').pop()
if (returnObj[serviceName]) return
returnObj[serviceName] = service
})
return returnObj
}
export async function executeShellScript(filePath, logFilePath) {
return new Promise(async (resolve, reject) => {
const result = shelljs.exec(`bash ${filePath}`, {
silent: true,
async: false
})
if (result.code) {
console.error(chalk.redBright('Error:\n'), chalk.red(result.stderr))
reject(result.code)
throw new Error(chalk.cyanBright('Ended with code ' + result.code))
} else {
if (logFilePath) {
await createFile(logFilePath, result.stdout)
}
resolve(result.stdout)
}
})
}
export function chunk(text, maxLength = 220) {
if (text.length <= maxLength) {
return [text]
}
return `${text}`
.match(new RegExp('.{1,' + maxLength + '}', 'g'))
.filter((m) => !!m)
}
export async function getVariable(name, target) {
let value = process.env[name]
if (value) {
return value
}
value = target && target.tgtDeployVars ? target.tgtDeployVars[name] : null
if (value) {
return value
}
value = target && target.tgtBuildVars ? target.tgtBuildVars[name] : null
if (value) {
return value
}
return null
}
/**
* Extracts plain text job log from fetched json log
* @param {object} logJson
*/
export function parseLogLines(logJson) {
let logLines = ''
for (let item of logJson.items) {
logLines += `${item.line}\n`
}
return logLines
}
/**
* Returns a timestamp in YYYYMMDDSS format
*/
export function generateTimestamp() {
const date = new Date()
const timestamp = `${date.getUTCFullYear()}${
date.getUTCMonth() + 1
}${date.getUTCDate()}${date.getUTCHours()}${date.getUTCMinutes()}${date.getUTCSeconds()}`
return timestamp
}
export const arrToObj = (arr) =>
arr.reduce((o, key) => ({ ...o, [key]: key }), {})