-
Notifications
You must be signed in to change notification settings - Fork 36
/
init.config.js
430 lines (408 loc) · 18.7 KB
/
init.config.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
'use strict';
import TYPE from '../../types/mcdev.d.js';
import Cli from './cli.js';
import File from './file.js';
import config from './config.js';
import { Util } from './util.js';
import inquirer from 'inquirer';
import path from 'node:path';
import semver from 'semver';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
/**
* CLI helper class
*/
const Init = {
/**
* helper method for this.upgradeProject that upgrades project config if needed
*
* @param {TYPE.Mcdevrc} properties config file's json
* @returns {Promise.<boolean>} returns true if worked without errors
*/
async fixMcdevConfig(properties) {
if (!properties) {
// skip if no config exists yet
return true;
}
let updateConfigNeeded = false;
const upgradeMsgs = [`Upgrading existing ${Util.configFileName}:`];
const missingFields = await config.checkProperties(properties, true);
const defaultProps = await config.getDefaultProperties();
if (missingFields.length) {
for (const fieldName of missingFields) {
switch (fieldName) {
case 'marketList': {
if (properties.marketBulk) {
upgradeMsgs.push(`- ✔️ converted 'marketBulk' to '${fieldName}'`);
properties[fieldName] = properties.marketBulk;
delete properties.marketBulk;
} else {
upgradeMsgs.push(`- ✔️ added '${fieldName}'`);
this._updateLeaf(properties, defaultProps, fieldName);
}
break;
}
case 'directories.docs': {
if (properties.directories.badKeys) {
delete properties.directories.badKeys;
upgradeMsgs.push(`- ✋ removed 'directories.badKeys'`);
}
if (properties.directories.dataExtension) {
File.removeSync(properties.directories.dataExtension);
delete properties.directories.dataExtension;
upgradeMsgs.push(`- ✋ removed 'directories.dataExtension'`);
}
if (properties.directories.deltaPackage) {
delete properties.directories.deltaPackage;
upgradeMsgs.push(`- ✋ removed 'directories.deltaPackage'`);
}
if (properties.directories.dataextension) {
delete properties.directories.dataextension;
upgradeMsgs.push(`- ✋ removed 'directories.dataextension'`);
}
if (properties.directories.roles) {
delete properties.directories.roles;
upgradeMsgs.push(`- ✋ removed 'directories.roles'`);
}
if (properties.directories.users) {
delete properties.directories.users;
upgradeMsgs.push(`- ✋ removed 'directories.users'`);
}
this._updateLeaf(properties, defaultProps, fieldName);
upgradeMsgs.push(`- ✔️ added '${fieldName}'`);
break;
}
case 'metaDataTypes.documentOnRetrieve': {
if (properties.options.documentOnRetrieve) {
this._updateLeaf(properties, defaultProps, fieldName);
} else {
properties.metaDataTypes.documentOnRetrieve = [];
}
delete properties.options.documentOnRetrieve;
upgradeMsgs.push(
`- ✔️ converted 'options.documentOnRetrieve' to '${fieldName}'`
);
break;
}
case 'options.deployment.commitHistory': {
if (properties.options.commitHistory) {
upgradeMsgs.push(
`- ✔️ converted 'options.commitHistory' to '${fieldName}'`
);
properties.options.deployment.commitHistory =
properties.options.commitHistory;
delete properties.options.commitHistory;
} else {
upgradeMsgs.push(`- ✔️ added '${fieldName}'`);
this._updateLeaf(properties, defaultProps, fieldName);
}
break;
}
case 'options.exclude': {
if (properties.options.filter) {
upgradeMsgs.push(`- ✔️ converted 'options.filter' to '${fieldName}'`);
properties.options.exclude = properties.options.filter;
delete properties.options.filter;
} else {
upgradeMsgs.push(`- ✔️ added '${fieldName}'`);
this._updateLeaf(properties, defaultProps, fieldName);
}
break;
}
case 'version': {
// do nothing other than ensure we re-save the config (with the new version)
upgradeMsgs.push(`- ✔️ version updated`);
break;
}
default: {
this._updateLeaf(properties, defaultProps, fieldName);
upgradeMsgs.push(`- ✔️ added '${fieldName}'`);
}
}
}
updateConfigNeeded = true;
}
// ensure we document dataExtensions and automations on retrieve as they should now be in the retrieve folder
this._updateLeaf(properties, defaultProps, 'metaDataTypes.documentOnRetrieve');
upgradeMsgs.push(
`- ✔️ updated 'metaDataTypes.documentOnRetrieve' to include all available types`
);
// check if metaDataTypes.retrieve is set to default values and if not, launch selectTypes
const defaultRetrieveArr = Util.getRetrieveTypeChoices();
let reselectDefaultRetrieve = false;
const toBeRemovedTypes = properties.metaDataTypes.retrieve.filter(
(type) => !defaultRetrieveArr.includes(type)
);
const toBeAddedTypes = defaultRetrieveArr.filter(
(type) => !properties.metaDataTypes.retrieve.includes(type)
);
if (toBeRemovedTypes.length || toBeAddedTypes.length) {
reselectDefaultRetrieve = true;
updateConfigNeeded = true;
}
// move to version 4 uses integers for MIDs
for (const cred in properties.credentials) {
properties.credentials[cred].eid = Number.parseInt(properties.credentials[cred].eid);
for (const bu in properties.credentials[cred].businessUnits) {
properties.credentials[cred].businessUnits[bu] = Number.parseInt(
properties.credentials[cred].businessUnits[bu]
);
}
updateConfigNeeded = true;
upgradeMsgs.push(`- ✔️ updated Business Unit format (${cred})`);
}
// update config
if (updateConfigNeeded) {
for (const msg of upgradeMsgs) {
Util.logger.info(msg);
}
if (reselectDefaultRetrieve) {
// run selectTypes here as it _also_ runs File.saveConfigFile()
Util.logger.warn(
'Your metaDataTypes.retrieve list is not set to standard values. Resetting config.'
);
Util.logger.warn('');
if (toBeAddedTypes.length) {
Util.logger.warn('Adding types:');
for (const type of toBeAddedTypes) {
Util.logger.warn(` - ${type}`);
}
Util.logger.warn('');
}
if (toBeRemovedTypes.length) {
Util.logger.warn('Removing types:');
for (const type of toBeRemovedTypes) {
Util.logger.warn(` - ${type}`);
}
Util.logger.warn('');
}
await Cli.selectTypes(properties, defaultRetrieveArr);
} else {
// update config if anything else was changed but no re-selection of retrieve-types was triggered
await File.saveConfigFile(properties);
}
} else {
Util.logger.info(`✔️ No problems found in existing ${Util.configFileName}`);
}
return true;
},
/**
* handles creation/update of all config file from the boilerplate
*
* @param {string} versionBeforeUpgrade 'x.y.z'
* @returns {Promise.<boolean>} status of config file creation
*/
async createIdeConfigFiles(versionBeforeUpgrade) {
Util.logger.info('Checking configuration files (existing files will not be changed):');
const creationLog = [];
await File.ensureDir('deploy/');
await File.ensureDir('src/cloudPages');
const relevantForcedUpdates = await this._getForcedUpdateList(versionBeforeUpgrade);
// copy in .gitignore (cant be retrieved via npm install directly)
const gitignoreFileName = path.resolve(
__dirname,
Util.boilerplateDirectory,
'gitignore-template'
);
if (await File.pathExists(gitignoreFileName)) {
const fileContent = await File.readFile(gitignoreFileName, 'utf8');
creationLog.push(
await this._createIdeConfigFile(
['.' + path.sep, '', '.gitignore'],
relevantForcedUpdates,
fileContent
)
);
} else {
Util.logger.debug(`Dependency file not found in ${gitignoreFileName}`);
return false;
}
// load file list from boilerplate dir and initiate copy process
const boilerPlateFilesPath = path.resolve(__dirname, Util.boilerplateDirectory, 'files');
// ! do not switch to readDirectories before merging the two custom methods. Their logic is different!
const directories = await File.readDirectoriesSync(boilerPlateFilesPath, 10, false);
for (const subdir of directories) {
// walk thru the root of our boilerplate-files directory and all sub folders
const curDir = path.join(boilerPlateFilesPath, subdir);
for (const file of await File.readdir(curDir)) {
// read all files in these directories
if (!(await File.lstat(path.join(curDir, file))).isDirectory()) {
// filter entries that are actually folders
const fileArr = file.split('.');
const ext = '.' + fileArr.pop();
// awaiting the result here due to interactive optional overwrite
creationLog.push(
await this._createIdeConfigFile(
[subdir + path.sep, fileArr.join('.'), ext],
relevantForcedUpdates
)
);
}
}
}
if (creationLog.includes(false) && creationLog.includes(true)) {
Util.logger.warn('✋ Configuration files creation partially failed.');
return true;
} else if (creationLog.includes(false)) {
Util.logger.error('❌ Configuration files creation failed.');
return false;
} else {
Util.logger.info('✔️ Configuration files done.');
return true;
}
},
/**
* recursive helper for {@link Init.fixMcdevConfig} that adds missing settings
*
* @param {object} propertiersCur current sub-object of project settings
* @param {object} defaultPropsCur current sub-object of default settings
* @param {string} fieldName dot-concatenated object-path that needs adding
* @returns {void}
*/
_updateLeaf(propertiersCur, defaultPropsCur, fieldName) {
if (fieldName.includes('.')) {
const fieldNameArr = fieldName.split('.');
const curKey = fieldNameArr[0];
if (!propertiersCur[curKey]) {
propertiersCur[curKey] = {};
}
fieldNameArr.splice(0, 1);
this._updateLeaf(
propertiersCur[curKey],
defaultPropsCur[curKey],
fieldNameArr.join('.')
);
} else {
propertiersCur[fieldName] = defaultPropsCur[fieldName];
}
},
/**
* returns list of files that need to be updated
*
* @param {string} projectVersion version found in config file of the current project
* @returns {Promise.<string[]>} relevant files with path that need to be updated
*/
async _getForcedUpdateList(projectVersion) {
// list of files that absolutely need to get overwritten, no questions asked, when upgrading from a version lower than the given.
let forceIdeConfigUpdate;
const relevantForcedUpdates = [];
if (await File.pathExists(Util.configFileName)) {
forceIdeConfigUpdate = File.readJsonSync(
path.resolve(__dirname, Util.boilerplateDirectory, 'forcedUpdates.json')
);
// return all if no project version was found or only changes from "newer" versions otherwise
for (const element of forceIdeConfigUpdate) {
if (!projectVersion || semver.gt(element.version, projectVersion)) {
relevantForcedUpdates.push(
// adapt it for local file systems
...element.files.map((item) => path.normalize(item))
);
} else {
continue;
}
}
}
return relevantForcedUpdates;
},
/**
* handles creation/update of one config file from the boilerplate at a time
*
* @param {string[]} fileNameArr 0: path, 1: filename, 2: extension with dot
* @param {string[]} relevantForcedUpdates if fileNameArr is in this list we require an override
* @param {string} [boilerplateFileContent] in case we cannot copy files 1:1 this can be used to pass in content
* @returns {Promise.<boolean>} install successful or error occured
*/
async _createIdeConfigFile(fileNameArr, relevantForcedUpdates, boilerplateFileContent) {
let update = false;
const fileName = fileNameArr.join('');
const boilerplateFileName = path.resolve(
__dirname,
Util.boilerplateDirectory,
'files',
fileName
);
boilerplateFileContent ||= await File.readFile(boilerplateFileName, 'utf8');
if (await File.pathExists(fileName)) {
const existingFileContent = await File.readFile(fileName, 'utf8');
if (existingFileContent === boilerplateFileContent) {
Util.logger.info(`- ✔️ ${fileName} found. No update needed`);
return true;
}
if (relevantForcedUpdates.includes(path.normalize(fileName))) {
Util.logger.info(
`- ✋ ${fileName} found but an update is required. Commencing with override:`
);
} else {
Util.logger.info(
`- ✋ ${fileName} found with differences to the new standard version. We recommend updating it.`
);
if (!Util.skipInteraction) {
const responses = await inquirer.prompt([
{
type: 'confirm',
name: 'overrideFile',
message: 'Would you like to update (override) it?',
default: true,
},
]);
if (!responses.overrideFile) {
// skip override without error
return true;
}
}
}
update = true;
// ensure our update is not leading to data loss in case config files were not versioned correctly by the user
await File.rename(fileName, fileName + '.BAK');
}
const saveStatus = await File.writeToFile(
fileNameArr[0],
fileNameArr[1],
fileNameArr[2].slice(1),
boilerplateFileContent
);
if (saveStatus) {
Util.logger.info(
`- ✔️ ${fileName} ${
update
? `updated (we created a backup of the old file under ${fileName + '.BAK'})`
: 'created'
}`
);
return true;
} else {
Util.logger.warn(`- ❌ ${fileName} ${update ? 'update' : 'creation'} failed`);
return false;
}
},
/**
* helper method for this.upgradeProject that upgrades project config if needed
*
* @returns {Promise.<boolean>} returns true if worked without errors
*/
async upgradeAuthFile() {
if (await File.pathExists(Util.authFileName)) {
const existingAuth = await File.readJSON(Util.authFileName);
// if has credentials key then is old format
if (existingAuth.credentials) {
const newAuth = {};
for (const cred in existingAuth.credentials) {
newAuth[cred] = {
client_id: existingAuth.credentials[cred].clientId,
client_secret: existingAuth.credentials[cred].clientSecret,
auth_url: `https://${existingAuth.credentials[cred].tenant}.auth.marketingcloudapis.com/`,
account_id: Number.parseInt(existingAuth.credentials[cred].eid),
};
}
await File.writeJSONToFile(
'./',
Util.authFileName.replace(/(.json)+$/, ''),
newAuth
);
Util.logger.info(`- ✔️ upgraded credential file`);
}
}
return true;
},
};
export default Init;