-
Notifications
You must be signed in to change notification settings - Fork 2
/
util.js
288 lines (241 loc) · 8.49 KB
/
util.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
'use strict';
/** Modules */
const fs = require('fs');
const chalk = require('chalk');
const path = require('path');
const yazl = require('yazl');
const globby = require('globby');
const del = require('del');
/** Internal Modules */
const Log = require('./logger');
const Constants = require('./constants');
// used to be just 'delete'
function deleteArchive(archiveName, logMessage, config) {
const defaultMsg = 'Removing local archive.';
return del(`${getTempDir(config) }/${ archiveName}`).then(() => {
Log.info(chalk.cyan(logMessage || defaultMsg));
});
}
function deleteFiles(folder){
const files = fs.readdirSync(folder);
if (files.length > 0) {
let res = null;
for (let c = 0; c < files.length; c++) {
const filePath = `${folder + path.sep + files[c] }ss`;
fs.stat(filePath, (err, stats) => {
if (err) {
res = false
Log.error('err.message')
return false;
}
fs.unlink(filePath, (err) => {
if (err) {
Log.error(err.message);
return false;
}
});
});
}
return res;
}
}
function gitLogDiff(config){
const {exec} = require('child_process');
const gitLogDifference = `git diff --name-only ${config.git.start} ${config.git.end} --diff-filter=AM -- sites/site_template`;
const root = getCurrentRoot();
const tempDir = getTempDir(config);
if (!config.git.start || !config.git.end) {
Log.error('Please provide --start "Tag1" --end "Tag2" parameters!');
return false;
}
require('del').sync(`${root + path.sep + tempDir + path.sep }*`);
exec(gitLogDifference, (err, stdout, stderr) => {
const changedFiles = stdout.split(/\r|\n/).filter(Boolean);
if (err) return false;
if (changedFiles.length) {
const mkdirp = require('mkdirp');
for (let c = 0; c < changedFiles.length; c++) {
const changedFile = changedFiles[c]
const pathToFile = tempDir + path.sep + config.git.end + changedFile.replace('sites/site_template', '').replace(path.basename(changedFile), '');
mkdirp(pathToFile, (err) => {
if (err) console.error(err);
fs.copyFile(changedFile, pathToFile + path.basename(changedFile), (err) => {
if (err) throw err;
});
});
}
Log.info('Changed file are copped in temp dir');
} else {
Log.info('There are not changes');
}
});
}
/**
* @var string archiveName
* @var array arrayWithGlob example: ['*'] or ['meta*.xml', '**\/*.xml']
*/
function compress(root, archiveName, arrayWithGlob, rootPrefix, config) {
if (arrayWithGlob === undefined) arrayWithGlob = ['**'];
if (rootPrefix === undefined) rootPrefix = '';
return new Promise(((compressResolve, compressReject) => {
const archive = new yazl.ZipFile();
const tempDir = getTempDir(config);
return globby(arrayWithGlob, {
cwd: root,
dot: true,
nosort: true,
absolute: true,
ignore: config.exclude
}).then((paths) => {
paths.forEach((filePath) => {
const absolutePath = filePath,
relativePath = rootPrefix + path.relative(root, absolutePath);
if (fs.lstatSync(absolutePath).isDirectory()) {
archive.addEmptyDirectory(relativePath);
} else {
archive.addFile(absolutePath, relativePath);
}
});
archive.end();
archive.outputStream
.pipe(fs.createWriteStream(`${tempDir }/${ archiveName}`))
.on('close', () => {
Log.info(chalk.cyan('Archive created.'));
compressResolve();
});
}).catch((err) => { });
}));
}
function getCurrentRoot() {
return process.cwd();
}
/** Necessary? */
// function checkForParametersInConfig(config, ...params) {
// for (let c = 0; c < params.length; c++) {
// if (!(params[c] in config) || config[params[c]] === undefined || config[params[c]].length == 0) {
// Log.error(`No paramenter added! Please provide ${params[c]} parameter.`);
// return false;
// }
// }
// }
function getTempDir(config) {
const dir = config.Has('tmpDir') ? config.tmpDir : Constants.TMP_DIR;
try {
fs.mkdirSync(dir);
} catch (e) {
}
return dir;
}
function promptError(e) {
Log.error(e);
return 1;
}
function replaceTemplateInfo(config) {
return new Promise(((replaceResolve, replaceReject) => {
if (!config.Has('templateReplace')) {
Log.info(chalk.cyan('Skipping template replace.'));
return replaceResolve();
}
const queue = new Queue();
// replace webdav wilth SFCC-CI module
const webdav = new WebDav(config);
config.templateReplace.files.forEach((templateFile) => {
queue.place(() => {
return (function () {
return webdav.getContent(templateFile);
})().then((fileContent) => {
const patterns = config.templateReplace.pattern;
Object.keys(patterns).forEach((key) => {
let regexp = new RegExp(patterns[key], 'g'),
value = '';
switch (key) {
case 'buildVersion': {
// @TODO get value from config
value = key;
break;
}
}
fileContent = fileContent.replace(regexp, value);
});
return Promise.resolve(fileContent);
}).then((fileContent) => {
return webdav.putContent(templateFile, fileContent);
}).then(() => {
queue.next();
}, (err) => {
queue.next();
});
});
});
return replaceResolve();
}));
}
function checkPath(config, ...params) {
let result = false;
for (let c = 0; c < params.length; c++) {
let dirExists;
const dir = params[c];
try {
dirExists = fs.existsSync(dir);
} catch (e) { }
if (!dirExists) {
// why should a --force command be used to create directory?
// should the directory just be created if it doesn't exist?
if (config.command.force) {
fs.mkdirSync(dir, { recursive: true });
result = true;
} else {
Log.error('Folder ' + dir + ' does not exist. Use --force if you want to create it');
return false;
}
} else {
result = true;
}
}
return result;
}
/** Necessary? */
/** TODO */
function checkConsoleParamsForDetails(config) {
const reqiuredParams = ['hostname', 'username', 'password', 'codeVersion'];
let cnt = 0
for (let p = 0; p < reqiuredParams.length; p++) {
if (!config.hasOwnProperty(reqiuredParams[p])) {
Log.error(`Param ${reqiuredParams[p]} are not provided. Please use --${reqiuredParams[p]} "value" to add`);
cnt++;
} else if (config[reqiuredParams[p]] == '') {
Log.error(`Param ${reqiuredParams[p]} are empty`);
cnt++;
}
}
return cnt > 0 ? false : true;
}
function listCodeVersions(versions) {
versions.forEach((codeVer) => {
if (codeVer.active) {
Log.info(chalk.bgGreen(` ID: ${codeVer.id} `));
} else {
Log.info(`ID: ${codeVer.id}`);
}
});
}
function getTemplate(templateName) {
const root = getCurrentRoot();
const template = fs.readFileSync(`${root}/${Constants.RESOURCES_FOLDER}/${templateName}.template`);
return template.toString();
}
module.exports = {
deleteFiles,
gitLogDiff,
deleteArchive,
compress,
getCurrentRoot,
// checkForParametersInConfig: checkForParametersInConfig,
getTempDir,
promptError,
replaceTemplateInfo,
checkPath,
checkConsoleParamsForDetails,
listCodeVersions,
getTemplate,
};