-
Notifications
You must be signed in to change notification settings - Fork 36
/
index.js
1142 lines (1104 loc) · 45 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
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'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',
'execute',
'filter',
'fromRetrieve',
'json',
'like',
'noLogColors',
'noLogFile',
'refresh',
'schedule',
'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) {
console.time('Time'); // eslint-disable-line no-console
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;
}
}
}
const resultsObj = {};
if (businessUnit === '*') {
Util.logger.info(':: Retrieving all BUs for all credentials');
let counter_credTotal = 0;
for (const cred in properties.credentials) {
Util.logger.info(`:: Retrieving all BUs for ${cred}`);
let counter_credBu = 0;
for (const bu in properties.credentials[cred].businessUnits) {
resultsObj[`${cred}/${bu}`] = await this.#retrieveBU(
cred,
bu,
selectedTypesArr,
keys
);
counter_credBu++;
Util.startLogger(true);
}
counter_credTotal += counter_credBu;
Util.logger.info(`:: ${counter_credBu} BUs of ${cred}\n`);
}
const credentialCount = Object.keys(properties.credentials).length;
Util.logger.info(
`:: Done for ${counter_credTotal} BUs of ${credentialCount} credential${
credentialCount === 1 ? '' : 's'
} 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(`:: Retrieving all BUs for ${cred}`);
let counter_credBu = 0;
for (const bu in properties.credentials[cred].businessUnits) {
resultsObj[`${cred}/${bu}`] = await this.#retrieveBU(
cred,
bu,
selectedTypesArr,
keys
);
counter_credBu++;
Util.startLogger(true);
}
Util.logger.info(`:: Done for ${counter_credBu} BUs of ${cred}\n`);
} else {
// retrieve a single BU; return
const retrieveChangelog = await this.#retrieveBU(
cred,
bu,
selectedTypesArr,
keys,
changelogOnly
);
if (changelogOnly) {
console.timeEnd('Time'); // eslint-disable-line no-console
return retrieveChangelog;
} else {
resultsObj[`${cred}/${bu}`] = retrieveChangelog;
}
Util.logger.info(`:: Done\n`);
}
}
// merge all results into one object
for (const credBu in resultsObj) {
for (const type in resultsObj[credBu]) {
const base = resultsObj[credBu][type][0];
for (let i = 1; i < resultsObj[credBu][type].length; i++) {
// merge all items into the first array
Object.assign(base, resultsObj[credBu][type][i]);
}
resultsObj[credBu][type] = resultsObj[credBu][type][0];
}
}
console.timeEnd('Time'); // eslint-disable-line no-console
return resultsObj;
}
/**
* 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 = {
attributeSet: 'setDefinition',
emailSend: 'emailSendDefinition',
event: 'eventDefinition',
fileLocation: 'ftpLocation',
journey: 'interaction',
triggeredSend: 'triggeredSendDefinition',
user: 'accountUser',
};
Util.logger.info(`:: 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
);
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
* @returns {Promise.<Object.<string,TYPE.MultiMetadataTypeMap>>} deployed metadata per BU (first key: bu name, second key: metadata type)
*/
static async deploy(businessUnit, selectedTypesArr, keyArr) {
console.time('Time'); // eslint-disable-line no-console
Util.startLogger();
const deployResult = await Deployer.deploy(businessUnit, selectedTypesArr, keyArr);
console.timeEnd('Time'); // eslint-disable-line no-console
return deployResult;
}
/**
* 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);
}
}
/**
* Schedule an item (shortcut for execute --schedule)
*
* @param {string} businessUnit name of BU
* @param {TYPE.SupportedMetadataTypes} [selectedType] limit to given metadata types
* @param {string[]} [keys] customerkey of the metadata
* @returns {Promise.<Object.<string, string[]>>} key: business unit name, value: list of scheduled item keys
*/
static async schedule(businessUnit, selectedType, keys) {
this.setOptions({ schedule: true });
return this.#runMethod('execute', businessUnit, selectedType, keys);
}
/**
* Start/execute an item
*
* @param {string} businessUnit name of BU
* @param {TYPE.SupportedMetadataTypes} [selectedType] limit to given metadata types
* @param {string[]} [keys] customerkey of the metadata
* @returns {Promise.<Object.<string, string[]>>} key: business unit name, value: list of executed item keys
*/
static async execute(businessUnit, selectedType, keys) {
return this.#runMethod('execute', businessUnit, selectedType, keys);
}
/**
* pause an item
*
* @param {string} businessUnit name of BU
* @param {TYPE.SupportedMetadataTypes} [selectedType] limit to given metadata types
* @param {string[]} [keys] customerkey of the metadata
* @returns {Promise.<Object.<string, string[]>>} key: business unit name, value: list of paused item keys
*/
static async pause(businessUnit, selectedType, keys) {
return this.#runMethod('pause', businessUnit, selectedType, keys);
}
/**
* Updates the key to match the name field
*
* @param {string} businessUnit name of BU
* @param {TYPE.SupportedMetadataTypes} selectedType limit to given metadata types
* @param {string[]} [keys] customerkey of the metadata
* @returns {Promise.<Object.<string, string[]>>} key: business unit name, value: list of paused item keys
*/
static async fixKeys(businessUnit, selectedType, keys) {
return this.#runMethod('fixKeys', businessUnit, selectedType, keys);
}
/**
* run a method across BUs
*
* @param {'execute'|'pause'|'fixKeys'} methodName what to run
* @param {string} businessUnit name of BU
* @param {TYPE.SupportedMetadataTypes} [selectedType] limit to given metadata types
* @param {string[]} [keys] customerkey of the metadata
* @returns {Promise.<Object.<string, string[]>>} key: business unit name, value: list of affected item keys
*/
static async #runMethod(methodName, businessUnit, selectedType, keys) {
Util.startLogger();
let lang_past;
let lang_present;
let requireKeyOrLike;
let checkMetadataSupport;
const resultObj = {};
switch (methodName) {
case 'execute': {
lang_past = 'executed';
lang_present = 'executing';
requireKeyOrLike = true;
checkMetadataSupport = true;
break;
}
case 'pause': {
lang_past = 'paused';
lang_present = 'pausing';
requireKeyOrLike = true;
checkMetadataSupport = true;
break;
}
case 'fixKeys': {
lang_past = 'fixed keys';
lang_present = 'fixing keys';
requireKeyOrLike = false;
checkMetadataSupport = false;
break;
}
}
Util.logger.info(`mcdev:: ${methodName} ${selectedType}`);
const properties = await config.getProperties();
let counter_credBu = 0;
let counter_credKeys = 0;
if (!(await config.checkProperties(properties))) {
// return null here to avoid seeing 2 error messages for the same issue
return resultObj;
}
if (!Util._isValidType(selectedType)) {
return resultObj;
}
if (
checkMetadataSupport &&
!Object.prototype.hasOwnProperty.call(MetadataTypeInfo[selectedType], methodName)
) {
Util.logger.error(
` ☇ skipping ${selectedType}: ${methodName} is not supported yet for ${selectedType}`
);
return resultObj;
}
if (
requireKeyOrLike &&
(!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 resultObj;
} 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 resultObj;
}
if (businessUnit === '*') {
Util.logger.info(
`:: ${lang_present} the ${selectedType} on all BUs for all credentials`
);
let counter_credTotal = 0;
for (const cred in properties.credentials) {
Util.logger.info(`:: ${lang_present} ${selectedType} on all BUs for ${cred}`);
// reset counter per cred
counter_credKeys = 0;
counter_credBu = 0;
for (const bu in properties.credentials[cred].businessUnits) {
resultObj[cred + '/' + bu] = await this.#runOnBU(
methodName,
cred,
bu,
selectedType,
keys
);
counter_credBu++;
counter_credKeys += resultObj[cred + '/' + bu].length;
Util.startLogger(true);
}
counter_credTotal += counter_credBu;
Util.logger.info(
`:: ${lang_past} for ${counter_credKeys} ${selectedType}s on ${counter_credBu} BUs for ${cred}`
);
}
Util.logger.info(
`:: ${lang_past} ${selectedType} 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 resultObj;
} else {
cred = buObject.credential;
bu = buObject.businessUnit;
}
}
if (bu === '*' && properties.credentials && properties.credentials[cred]) {
Util.logger.info(`:: ${lang_present} ${selectedType} on all BUs for ${cred}`);
for (const bu in properties.credentials[cred].businessUnits) {
resultObj[cred + '/' + bu] = await this.#runOnBU(
methodName,
cred,
bu,
selectedType,
keys
);
counter_credBu++;
counter_credKeys += resultObj[cred + '/' + bu].length;
Util.startLogger(true);
}
Util.logger.info(
`:: ${lang_past} for ${counter_credKeys} ${selectedType}s on ${counter_credBu} BUs for ${cred}`
);
} else {
// execute runMethod for the entity on one BU only
resultObj[cred + '/' + bu] = await this.#runOnBU(
methodName,
cred,
bu,
selectedType,
keys
);
Util.logger.info(`:: Done`);
}
}
return resultObj;
}
/**
* helper for {@link Mcdev.#runMethod}
*
* @param {'execute'|'pause'|'fixKeys'} methodName what to run
* @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.<string[]>} list of keys that were affected
*/
static async #runOnBU(methodName, cred, bu, type, keyArr) {
const properties = await config.getProperties();
const resultArr = [];
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(`:: ${methodName} ${type} on ${cred}/${bu}`);
MetadataTypeInfo[type].client = auth.getSDK(buObject);
MetadataTypeInfo[type].properties = properties;
MetadataTypeInfo[type].buObject = buObject;
switch (methodName) {
case 'fixKeys': {
{
resultArr.push(...(await this.#fixKeys(cred, bu, type, keyArr)));
break;
}
}
default: {
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 methodName is not supported for the type
resultArr.push(...(await MetadataTypeInfo[type][methodName](keyArr)));
}
}
} catch (ex) {