-
Notifications
You must be signed in to change notification settings - Fork 36
/
index.js
928 lines (899 loc) · 36.8 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
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
'use strict';
const TYPE = require('../types/mcdev.d');
const Util = require('./util/util');
const auth = require('./util/auth');
const File = require('./util/file');
const config = require('./util/config');
const Init = require('./util/init');
const InitGit = require('./util/init.git');
const Cli = require('./util/cli');
const DevOps = require('./util/devops');
const BuHelper = require('./util/businessUnit');
const Builder = require('./Builder');
const Deployer = require('./Deployer');
const MetadataTypeInfo = require('./MetadataTypeInfo');
const MetadataTypeDefinitions = require('./MetadataTypeDefinitions');
const Retriever = require('./Retriever');
const cache = require('./util/cache');
/**
* main class
*/
class Mcdev {
/**
* helper method to use unattended mode when including mcdev as a package
*
* @param {boolean | TYPE.skipInteraction} [skipInteraction] signals what to insert automatically for things usually asked via wizard
* @returns {void}
*/
static setSkipInteraction(skipInteraction) {
Util.skipInteraction = skipInteraction;
}
/**
* configures what is displayed in the console
*
* @param {object} argv list of command line parameters given by user
* @param {boolean} [argv.silent] only errors printed to CLI
* @param {boolean} [argv.verbose] chatty user CLI output
* @param {boolean} [argv.debug] enables developer output & features
* @returns {void}
*/
static setLoggingLevel(argv) {
Util.setLoggingLevel(argv);
}
/**
* allows setting system wide / command related options
*
* @param {object} argv list of command line parameters given by user
* @returns {void}
*/
static setOptions(argv) {
const knownOptions = [
'api',
'changeKeyField',
'changeKeyValue',
'commitHistory',
'filter',
'fromRetrieve',
'json',
'like',
'noLogFile',
'refresh',
'execute',
'skipInteraction',
];
for (const option of knownOptions) {
if (argv[option] !== undefined) {
Util.OPTIONS[option] = argv[option];
}
}
// set logging level
const loggingOptions = ['silent', 'verbose', 'debug'];
for (const option of loggingOptions) {
if (argv[option] !== undefined) {
this.setLoggingLevel(argv);
break;
}
}
// set skip interaction
if (argv.skipInteraction !== undefined) {
this.setSkipInteraction(argv.skipInteraction);
}
}
/**
* handler for 'mcdev createDeltaPkg
*
* @param {object} argv yargs parameters
* @param {string} [argv.range] git commit range
into deploy directory
* @param {string} [argv.filter] filter file paths that start with any
* @param {TYPE.DeltaPkgItem[]} [argv.diffArr] list of files to include in delta package (skips git diff when provided)
* @returns {Promise.<TYPE.DeltaPkgItem[]>} list of changed items
*/
static async createDeltaPkg(argv) {
Util.startLogger();
Util.logger.info('Create Delta Package ::');
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
return null;
}
return argv.filter
? // get source market and source BU from config
DevOps.getDeltaList(properties, argv.range, true, argv.filter, argv.commitHistory)
: // If no custom filter was provided, use deployment marketLists & templating
DevOps.buildDeltaDefinitions(
properties,
argv.range,
argv.diffArr,
argv.commitHistory
);
}
/**
* @returns {Promise} .
*/
static async selectTypes() {
Util.startLogger();
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
return null;
}
await Cli.selectTypes(properties);
}
/**
* @returns {object[]} list of supported types with their apiNames
*/
static explainTypes() {
return Cli.explainTypes();
}
/**
* @returns {Promise.<boolean>} success flag
*/
static async upgrade() {
Util.startLogger();
const properties = await config.getProperties();
if (!properties) {
Util.logger.error('No config found. Please run mcdev init');
return false;
}
if ((await InitGit.initGitRepo()).status === 'error') {
return false;
}
return Init.upgradeProject(properties, false);
}
/**
* Retrieve all metadata from the specified business unit into the local file system.
*
* @param {string} businessUnit references credentials from properties.json
* @param {TYPE.SupportedMetadataTypes[]|TYPE.TypeKeyCombo} [selectedTypesArr] limit retrieval to given metadata type
* @param {string[]} [keys] limit retrieval to given metadata key
* @param {boolean} [changelogOnly] skip saving, only create json in memory
* @returns {Promise.<object>} -
*/
static async retrieve(businessUnit, selectedTypesArr, keys, changelogOnly) {
Util.startLogger();
Util.logger.info('mcdev:: Retrieve');
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
// return null here to avoid seeing 2 error messages for the same issue
return null;
}
// assume a list was passed in and check each entry's validity
if (selectedTypesArr) {
for (const selectedType of Array.isArray(selectedTypesArr)
? selectedTypesArr
: Object.keys(selectedTypesArr)) {
if (!Util._isValidType(selectedType)) {
return;
}
}
}
if (businessUnit === '*') {
Util.logger.info('\n :: Retrieving all BUs for all credentials');
let counter_credTotal = 0;
for (const cred in properties.credentials) {
Util.logger.info(`\n :: Retrieving all BUs for ${cred}`);
let counter_credBu = 0;
for (const bu in properties.credentials[cred].businessUnits) {
await this._retrieveBU(cred, bu, selectedTypesArr, keys);
counter_credBu++;
Util.startLogger(true);
}
counter_credTotal += counter_credBu;
Util.logger.info(`\n :: ${counter_credBu} BUs for ${cred}\n`);
}
Util.logger.info(`\n :: ${counter_credTotal} BUs in total\n`);
} else {
let [cred, bu] = businessUnit ? businessUnit.split('/') : [null, null];
// to allow all-BU via user selection we need to run this here already
if (
properties.credentials &&
(!properties.credentials[cred] ||
(bu !== '*' && !properties.credentials[cred].businessUnits[bu]))
) {
const buObject = await Cli.getCredentialObject(
properties,
cred === null ? null : cred + '/' + bu,
null,
true
);
if (buObject === null) {
return;
} else {
cred = buObject.credential;
bu = buObject.businessUnit;
}
}
if (bu === '*' && properties.credentials && properties.credentials[cred]) {
Util.logger.info(`\n :: Retrieving all BUs for ${cred}`);
let counter_credBu = 0;
for (const bu in properties.credentials[cred].businessUnits) {
await this._retrieveBU(cred, bu, selectedTypesArr, keys);
counter_credBu++;
Util.startLogger(true);
}
Util.logger.info(`\n :: ${counter_credBu} BUs for ${cred}\n`);
} else {
// retrieve a single BU; return
const retrieveChangelog = await this._retrieveBU(
cred,
bu,
selectedTypesArr,
keys,
changelogOnly
);
if (changelogOnly) {
return retrieveChangelog;
}
Util.logger.info(`:: Done\n`);
}
}
}
/**
* helper for {@link Mcdev.retrieve}
*
* @private
* @param {string} cred name of Credential
* @param {string} bu name of BU
* @param {TYPE.SupportedMetadataTypes[]|TYPE.TypeKeyCombo} [selectedTypesArr] limit retrieval to given metadata type/subtype
* @param {string[]} [keys] limit retrieval to given metadata key
* @param {boolean} [changelogOnly] skip saving, only create json in memory
* @returns {Promise.<object>} ensure that BUs are worked on sequentially
*/
static async _retrieveBU(cred, bu, selectedTypesArr, keys, changelogOnly) {
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
return null;
}
const buObject = await Cli.getCredentialObject(
properties,
cred === null ? null : cred + '/' + bu,
null,
true
);
if (buObject !== null) {
cache.initCache(buObject);
cred = buObject.credential;
bu = buObject.businessUnit;
// clean up old folders after types were renamed
// TODO: Remove renamedTypes-logic 6 months after version 5 release
const renamedTypes = {
emailSend: 'emailSendDefinition',
event: 'eventDefinition',
fileLocation: 'ftpLocation',
journey: 'interaction',
triggeredSend: 'triggeredSendDefinition',
user: 'accountUser',
};
Util.logger.info(`\n :: Retrieving ${cred}/${bu}\n`);
const retrieveTypesArr = [];
if (selectedTypesArr) {
for (const selectedType of Array.isArray(selectedTypesArr)
? selectedTypesArr
: Object.keys(selectedTypesArr)) {
const [type, subType] = Util.getTypeAndSubType(selectedType);
const removePathArr = [properties.directories.retrieve, cred, bu, type];
if (
type &&
subType &&
MetadataTypeInfo[type] &&
MetadataTypeDefinitions[type].subTypes.includes(subType)
) {
// Clear output folder structure for selected sub-type
removePathArr.push(subType);
retrieveTypesArr.push(selectedType);
} else if (type && MetadataTypeInfo[type]) {
// Clear output folder structure for selected type
retrieveTypesArr.push(type);
}
if (!keys) {
// dont delete directories if we are just re-retrieving a single file
await File.remove(File.normalizePath(removePathArr));
// clean up old folders after types were renamed
// TODO: Remove this with version 5.0.0
if (renamedTypes[type]) {
await File.remove(
File.normalizePath([
properties.directories.retrieve,
cred,
bu,
renamedTypes[type],
])
);
}
}
}
}
if (!retrieveTypesArr.length) {
// assume no type was given and config settings are used instead:
// Clear output folder structure
File.removeSync(File.normalizePath([properties.directories.retrieve, cred, bu]));
// removes subtypes and removes duplicates
retrieveTypesArr.push(
...new Set(properties.metaDataTypes.retrieve.map((type) => type.split('-')[0]))
);
for (const selectedType of retrieveTypesArr) {
const test = Util._isValidType(selectedType);
if (!test) {
Util.logger.error(
`Please remove the type ${selectedType} from your ${Util.configFileName}`
);
return;
}
}
}
const retriever = new Retriever(properties, buObject);
try {
// await is required or the calls end up conflicting
const retrieveChangelog = await retriever.retrieve(
retrieveTypesArr,
Array.isArray(selectedTypesArr) ? keys : selectedTypesArr,
null,
changelogOnly
);
if (changelogOnly) {
return retrieveChangelog;
}
} catch (ex) {
Util.logger.errorStack(ex, 'mcdev.retrieve failed');
}
}
}
/**
* Deploys all metadata located in the 'deploy' directory to the specified business unit
*
* @param {string} businessUnit references credentials from properties.json
* @param {TYPE.SupportedMetadataTypes[]} [selectedTypesArr] limit deployment to given metadata type
* @param {string[]} [keyArr] limit deployment to given metadata keys
* @param {boolean} [fromRetrieve] optionally deploy whats defined via selectedTypesArr + keyArr directly from retrieve folder instead of from deploy folder
* @returns {Promise.<Object.<string,TYPE.MultiMetadataTypeMap>>} deployed metadata per BU (first key: bu name, second key: metadata type)
*/
static async deploy(businessUnit, selectedTypesArr, keyArr, fromRetrieve = false) {
Util.startLogger();
return Deployer.deploy(businessUnit, selectedTypesArr, keyArr, fromRetrieve);
}
/**
* Creates template file for properties.json
*
* @param {string} [credentialsName] identifying name of the installed package / project
* @returns {Promise.<void>} -
*/
static async initProject(credentialsName) {
Util.startLogger();
Util.logger.info('mcdev:: Setting up project');
const properties = await config.getProperties(!!credentialsName, true);
await Init.initProject(properties, credentialsName);
}
/**
* Clones an existing project from git repository and installs it
*
* @returns {Promise.<void>} -
*/
static async joinProject() {
Util.startLogger();
Util.logger.info('mcdev:: Joining an existing project');
await Init.joinProject();
}
/**
* Refreshes BU names and ID's from MC instance
*
* @param {string} credentialsName identifying name of the installed package / project
* @returns {Promise.<void>} -
*/
static async findBUs(credentialsName) {
Util.startLogger();
Util.logger.info('mcdev:: Load BUs');
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
return null;
}
const buObject = await Cli.getCredentialObject(properties, credentialsName, true);
if (buObject !== null) {
BuHelper.refreshBUProperties(properties, buObject.credential);
}
}
/**
* Creates docs for supported metadata types in Markdown and/or HTML format
*
* @param {string} businessUnit references credentials from properties.json
* @param {string} type metadata type
* @returns {Promise.<void>} -
*/
static async document(businessUnit, type) {
Util.startLogger();
Util.logger.info('mcdev:: Document');
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
return null;
}
if (type && !MetadataTypeInfo[type]) {
Util.logger.error(`:: '${type}' is not a valid metadata type`);
return;
}
try {
const parentBUOnlyTypes = ['user', 'role'];
const buObject = await Cli.getCredentialObject(
properties,
parentBUOnlyTypes.includes(type) ? businessUnit.split('/')[0] : businessUnit,
parentBUOnlyTypes.includes(type) ? Util.parentBuName : null
);
if (buObject !== null) {
MetadataTypeInfo[type].properties = properties;
MetadataTypeInfo[type].buObject = buObject;
MetadataTypeInfo[type].document();
}
} catch (ex) {
Util.logger.error('mcdev.document ' + ex.message);
Util.logger.debug(ex.stack);
Util.logger.info(
'If the directoy does not exist, you may need to retrieve this BU first.'
);
}
}
/**
* deletes metadata from MC instance by key
*
* @param {string} businessUnit references credentials from properties.json
* @param {string} type supported metadata type
* @param {string} customerKey Identifier of metadata
* @returns {Promise.<boolean>} true if successful, false otherwise
*/
static async deleteByKey(businessUnit, type, customerKey) {
Util.startLogger();
Util.logger.info('mcdev:: delete');
if (!Util._isValidType(type)) {
return;
}
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
return null;
}
const buObject = await Cli.getCredentialObject(properties, businessUnit);
if (buObject !== null) {
try {
MetadataTypeInfo[type].client = auth.getSDK(buObject);
} catch (ex) {
Util.logger.error(ex.message);
return;
}
Util.logger.info(
Util.getGrayMsg(` - Deleting ${type} with key ${customerKey} on BU ${businessUnit}`)
);
try {
MetadataTypeInfo[type].properties = properties;
MetadataTypeInfo[type].buObject = buObject;
return await MetadataTypeInfo[type].deleteByKey(customerKey);
} catch (ex) {
Util.logger.errorStack(ex, ` - Deleting ${type} failed`);
}
}
}
/**
* ensures triggered sends are restarted to ensure they pick up on changes of the underlying emails
*
* @param {string} businessUnit references credentials from properties.json
* @param {string} type references credentials from properties.json
* @param {string[]} [keyArr] metadata keys
* @returns {Promise.<void>} -
*/
static async refresh(businessUnit, type, keyArr) {
Util.startLogger();
Util.logger.info('mcdev:: refresh');
if (!type || !Util._isValidType(type, true)) {
type = 'triggeredSend';
Util.logger.info(' - setting type to ' + type);
}
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
return null;
}
const buObject = await Cli.getCredentialObject(properties, businessUnit);
if (buObject !== null) {
try {
MetadataTypeInfo[type].client = auth.getSDK(buObject);
} catch (ex) {
Util.logger.error(ex.message);
return;
}
try {
cache.initCache(buObject);
MetadataTypeInfo[type].properties = properties;
MetadataTypeInfo[type].buObject = buObject;
await MetadataTypeInfo[type].refresh(keyArr);
} catch (ex) {
Util.logger.errorStack(ex, 'mcdev.refresh ' + ex.message);
}
}
}
/**
* Converts metadata to legacy format. Output is saved in 'converted' directory
*
* @param {string} businessUnit references credentials from properties.json
* @returns {Promise.<void>} -
*/
static async badKeys(businessUnit) {
Util.startLogger();
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
return null;
}
const buObject = await Cli.getCredentialObject(properties, businessUnit);
if (buObject !== null) {
Util.logger.info('Gathering list of Name<>External Key mismatches (bad keys)');
const retrieveDir = File.filterIllegalPathChars(
File.normalizePath([
properties.directories.retrieve,
buObject.credential,
buObject.businessUnit,
])
);
const docPath = File.normalizePath([
properties.directories.docs,
'badKeys',
buObject.credential,
]);
const filename = File.normalizePath([
docPath,
File.filterIllegalFilenames(buObject.businessUnit) + '.badKeys.md',
]);
await File.ensureDir(docPath);
if (await File.pathExistsSync(filename)) {
File.removeSync(filename);
}
const regex = new RegExp('(\\w+-){4}\\w+');
await File.ensureDir(retrieveDir);
const metadata = Deployer.readBUMetadata(retrieveDir, null, true);
let output = '# List of Metadata with Name-Key mismatches\n';
for (const metadataType in metadata) {
let listEntries = '';
for (const entry in metadata[metadataType]) {
const metadataEntry = metadata[metadataType][entry];
if (regex.test(entry)) {
if (metadataType === 'query' && metadataEntry.Status === 'Inactive') {
continue;
}
listEntries +=
'- ' +
entry +
(metadataEntry.name || metadataEntry.Name
? ' => ' + (metadataEntry.name || metadataEntry.Name)
: '') +
'\n';
}
}
if (listEntries !== '') {
output += '\n## ' + metadataType + '\n\n' + listEntries;
}
}
await File.writeToFile(
docPath,
File.filterIllegalFilenames(buObject.businessUnit) + '.badKeys',
'md',
output
);
Util.logger.info('Bad keys documented in ' + filename);
}
}
/**
* Retrieve a specific metadata file and templatise.
*
* @param {string} businessUnit references credentials from properties.json
* @param {string} selectedType supported metadata type
* @param {string[]} name name of the metadata
* @param {string} market market which should be used to revert template
* @returns {Promise.<TYPE.MultiMetadataTypeList>} -
*/
static async retrieveAsTemplate(businessUnit, selectedType, name, market) {
Util.startLogger();
Util.logger.info('mcdev:: Retrieve as Template');
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
return null;
}
if (!Util._isValidType(selectedType)) {
return;
}
const [type, subType] = Util.getTypeAndSubType(selectedType);
let retrieveTypesArr;
if (
type &&
subType &&
MetadataTypeInfo[type] &&
MetadataTypeDefinitions[type].subTypes.includes(subType)
) {
retrieveTypesArr = [selectedType];
} else if (type && MetadataTypeInfo[type]) {
retrieveTypesArr = [type];
}
const buObject = await Cli.getCredentialObject(properties, businessUnit);
if (buObject !== null) {
cache.initCache(buObject);
const retriever = new Retriever(properties, buObject);
if (Util.checkMarket(market, properties)) {
return retriever.retrieve(retrieveTypesArr, name, properties.markets[market]);
}
}
}
/**
* Build a template based on a list of metadata files in the retrieve folder.
*
* @param {string} businessUnit references credentials from properties.json
* @param {string} selectedType supported metadata type
* @param {string[]} keyArr customerkey of the metadata
* @param {string} market market localizations
* @returns {Promise.<TYPE.MultiMetadataTypeList>} -
*/
static async buildTemplate(businessUnit, selectedType, keyArr, market) {
Util.startLogger();
Util.logger.info('mcdev:: Build Template from retrieved files');
return Builder.buildTemplate(businessUnit, selectedType, keyArr, market);
}
/**
* Build a specific metadata file based on a template.
*
* @param {string} businessUnit references credentials from properties.json
* @param {string} selectedType supported metadata type
* @param {string} name name of the metadata
* @param {string} market market localizations
* @returns {Promise.<void>} -
*/
static async buildDefinition(businessUnit, selectedType, name, market) {
Util.startLogger();
Util.logger.info('mcdev:: Build Definition from Template');
return Builder.buildDefinition(businessUnit, selectedType, name, market);
}
/**
* Build a specific metadata file based on a template using a list of bu-market combos
*
* @param {string} listName name of list of BU-market combos
* @param {string} type supported metadata type
* @param {string} name name of the metadata
* @returns {Promise.<void>} -
*/
static async buildDefinitionBulk(listName, type, name) {
Util.startLogger();
Util.logger.info('mcdev:: Build Definition from Template Bulk');
return Builder.buildDefinitionBulk(listName, type, name);
}
/**
*
* @param {string} businessUnit references credentials from properties.json
* @param {string} selectedType supported metadata type
* @param {string[]} keyArr customerkey of the metadata
* @returns {Promise.<string[]>} list of all files that need to be committed in a flat array ['path/file1.ext', 'path/file2.ext']
*/
static async getFilesToCommit(businessUnit, selectedType, keyArr) {
Util.startLogger();
Util.logger.info('mcdev:: getFilesToCommit');
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
return null;
}
if (!Util._isValidType(selectedType)) {
return;
}
if (selectedType.includes('-')) {
Util.logger.error(
`:: '${selectedType}' is not a valid metadata type. Please don't include subtypes.`
);
return;
}
const buObject = await Cli.getCredentialObject(properties, businessUnit);
if (buObject !== null) {
return DevOps.getFilesToCommit(properties, buObject, selectedType, keyArr);
}
}
/**
* Start an item (query)
*
* @param {string} businessUnit name of BU
* @param {TYPE.SupportedMetadataTypes} [selectedType] limit to given metadata types
* @param {string[]} [keys] customerkey of the metadata
* @returns {Promise.<boolean>} true if all started successfully, false if not
*/
static async execute(businessUnit, selectedType, keys) {
Util.startLogger();
Util.logger.info('mcdev:: Executing ' + selectedType);
const properties = await config.getProperties();
let counter_credBu = 0;
let counter_failed = 0;
if (!(await config.checkProperties(properties))) {
// return null here to avoid seeing 2 error messages for the same issue
return false;
}
if (!Util._isValidType(selectedType)) {
return false;
}
if (!Object.prototype.hasOwnProperty.call(MetadataTypeInfo[selectedType], 'execute')) {
Util.logger.error(
` ☇ skipping ${selectedType}: execute is not supported yet for ${selectedType}`
);
return false;
}
if (
(!Array.isArray(keys) || !keys.length) &&
(!Util.OPTIONS.like || !Object.keys(Util.OPTIONS.like).length)
) {
Util.logger.error('At least one key or a --like filter is required.');
return false;
} else if (
Array.isArray(keys) &&
keys.length &&
Util.OPTIONS.like &&
Object.keys(Util.OPTIONS.like).length
) {
Util.logger.error('You can either specify keys OR a --like filter.');
return false;
}
if (businessUnit === '*') {
Util.logger.info(':: Executing the entity on all BUs for all credentials');
let counter_credTotal = 0;
for (const cred in properties.credentials) {
Util.logger.info(`:: Executing the entity on all BUs for ${cred}`);
for (const bu in properties.credentials[cred].businessUnits) {
if (await this._executeBU(cred, bu, selectedType, keys)) {
counter_credBu++;
} else {
counter_failed++;
}
Util.startLogger(true);
}
counter_credTotal += counter_credBu;
Util.logger.info(`:: Executed the entity on ${counter_credBu} BUs for ${cred}\n`);
}
Util.logger.info(`:: Executed the entity on ${counter_credTotal} BUs in total\n`);
} else {
let [cred, bu] = businessUnit ? businessUnit.split('/') : [null, null];
// to allow all-BU via user selection we need to run this here already
if (
properties.credentials &&
(!properties.credentials[cred] ||
(bu !== '*' && !properties.credentials[cred].businessUnits[bu]))
) {
const buObject = await Cli.getCredentialObject(
properties,
cred === null ? null : cred + '/' + bu,
null,
true
);
if (buObject === null) {
return false;
} else {
cred = buObject.credential;
bu = buObject.businessUnit;
}
}
if (bu === '*' && properties.credentials && properties.credentials[cred]) {
Util.logger.info(`\n :: Executing the entity on all BUs for ${cred}`);
let counter_credBu = 0;
for (const bu in properties.credentials[cred].businessUnits) {
if (await this._executeBU(cred, bu, selectedType, keys)) {
counter_credBu++;
} else {
counter_failed++;
}
Util.startLogger(true);
}
Util.logger.info(
`\n :: Executed the entity on ${counter_credBu} BUs for ${cred}\n`
);
} else {
// execute the entity on one BU only
if (await this._executeBU(cred, bu, selectedType, keys)) {
counter_credBu++;
} else {
counter_failed++;
}
Util.logger.info(`\n :: Done\n`);
}
}
if (counter_credBu !== 0) {
Util.logger.info(`\n :: Executed query on ${counter_credBu} BUs\n`);
}
return counter_failed === 0 ? true : false;
}
/**
* helper for {@link Mcdev.execute}
*
* @param {string} cred name of Credential
* @param {string} bu name of BU
* @param {TYPE.SupportedMetadataTypes} [type] limit execution to given metadata type
* @param {string[]} keyArr customerkey of the metadata
* @returns {Promise.<boolean>} true if all items were executed, false otherwise
*/
static async _executeBU(cred, bu, type, keyArr) {
const properties = await config.getProperties();
let counter_failed = 0;
const buObject = await Cli.getCredentialObject(
properties,
cred === null ? null : cred + '/' + bu,
null,
true
);
try {
if (!type) {
throw new Error('No type was provided');
}
if (buObject !== null) {
cache.initCache(buObject);
cred = buObject.credential;
bu = buObject.businessUnit;
}
Util.logger.info(`\n :: Executing ${type} on ${cred}/${bu}\n`);
MetadataTypeInfo[type].client = auth.getSDK(buObject);
if (Util.OPTIONS.like && Object.keys(Util.OPTIONS.like).length) {
keyArr = await this._retrieveKeysWithLike(type, buObject);
}
if (!keyArr || (Array.isArray(keyArr) && !keyArr.length)) {
throw new Error('No keys were provided');
}
// result will be undefined (false) if execute is not supported for the type
if (!(await MetadataTypeInfo[type].execute(keyArr))) {
counter_failed++;
}
} catch (ex) {
Util.logger.errorStack(ex, 'mcdev.execute failed');
}
return counter_failed === 0 ? true : false;
}
/**
* helper for {@link Mcdev._executeBU}
*
* @param {TYPE.SupportedMetadataTypes} selectedType limit execution to given metadata type
* @param {TYPE.BuObject} buObject properties for auth
* @returns {string[]} keyArr
*/
static async _retrieveKeysWithLike(selectedType, buObject) {
const properties = await config.getProperties();
// cache depenencies
const deployOrder = Util.getMetadataHierachy([selectedType]);
for (const type in deployOrder) {
const subTypeArr = deployOrder[type];
MetadataTypeInfo[type].client = auth.getSDK(buObject);
MetadataTypeInfo[type].properties = properties;
MetadataTypeInfo[type].buObject = buObject;
Util.logger.info(`Caching dependent Metadata: ${type}`);
Util.logSubtypes(subTypeArr);
const result = await MetadataTypeInfo[type].retrieveForCache(null, subTypeArr);
if (result) {
if (Array.isArray(result)) {
for (const result_i of result) {
if (result_i?.metadata && Object.keys(result_i.metadata).length) {
cache.mergeMetadata(type, result_i.metadata);
}
}
} else {
cache.setMetadata(type, result.metadata);
}
}
}
// find all keys in chosen type that match the like-filter
const keyArr = [];
const metadataMap = cache.getCache()[selectedType];
if (!metadataMap) {
throw new Error(`Selected type ${selectedType} could not be cached`);
}
Util.logger.info(
Util.getGrayMsg(`Found ${Object.keys(metadataMap).length} ${selectedType}s`)
);
for (const originalKey in metadataMap) {
// hide postRetrieveOutput
Util.setLoggingLevel({ silent: true });
metadataMap[originalKey] = MetadataTypeInfo[selectedType].postRetrieveTasks(
metadataMap[originalKey]
);
// reactivate logging
Util.setLoggingLevel({});
if (Util.fieldsLike(metadataMap[originalKey])) {
keyArr.push(originalKey);
}
}
Util.logger.info(
Util.getGrayMsg(
`Identified ${keyArr.length} ${selectedType}${
keyArr.length === 1 ? '' : 's'
} that match${selectedType}${keyArr.length === 1 ? 'es' : ''} the like-filter`
)
);
return keyArr;
}
}
module.exports = Mcdev;