@contentstack/cli-cm-branches 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,503 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.prepareModifiedDiff = exports.deepDiff = exports.prepareBranchVerboseRes = exports.branchCompareSDK = exports.filterBranchDiffDataByModule = exports.printVerboseTextView = exports.parseVerbose = exports.printCompactTextView = exports.parseCompactText = exports.printSummary = exports.parseSummary = exports.fetchBranchesDiff = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const chalk_1 = tslib_1.__importDefault(require("chalk"));
6
+ const forEach_1 = tslib_1.__importDefault(require("lodash/forEach"));
7
+ const padStart_1 = tslib_1.__importDefault(require("lodash/padStart"));
8
+ const startCase_1 = tslib_1.__importDefault(require("lodash/startCase"));
9
+ const camelCase_1 = tslib_1.__importDefault(require("lodash/camelCase"));
10
+ const unionWith_1 = tslib_1.__importDefault(require("lodash/unionWith"));
11
+ const find_1 = tslib_1.__importDefault(require("lodash/find"));
12
+ const cli_utilities_1 = require("@contentstack/cli-utilities");
13
+ const isArray_1 = tslib_1.__importDefault(require("lodash/isArray"));
14
+ const just_diff_1 = require("just-diff");
15
+ const config_1 = tslib_1.__importDefault(require("../config"));
16
+ /**
17
+ * Fetch differences between two branches
18
+ * @async
19
+ * @method
20
+ * @param payload
21
+ * @param branchesDiffData
22
+ * @param skip
23
+ * @param limit
24
+ * @returns {*} Promise<any>
25
+ */
26
+ async function fetchBranchesDiff(payload, branchesDiffData = [], skip = config_1.default.skip, limit = config_1.default.limit) {
27
+ const branchDiffData = await branchCompareSDK(payload, skip, limit);
28
+ const diffData = branchDiffData === null || branchDiffData === void 0 ? void 0 : branchDiffData.diff;
29
+ const nextUrl = (branchDiffData === null || branchDiffData === void 0 ? void 0 : branchDiffData.next_url) || '';
30
+ if (branchesDiffData === null || branchesDiffData === void 0 ? void 0 : branchesDiffData.length) {
31
+ branchesDiffData = [...branchesDiffData, ...diffData];
32
+ }
33
+ else {
34
+ branchesDiffData = diffData;
35
+ }
36
+ if (nextUrl) {
37
+ skip = skip + limit;
38
+ return await fetchBranchesDiff(payload, branchesDiffData, skip, limit);
39
+ }
40
+ return branchesDiffData;
41
+ }
42
+ exports.fetchBranchesDiff = fetchBranchesDiff;
43
+ /**
44
+ * branch compare sdk integration
45
+ * @async
46
+ * @method
47
+ * @param payload
48
+ * @param skip
49
+ * @param limit
50
+ * @returns {*} Promise<any>
51
+ */
52
+ async function branchCompareSDK(payload, skip, limit) {
53
+ const { host } = payload;
54
+ const managementAPIClient = await (0, cli_utilities_1.managementSDKClient)({ host });
55
+ const branchQuery = managementAPIClient
56
+ .stack({ api_key: payload.apiKey })
57
+ .branch(payload.baseBranch)
58
+ .compare(payload.compareBranch);
59
+ const queryParams = {};
60
+ if (skip >= 0)
61
+ queryParams['skip'] = skip;
62
+ if (limit >= 0)
63
+ queryParams['limit'] = limit;
64
+ if (payload === null || payload === void 0 ? void 0 : payload.uid)
65
+ queryParams['uid'] = payload.uid;
66
+ const module = payload.module || 'all';
67
+ switch (module) {
68
+ case 'content_types' || 'content_type':
69
+ return await branchQuery
70
+ .contentTypes(queryParams)
71
+ .then((data) => data)
72
+ .catch((err) => handleErrorMsg(err, payload.spinner));
73
+ break;
74
+ case 'global_fields' || 'global_field':
75
+ return await branchQuery
76
+ .globalFields(queryParams)
77
+ .then((data) => data)
78
+ .catch((err) => handleErrorMsg(err, payload.spinner));
79
+ break;
80
+ case 'all':
81
+ return await branchQuery
82
+ .all(queryParams)
83
+ .then((data) => data)
84
+ .catch((err) => handleErrorMsg(err, payload.spinner));
85
+ break;
86
+ default:
87
+ handleErrorMsg({ errorMessage: 'Invalid module!' }, payload.spinner);
88
+ }
89
+ }
90
+ exports.branchCompareSDK = branchCompareSDK;
91
+ function handleErrorMsg(err, spinner) {
92
+ cli_utilities_1.cliux.loaderV2('', spinner);
93
+ if (err === null || err === void 0 ? void 0 : err.errorMessage) {
94
+ cli_utilities_1.cliux.print(`Error: ${err.errorMessage}`, { color: 'red' });
95
+ }
96
+ else if (err === null || err === void 0 ? void 0 : err.message) {
97
+ cli_utilities_1.cliux.print(`Error: ${err.message}`, { color: 'red' });
98
+ }
99
+ else {
100
+ console.log(err);
101
+ cli_utilities_1.cliux.print(`Error: ${cli_utilities_1.messageHandler.parse('CLI_BRANCH_API_FAILED')}`, { color: 'red' });
102
+ }
103
+ process.exit(1);
104
+ }
105
+ /**
106
+ * filter out differences of two branches on basis of their status and return overall summary
107
+ * @method
108
+ * @param branchesDiffData - differences of two branches
109
+ * @param {string} baseBranch
110
+ * @param {string} compareBranch
111
+ * @returns {*} BranchDiffSummary
112
+ */
113
+ function parseSummary(branchesDiffData, baseBranch, compareBranch) {
114
+ let baseCount = 0, compareCount = 0, modifiedCount = 0;
115
+ if (branchesDiffData === null || branchesDiffData === void 0 ? void 0 : branchesDiffData.length) {
116
+ (0, forEach_1.default)(branchesDiffData, (diff) => {
117
+ if (diff.status === 'compare_only')
118
+ compareCount++;
119
+ else if (diff.status === 'base_only')
120
+ baseCount++;
121
+ else if (diff.status === 'modified')
122
+ modifiedCount++;
123
+ });
124
+ }
125
+ const branchSummary = {
126
+ base: baseBranch,
127
+ compare: compareBranch,
128
+ base_only: baseCount,
129
+ compare_only: compareCount,
130
+ modified: modifiedCount,
131
+ };
132
+ return branchSummary;
133
+ }
134
+ exports.parseSummary = parseSummary;
135
+ /**
136
+ * print summary of two branches differences
137
+ * @method
138
+ * @param {BranchDiffSummary} diffSummary - summary of branches diff
139
+ */
140
+ function printSummary(diffSummary) {
141
+ const totalTextLen = 12;
142
+ (0, forEach_1.default)(diffSummary, (value, key) => {
143
+ const str = (0, startCase_1.default)((0, camelCase_1.default)(key));
144
+ cli_utilities_1.cliux.print(`${(0, padStart_1.default)(str, totalTextLen)}: ${value}`);
145
+ });
146
+ }
147
+ exports.printSummary = printSummary;
148
+ /**
149
+ * filter out differences of two branches on basis of their status and return compact text details
150
+ * @method
151
+ * @param branchesDiffData
152
+ * @returns {*} BranchCompactTextRes
153
+ */
154
+ function parseCompactText(branchesDiffData) {
155
+ let listOfModified = [], listOfAdded = [], listOfDeleted = [];
156
+ if (branchesDiffData === null || branchesDiffData === void 0 ? void 0 : branchesDiffData.length) {
157
+ (0, forEach_1.default)(branchesDiffData, (diff) => {
158
+ if (diff.status === 'compare_only')
159
+ listOfAdded.push(diff);
160
+ else if (diff.status === 'base_only')
161
+ listOfDeleted.push(diff);
162
+ else if (diff.status === 'modified')
163
+ listOfModified.push(diff);
164
+ });
165
+ }
166
+ const branchTextRes = {
167
+ modified: listOfModified,
168
+ added: listOfAdded,
169
+ deleted: listOfDeleted,
170
+ };
171
+ return branchTextRes;
172
+ }
173
+ exports.parseCompactText = parseCompactText;
174
+ /**
175
+ * print compact text details of two branches differences
176
+ * @method
177
+ * @param {BranchCompactTextRes} branchTextRes
178
+ */
179
+ function printCompactTextView(branchTextRes) {
180
+ var _a, _b, _c;
181
+ if (((_a = branchTextRes.modified) === null || _a === void 0 ? void 0 : _a.length) || ((_b = branchTextRes.added) === null || _b === void 0 ? void 0 : _b.length) || ((_c = branchTextRes.deleted) === null || _c === void 0 ? void 0 : _c.length)) {
182
+ cli_utilities_1.cliux.print(' ');
183
+ (0, forEach_1.default)(branchTextRes.added, (diff) => {
184
+ cli_utilities_1.cliux.print(chalk_1.default.green(`+ '${diff.title}' ${(0, startCase_1.default)((0, camelCase_1.default)(diff.type))}`));
185
+ });
186
+ (0, forEach_1.default)(branchTextRes.modified, (diff) => {
187
+ cli_utilities_1.cliux.print(chalk_1.default.blue(`± '${diff.title}' ${(0, startCase_1.default)((0, camelCase_1.default)(diff.type))}`));
188
+ });
189
+ (0, forEach_1.default)(branchTextRes.deleted, (diff) => {
190
+ cli_utilities_1.cliux.print(chalk_1.default.red(`- '${diff.title}' ${(0, startCase_1.default)((0, camelCase_1.default)(diff.type))}`));
191
+ });
192
+ }
193
+ }
194
+ exports.printCompactTextView = printCompactTextView;
195
+ /**
196
+ * filter out text verbose details - deleted, added, modified details
197
+ * @async
198
+ * @method
199
+ * @param branchesDiffData
200
+ * @param {BranchDiffPayload} payload
201
+ * @returns {*} Promise<BranchDiffVerboseRes>
202
+ */
203
+ async function parseVerbose(branchesDiffData, payload) {
204
+ const { added, modified, deleted } = parseCompactText(branchesDiffData);
205
+ let modifiedDetailList = [];
206
+ for (let i = 0; i < (modified === null || modified === void 0 ? void 0 : modified.length); i++) {
207
+ const diff = modified[i];
208
+ payload.uid = diff === null || diff === void 0 ? void 0 : diff.uid;
209
+ const branchDiff = await branchCompareSDK(payload);
210
+ if (branchDiff) {
211
+ const { listOfModifiedFields, listOfAddedFields, listOfDeletedFields } = await prepareBranchVerboseRes(branchDiff);
212
+ modifiedDetailList.push({
213
+ moduleDetails: diff,
214
+ modifiedFields: {
215
+ modified: listOfModifiedFields,
216
+ deleted: listOfDeletedFields,
217
+ added: listOfAddedFields,
218
+ },
219
+ });
220
+ }
221
+ }
222
+ const verboseRes = {
223
+ modified: modifiedDetailList,
224
+ added: added,
225
+ deleted: deleted,
226
+ };
227
+ return verboseRes;
228
+ }
229
+ exports.parseVerbose = parseVerbose;
230
+ /**
231
+ * check whether fields exists in either base or compare branches.
232
+ * @method
233
+ * @param branchDiff
234
+ * @returns
235
+ */
236
+ async function prepareBranchVerboseRes(branchDiff) {
237
+ var _a, _b, _c, _d, _e;
238
+ let listOfModifiedFields = [], listOfDeletedFields = [], listOfAddedFields = [];
239
+ if (((_a = branchDiff === null || branchDiff === void 0 ? void 0 : branchDiff.diff) === null || _a === void 0 ? void 0 : _a.status) === 'modified') {
240
+ let unionOfBaseAndCompareBranch = [];
241
+ const baseBranchDiff = (_c = (_b = branchDiff.diff) === null || _b === void 0 ? void 0 : _b.base_branch) === null || _c === void 0 ? void 0 : _c.differences;
242
+ const compareBranchDiff = (_e = (_d = branchDiff.diff) === null || _d === void 0 ? void 0 : _d.compare_branch) === null || _e === void 0 ? void 0 : _e.differences;
243
+ if (baseBranchDiff && compareBranchDiff) {
244
+ unionOfBaseAndCompareBranch = (0, unionWith_1.default)(baseBranchDiff, compareBranchDiff, customComparator);
245
+ }
246
+ (0, forEach_1.default)(unionOfBaseAndCompareBranch, (diffData) => {
247
+ const baseBranchFieldExists = (0, find_1.default)(baseBranchDiff, (item) => (item === null || item === void 0 ? void 0 : item.uid) && diffData.uid ? item.uid === diffData.uid : item.path === diffData.path);
248
+ const compareBranchFieldExists = (0, find_1.default)(compareBranchDiff, (item) => (item === null || item === void 0 ? void 0 : item.uid) && diffData.uid ? item.uid === diffData.uid : item.path === diffData.path);
249
+ baseAndCompareBranchDiff({
250
+ baseBranchFieldExists,
251
+ compareBranchFieldExists,
252
+ diffData,
253
+ listOfModifiedFields,
254
+ listOfDeletedFields,
255
+ listOfAddedFields,
256
+ });
257
+ });
258
+ }
259
+ return { listOfAddedFields, listOfDeletedFields, listOfModifiedFields };
260
+ }
261
+ exports.prepareBranchVerboseRes = prepareBranchVerboseRes;
262
+ /**
263
+ * filter out the fields from the module that are deleted, added, or modified. Modules having a modified status.
264
+ * @method
265
+ * @param params
266
+ */
267
+ async function baseAndCompareBranchDiff(params) {
268
+ const { baseBranchFieldExists, compareBranchFieldExists, diffData } = params;
269
+ if (baseBranchFieldExists && compareBranchFieldExists) {
270
+ await prepareModifiedDiff(params);
271
+ }
272
+ else if (baseBranchFieldExists && !compareBranchFieldExists) {
273
+ params.listOfDeletedFields.push({
274
+ path: baseBranchFieldExists === null || baseBranchFieldExists === void 0 ? void 0 : baseBranchFieldExists.uid,
275
+ displayName: baseBranchFieldExists === null || baseBranchFieldExists === void 0 ? void 0 : baseBranchFieldExists.display_name,
276
+ uid: baseBranchFieldExists === null || baseBranchFieldExists === void 0 ? void 0 : baseBranchFieldExists.uid,
277
+ field: baseBranchFieldExists === null || baseBranchFieldExists === void 0 ? void 0 : baseBranchFieldExists.data_type,
278
+ });
279
+ }
280
+ else if (!baseBranchFieldExists && compareBranchFieldExists) {
281
+ params.listOfAddedFields.push({
282
+ path: compareBranchFieldExists === null || compareBranchFieldExists === void 0 ? void 0 : compareBranchFieldExists.uid,
283
+ displayName: compareBranchFieldExists === null || compareBranchFieldExists === void 0 ? void 0 : compareBranchFieldExists.display_name,
284
+ uid: compareBranchFieldExists === null || compareBranchFieldExists === void 0 ? void 0 : compareBranchFieldExists.uid,
285
+ field: compareBranchFieldExists === null || compareBranchFieldExists === void 0 ? void 0 : compareBranchFieldExists.data_type,
286
+ });
287
+ }
288
+ }
289
+ async function prepareModifiedDiff(params) {
290
+ const { baseBranchFieldExists, compareBranchFieldExists } = params;
291
+ if (baseBranchFieldExists.path === 'description' ||
292
+ baseBranchFieldExists.path === 'title' ||
293
+ baseBranchFieldExists.path === 'options.singleton') {
294
+ let displayName;
295
+ if (baseBranchFieldExists.path === 'options.singleton') {
296
+ displayName = 'Single/Multiple';
297
+ }
298
+ else if (baseBranchFieldExists.path === 'description') {
299
+ displayName = 'Description';
300
+ }
301
+ else if (baseBranchFieldExists.path === 'title') {
302
+ displayName = 'Name';
303
+ }
304
+ params.listOfModifiedFields.push({
305
+ path: baseBranchFieldExists.path,
306
+ displayName: displayName,
307
+ uid: baseBranchFieldExists.path,
308
+ field: 'metadata',
309
+ });
310
+ }
311
+ else {
312
+ if ((baseBranchFieldExists === null || baseBranchFieldExists === void 0 ? void 0 : baseBranchFieldExists.display_name) && (compareBranchFieldExists === null || compareBranchFieldExists === void 0 ? void 0 : compareBranchFieldExists.display_name)) {
313
+ const { modified, deleted, added } = await deepDiff(baseBranchFieldExists, compareBranchFieldExists);
314
+ for (let field of Object.values(added)) {
315
+ if (field) {
316
+ params.listOfAddedFields.push({
317
+ path: field['path'],
318
+ displayName: field['displayName'],
319
+ uid: field['uid'],
320
+ field: field['fieldType'],
321
+ });
322
+ }
323
+ }
324
+ for (let field of Object.values(deleted)) {
325
+ if (field) {
326
+ params.listOfDeletedFields.push({
327
+ path: field['path'],
328
+ displayName: field['displayName'],
329
+ uid: field['uid'],
330
+ field: field['fieldType'],
331
+ });
332
+ }
333
+ }
334
+ for (let field of Object.values(modified)) {
335
+ if (field) {
336
+ params.listOfModifiedFields.push({
337
+ path: field['path'],
338
+ displayName: field['displayName'],
339
+ uid: field['uid'],
340
+ field: field['fieldType'],
341
+ });
342
+ }
343
+ }
344
+ }
345
+ }
346
+ }
347
+ exports.prepareModifiedDiff = prepareModifiedDiff;
348
+ function customComparator(a, b) {
349
+ return (a === null || a === void 0 ? void 0 : a.uid) && (b === null || b === void 0 ? void 0 : b.uid) ? a.uid === b.uid : a.path === b.path;
350
+ }
351
+ /**
352
+ * print detail text view of two branches differences - deleted, added and modified fields
353
+ * @param {BranchDiffVerboseRes} branchTextRes
354
+ */
355
+ function printVerboseTextView(branchTextRes) {
356
+ var _a, _b, _c;
357
+ if (((_a = branchTextRes.modified) === null || _a === void 0 ? void 0 : _a.length) || ((_b = branchTextRes.added) === null || _b === void 0 ? void 0 : _b.length) || ((_c = branchTextRes.deleted) === null || _c === void 0 ? void 0 : _c.length)) {
358
+ cli_utilities_1.cliux.print(' ');
359
+ (0, forEach_1.default)(branchTextRes.added, (diff) => {
360
+ cli_utilities_1.cliux.print(chalk_1.default.green(`+ '${diff.title}' ${(0, startCase_1.default)((0, camelCase_1.default)(diff.type))}`));
361
+ });
362
+ (0, forEach_1.default)(branchTextRes.modified, (diff) => {
363
+ cli_utilities_1.cliux.print(chalk_1.default.blue(`± '${diff.moduleDetails.title}' ${(0, startCase_1.default)((0, camelCase_1.default)(diff.moduleDetails.type))}`));
364
+ printModifiedFields(diff.modifiedFields);
365
+ });
366
+ (0, forEach_1.default)(branchTextRes.deleted, (diff) => {
367
+ cli_utilities_1.cliux.print(chalk_1.default.red(`- '${diff.title}' ${(0, startCase_1.default)((0, camelCase_1.default)(diff.type))}`));
368
+ });
369
+ }
370
+ }
371
+ exports.printVerboseTextView = printVerboseTextView;
372
+ /**
373
+ * print detail text view of modified fields
374
+ * @method
375
+ * @param {ModifiedFieldsInput} modfiedFields
376
+ */
377
+ function printModifiedFields(modfiedFields) {
378
+ var _a, _b, _c;
379
+ if (((_a = modfiedFields.modified) === null || _a === void 0 ? void 0 : _a.length) || ((_b = modfiedFields.added) === null || _b === void 0 ? void 0 : _b.length) || ((_c = modfiedFields.deleted) === null || _c === void 0 ? void 0 : _c.length)) {
380
+ (0, forEach_1.default)(modfiedFields.added, (diff) => {
381
+ const field = diff.field ? `${diff.field} field` : 'field';
382
+ cli_utilities_1.cliux.print(` ${chalk_1.default.green(`+ "${diff.displayName}" (${diff.path}) ${field}`)}`);
383
+ });
384
+ (0, forEach_1.default)(modfiedFields.modified, (diff) => {
385
+ const field = diff.field ? `${diff.field} field` : 'field';
386
+ cli_utilities_1.cliux.print(` ${chalk_1.default.blue(`± "${diff.displayName}" (${diff.path}) ${field}`)}`);
387
+ });
388
+ (0, forEach_1.default)(modfiedFields.deleted, (diff) => {
389
+ const field = diff.field ? `${diff.field} field` : 'field';
390
+ cli_utilities_1.cliux.print(` ${chalk_1.default.red(`- "${diff.displayName}" (${diff.path}) ${field}`)}`);
391
+ });
392
+ }
393
+ }
394
+ /**
395
+ * filter out branch differences on basis of module like content_types, global_fields
396
+ * @param branchDiffData
397
+ * @returns
398
+ */
399
+ function filterBranchDiffDataByModule(branchDiffData) {
400
+ let moduleRes = {
401
+ content_types: [],
402
+ global_fields: [],
403
+ };
404
+ (0, forEach_1.default)(branchDiffData, (item) => {
405
+ if (item.type === 'content_type' || item.type === 'content_types')
406
+ moduleRes.content_types.push(item);
407
+ else if (item.type === 'global_field' || item.type === 'global_fields')
408
+ moduleRes.global_fields.push(item);
409
+ });
410
+ return moduleRes;
411
+ }
412
+ exports.filterBranchDiffDataByModule = filterBranchDiffDataByModule;
413
+ const buildPath = (path, key) => (path === '' ? key : `${path}.${key}`);
414
+ async function deepDiff(baseObj, compareObj) {
415
+ const changes = {
416
+ modified: {},
417
+ added: {},
418
+ deleted: {},
419
+ };
420
+ function baseAndCompareSchemaDiff(baseObj, compareObj, path = '') {
421
+ const { schema: baseSchema, path: basePath } = baseObj, restBaseObj = tslib_1.__rest(baseObj, ["schema", "path"]);
422
+ const { schema: compareSchema, path: comparePath } = compareObj, restCompareObj = tslib_1.__rest(compareObj, ["schema", "path"]);
423
+ const currentPath = buildPath(path, baseObj['uid']);
424
+ if (restBaseObj['uid'] === restCompareObj['uid']) {
425
+ prepareModifiedField({ restBaseObj, restCompareObj, currentPath, changes });
426
+ }
427
+ //case1:- base & compare schema both exists
428
+ if ((baseSchema === null || baseSchema === void 0 ? void 0 : baseSchema.length) && (compareSchema === null || compareSchema === void 0 ? void 0 : compareSchema.length) && (0, isArray_1.default)(baseSchema) && (0, isArray_1.default)(compareSchema)) {
429
+ const unionOfBaseAndCompareBranch = (0, unionWith_1.default)(baseSchema, compareSchema, (a, b) => (a === null || a === void 0 ? void 0 : a.uid) === (b === null || b === void 0 ? void 0 : b.uid));
430
+ (0, forEach_1.default)(unionOfBaseAndCompareBranch, (diffData, key) => {
431
+ const baseBranchField = (0, find_1.default)(baseSchema, (item) => item.uid === diffData.uid);
432
+ const compareBranchField = (0, find_1.default)(compareSchema, (item) => item.uid === diffData.uid);
433
+ let newPath;
434
+ if (baseBranchField && !compareBranchField) {
435
+ newPath = `${currentPath}.${baseBranchField['uid']}`;
436
+ prepareDeletedField({ path: newPath, changes, baseField: baseBranchField });
437
+ }
438
+ else if (compareBranchField && !baseBranchField) {
439
+ newPath = `${currentPath}.${compareBranchField['uid']}`;
440
+ prepareAddedField({ path: newPath, changes, compareField: compareBranchField });
441
+ }
442
+ else if (compareBranchField && baseBranchField) {
443
+ baseAndCompareSchemaDiff(baseBranchField, compareBranchField, currentPath);
444
+ }
445
+ });
446
+ }
447
+ //case2:- base schema exists only
448
+ if ((baseSchema === null || baseSchema === void 0 ? void 0 : baseSchema.length) && !(compareSchema === null || compareSchema === void 0 ? void 0 : compareSchema.length) && (0, isArray_1.default)(baseSchema)) {
449
+ (0, forEach_1.default)(baseSchema, (base, key) => {
450
+ const newPath = `${currentPath}.${base['uid']}`;
451
+ prepareDeletedField({ path: newPath, changes, baseField: base });
452
+ });
453
+ }
454
+ //case3:- compare schema exists only
455
+ if (!(baseSchema === null || baseSchema === void 0 ? void 0 : baseSchema.length) && (compareSchema === null || compareSchema === void 0 ? void 0 : compareSchema.length) && (0, isArray_1.default)(compareSchema)) {
456
+ (0, forEach_1.default)(compareSchema, (compare, key) => {
457
+ const newPath = `${currentPath}.${compare['uid']}`;
458
+ prepareAddedField({ path: newPath, changes, compareField: compare });
459
+ });
460
+ }
461
+ }
462
+ baseAndCompareSchemaDiff(baseObj, compareObj);
463
+ return changes;
464
+ }
465
+ exports.deepDiff = deepDiff;
466
+ function prepareAddedField(params) {
467
+ const { path, changes, compareField } = params;
468
+ if (!changes.added[path]) {
469
+ const obj = {
470
+ path: path,
471
+ uid: compareField['uid'],
472
+ displayName: compareField['display_name'],
473
+ fieldType: compareField['data_type'],
474
+ };
475
+ changes.added[path] = obj;
476
+ }
477
+ }
478
+ function prepareDeletedField(params) {
479
+ const { path, changes, baseField } = params;
480
+ if (!changes.added[path]) {
481
+ const obj = {
482
+ path: path,
483
+ uid: baseField['uid'],
484
+ displayName: baseField['display_name'],
485
+ fieldType: baseField['data_type'],
486
+ };
487
+ changes.deleted[path] = obj;
488
+ }
489
+ }
490
+ function prepareModifiedField(params) {
491
+ const { restBaseObj, restCompareObj, currentPath, changes } = params;
492
+ const differences = (0, just_diff_1.diff)(restBaseObj, restCompareObj);
493
+ if (differences.length) {
494
+ const modifiedField = {
495
+ path: currentPath,
496
+ uid: restCompareObj['uid'],
497
+ displayName: restCompareObj['display_name'],
498
+ fieldType: restCompareObj['data_type'],
499
+ };
500
+ if (!changes.modified[currentPath])
501
+ changes.modified[currentPath] = modifiedField;
502
+ }
503
+ }
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createBranch = void 0;
4
+ const cli_utilities_1 = require("@contentstack/cli-utilities");
5
+ async function createBranch(host, apiKey, branch) {
6
+ const managementAPIClient = await (0, cli_utilities_1.managementSDKClient)({ host });
7
+ managementAPIClient
8
+ .stack({ api_key: apiKey })
9
+ .branch()
10
+ .create({ branch })
11
+ .then(() => cli_utilities_1.cliux.success('Branch creation in progress. Once ready, it will show in the results of the branch list command `csdx cm:branches`'))
12
+ .catch((err) => {
13
+ var _a, _b;
14
+ if (err.errorCode === 910)
15
+ cli_utilities_1.cliux.error(`error : Branch with UID '${branch.uid}' already exists, please enter a unique branch UID`);
16
+ else if (err.errorCode === 903) {
17
+ if ((_a = err.errors) === null || _a === void 0 ? void 0 : _a.uid) {
18
+ cli_utilities_1.cliux.error(`error : Branch UID must be 15 character(s) or less, please enter a valid branch UID`);
19
+ }
20
+ else {
21
+ cli_utilities_1.cliux.error(`error : Source Branch with UID '${branch.source}' does not exist, please enter correct source branch UID`);
22
+ }
23
+ }
24
+ else {
25
+ let errorMsg;
26
+ if ((_b = err.errors) === null || _b === void 0 ? void 0 : _b.branches) {
27
+ const errorOutput = err.errors.branches[0];
28
+ errorMsg = `${err.errorMessage} ${errorOutput}`;
29
+ }
30
+ else {
31
+ errorMsg = err.errorMessage;
32
+ }
33
+ cli_utilities_1.cliux.error(`error: ${errorMsg}`);
34
+ }
35
+ });
36
+ }
37
+ exports.createBranch = createBranch;
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createMergeScripts = exports.getContentypeMergeStatus = exports.generateMergeScripts = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const fs_1 = tslib_1.__importDefault(require("fs"));
6
+ const entry_create_script_1 = require("./entry-create-script");
7
+ const entry_update_script_1 = require("./entry-update-script");
8
+ function generateMergeScripts(mergeSummary, mergeJobUID) {
9
+ var _a, _b, _c;
10
+ try {
11
+ let scriptFolderPath;
12
+ if (mergeSummary.content_types.modified && ((_a = mergeSummary.content_types.modified) === null || _a === void 0 ? void 0 : _a.length) !== 0) {
13
+ mergeSummary.content_types.modified.map((contentType) => {
14
+ let data = (0, entry_update_script_1.entryUpdateScript)(contentType.uid);
15
+ scriptFolderPath = createMergeScripts(contentType, data, mergeJobUID);
16
+ });
17
+ }
18
+ if (mergeSummary.content_types.added && ((_b = mergeSummary.content_types.added) === null || _b === void 0 ? void 0 : _b.length) !== 0) {
19
+ (_c = mergeSummary.content_types.added) === null || _c === void 0 ? void 0 : _c.map((contentType) => {
20
+ let data = (0, entry_create_script_1.entryCreateScript)(contentType.uid);
21
+ scriptFolderPath = createMergeScripts(contentType, data, mergeJobUID);
22
+ });
23
+ }
24
+ return scriptFolderPath;
25
+ }
26
+ catch (error) {
27
+ console.log(error);
28
+ }
29
+ }
30
+ exports.generateMergeScripts = generateMergeScripts;
31
+ function getContentypeMergeStatus(status) {
32
+ if (status === 'modified') {
33
+ return 'updated';
34
+ }
35
+ else if (status === 'compare_only') {
36
+ return 'created';
37
+ }
38
+ else {
39
+ return '';
40
+ }
41
+ }
42
+ exports.getContentypeMergeStatus = getContentypeMergeStatus;
43
+ function createMergeScripts(contentType, content, mergeJobUID) {
44
+ const date = new Date();
45
+ const rootFolder = 'merge_scripts';
46
+ const fileCreatedAt = `${date.getFullYear()}${date.getMonth().toString.length === 1 ? `0${date.getMonth() + 1}` : date.getMonth() + 1}${date.getUTCDate()}${date.getHours()}${date.getMinutes()}${date.getSeconds()}`;
47
+ const mergeScriptsSlug = `merge_scripts_${mergeJobUID}_${fileCreatedAt}`;
48
+ const fullPath = `${rootFolder}/${mergeScriptsSlug}`;
49
+ const { W_OK: writePermission } = fs_1.default.constants;
50
+ const checkPermissions = fs_1.default.accessSync('./', writePermission);
51
+ try {
52
+ if (checkPermissions === undefined) {
53
+ if (!fs_1.default.existsSync(rootFolder)) {
54
+ fs_1.default.mkdirSync(rootFolder);
55
+ }
56
+ if (!fs_1.default.existsSync(fullPath)) {
57
+ fs_1.default.mkdirSync(fullPath);
58
+ }
59
+ fs_1.default.writeFileSync(`${fullPath}/${fileCreatedAt}_${getContentypeMergeStatus(contentType.status)}_${contentType.uid}.js`, content, 'utf-8');
60
+ }
61
+ return fullPath;
62
+ }
63
+ catch (error) {
64
+ console.log(error);
65
+ }
66
+ }
67
+ exports.createMergeScripts = createMergeScripts;
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deleteBranch = void 0;
4
+ const cli_utilities_1 = require("@contentstack/cli-utilities");
5
+ const _1 = require(".");
6
+ async function deleteBranch(host, apiKey, uid) {
7
+ const managementAPIClient = await (0, cli_utilities_1.managementSDKClient)({ host });
8
+ return managementAPIClient
9
+ .stack({ api_key: apiKey })
10
+ .branch(uid)
11
+ .delete()
12
+ .then(() => cli_utilities_1.cliux.success(`Branch with UID '${uid}' has been deleted`))
13
+ .then(() => (0, _1.refreshbranchConfig)(apiKey, uid))
14
+ .catch((err) => {
15
+ var _a;
16
+ if (err.errorCode === 905) {
17
+ cli_utilities_1.cliux.error(`error: Branch with UID ${uid} does not exist`);
18
+ }
19
+ else if (err.errorCode === 909) {
20
+ let errorMsg;
21
+ if ((_a = err.errors) === null || _a === void 0 ? void 0 : _a.branch) {
22
+ const errorOutput = err.errors.branch[0];
23
+ errorMsg = `${err.errorMessage} ${errorOutput}`;
24
+ }
25
+ else {
26
+ errorMsg = err.errorMessage;
27
+ }
28
+ cli_utilities_1.cliux.error(`error: ${errorMsg}`);
29
+ }
30
+ else {
31
+ cli_utilities_1.cliux.error(`error: ${err.errorMessage}`);
32
+ }
33
+ });
34
+ }
35
+ exports.deleteBranch = deleteBranch;