contensis-cli 1.0.12-beta.5 → 1.0.12-beta.7

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.
@@ -1,15 +1,17 @@
1
1
  import { Node } from 'contensis-delivery-api/lib/models';
2
2
  import dayjs from 'dayjs';
3
+ import { deconstructApiError } from './error';
4
+ import { Logger, addNewLines } from './logger';
3
5
  import {
4
6
  BlockVersion,
5
7
  EntriesResult,
6
8
  MigrateModelsResult,
9
+ MigrateNodesTree,
7
10
  MigrateStatus,
8
11
  NodesResult,
9
12
  ProjectNodesToMigrate,
10
13
  } from 'migratortron';
11
14
  import ContensisCli from '~/services/ContensisCliService';
12
- import { Logger } from './logger';
13
15
 
14
16
  const formatDate = (date: Date | string, format = 'DD/MM/YYYY HH:mm') =>
15
17
  dayjs(date).format(format);
@@ -263,46 +265,22 @@ export const printEntriesMigrateResult = (
263
265
  };
264
266
 
265
267
  export const printNodesMigrateResult = (
266
- { log, messages, currentProject }: ContensisCli,
268
+ { log, currentProject }: ContensisCli,
267
269
  migrateResult: NodesResult,
268
270
  {
269
271
  action = 'import',
272
+ logLimit = 50,
270
273
  showDiff = false,
271
274
  showAll = false,
272
275
  showChanged = false,
273
276
  }: {
274
277
  action?: 'import' | 'delete';
278
+ logLimit?: number;
275
279
  showDiff?: boolean;
276
280
  showAll?: boolean;
277
281
  showChanged?: boolean;
278
282
  } = {}
279
283
  ) => {
280
- console.log(``);
281
-
282
- for (const [originalId, migrateNodeId] of Object.entries(
283
- migrateResult.nodesToMigrate.nodeIds
284
- )) {
285
- if (showAll || (showChanged && migrateNodeId.status !== 'no change')) {
286
- console.log(
287
- log.infoText(
288
- `${originalId} ${`${messages.migrate.status(migrateNodeId.status)(
289
- `${migrateNodeId.status}`
290
- )}${
291
- migrateNodeId.id !== originalId ? `-> ${migrateNodeId.id}` : ''
292
- }`}`
293
- ) + ` ${log.helpText(migrateNodeId.path)} ${migrateNodeId.displayName}`
294
- );
295
-
296
- if (migrateNodeId.diff && showDiff)
297
- console.log(
298
- ` ${log.highlightText(`diff:`)} ${log.infoText(
299
- highlightDiffText(migrateNodeId.diff)
300
- )}\n`
301
- );
302
- }
303
- }
304
- if (showAll || showChanged) console.log(``);
305
-
306
284
  for (const [projectId, counts] of Object.entries(migrateResult.nodes || {})) {
307
285
  const importTitle =
308
286
  action === 'delete'
@@ -364,15 +342,18 @@ export const printNodesMigrateResult = (
364
342
  console.log(
365
343
  ` - ${log.errorText(`errors: ${migrateResult.errors.length}`)}\n`
366
344
  );
367
- for (const error of migrateResult.errors) {
368
- let inner = '';
369
- if (error.data?.[0]) {
370
- inner = `${error.data?.[0].Field}: ${error.data?.[0].Message}`;
371
- }
372
- log.error(`${error.message} ${inner}`, null, '');
373
- }
345
+
346
+ log.limits(
347
+ migrateResult.errors
348
+ .map(error => {
349
+ return log.errorText(deconstructApiError(error));
350
+ })
351
+ .join('\n'),
352
+ logLimit
353
+ );
374
354
  }
375
355
  };
356
+
376
357
  const highlightDiffText = (str: string) => {
377
358
  const addedRegex = new RegExp(/<<\+>>(.*?)<<\/\+>>/, 'g');
378
359
  const removedRegex = new RegExp(/<<->>(.*?)<<\/->>/, 'g');
@@ -484,41 +465,124 @@ export const printModelMigrationResult = (
484
465
  };
485
466
 
486
467
  export const printNodeTreeOutput = (
487
- { log }: ContensisCli,
488
- root: Node | undefined
468
+ { log, messages }: ContensisCli,
469
+ root: Node | MigrateNodesTree | undefined,
470
+ logDetail = 'errors',
471
+ logLimit = 1000
489
472
  ) => {
490
- log.object({ ...root, children: undefined });
491
473
  log.raw('');
474
+ const statusColour = messages.migrate.status;
475
+
476
+ if (root && 'status' in root)
477
+ log.info(
478
+ `Migrate status: ${statusColour('no change')(
479
+ 'N'
480
+ )} [no change]; ${statusColour('create')('C')} [create]; ${statusColour(
481
+ 'update'
482
+ )('U')} [update]; ${statusColour('error')('E')} [error];`
483
+ );
492
484
  log.info(
493
- `${log.highlightText('e')} = has entry; ${log.highlightText(
494
- 'c'
495
- )} = canonical; ${log.highlightText('m')} = include in menu`
485
+ `Node properties: ${log.highlightText(
486
+ 'e'
487
+ )} = has entry; ${log.highlightText('c')} = canonical; ${log.highlightText(
488
+ 'm'
489
+ )} = include in menu`
496
490
  );
491
+
497
492
  log.line();
498
493
 
499
- const outputNode = (node: Node | any, spaces: string) =>
500
- `${node.entry ? log.highlightText('e') : log.infoText('-')}${
501
- node.isCanonical ? log.highlightText('c') : log.infoText('-')
494
+ const outputNode = (
495
+ node: Node | MigrateNodesTree,
496
+ spaces: string,
497
+ isRoot = false
498
+ ) => {
499
+ const errorOutput =
500
+ 'error' in node && node.error && deconstructApiError(node.error);
501
+ const fullOutput = logDetail === 'all';
502
+ const changesOutput =
503
+ logDetail === 'changes' &&
504
+ 'status' in node &&
505
+ ['create', 'update'].includes(node.status);
506
+
507
+ const diffOutput =
508
+ (fullOutput || changesOutput || errorOutput) &&
509
+ 'diff' in node &&
510
+ node.diff?.replaceAll('\n', '');
511
+
512
+ return `${
513
+ 'status' in node
514
+ ? `${statusColour(node.status)(
515
+ node.status.substring(0, 1).toUpperCase()
516
+ )} `
517
+ : ''
518
+ }${node.entry ? log.highlightText('e') : log.infoText('-')}${
519
+ 'isCanonical' in node && node.isCanonical
520
+ ? log.highlightText('c')
521
+ : log.infoText('-')
502
522
  }${
503
523
  node.includeInMenu ? log.highlightText('m') : log.infoText('-')
504
- }${spaces}${
505
- node.isCanonical ? log.boldText(`/${node.slug}`) : `/${node.slug}`
506
- }${node.entry ? ` ${log.helpText(node.entry.sys.contentTypeId)}` : ''}${
524
+ }${spaces}${log[
525
+ 'status' in node && node.status === 'no change'
526
+ ? 'infoText'
527
+ : 'standardText'
528
+ ](
529
+ 'isCanonical' in node && node.isCanonical
530
+ ? log.boldText(fullOutput || isRoot ? node.path : `/${node.slug}`)
531
+ : fullOutput || isRoot
532
+ ? node.path
533
+ : `/${node.slug}`
534
+ )}${node.entry ? ` ${log.helpText(node.entry.sys.contentTypeId)}` : ''}${
507
535
  node.childCount ? ` +${node.childCount}` : ``
508
- } ${log.infoText(node.displayName)}`;
536
+ } ${'displayName' in node ? log.infoText(node.displayName) : ''}${
537
+ fullOutput || (changesOutput && node.id !== node.originalId)
538
+ ? `~n ${log.infoText(`id:`)} ${
539
+ node.id === node.originalId
540
+ ? node.id
541
+ : `${node.id} ${log.infoText(`<= ${node.originalId}`)}`
542
+ }`
543
+ : ''
544
+ }${
545
+ (fullOutput ||
546
+ (changesOutput && node.parentId !== node.originalParentId)) &&
547
+ node.parentId
548
+ ? `~n ${log.infoText(
549
+ `parentId: ${
550
+ node.parentId === node.originalParentId
551
+ ? node.parentId
552
+ : `${node.parentId} <= ${node.originalParentId}`
553
+ }`
554
+ )}`
555
+ : ''
556
+ }${
557
+ fullOutput && node.entry?.sys.id
558
+ ? `~n ${log.infoText(`entryId: ${node.entry.sys.id}`)}`
559
+ : ''
560
+ }${
561
+ errorOutput
562
+ ? `~n${addNewLines(` ${log.errorText(errorOutput)}`, '~n')}`
563
+ : ''
564
+ }${
565
+ diffOutput
566
+ ? `~n${addNewLines(
567
+ ` ${log.infoText(`diff: ${highlightDiffText(diffOutput)}`)}`,
568
+ '~n'
569
+ )}`
570
+ : ''
571
+ }`;
572
+ };
509
573
 
510
- const outputChildren = (root: Node | undefined, depth = 2) => {
574
+ const outputChildren = (node: Node | undefined, depth = 2) => {
511
575
  let str = '';
512
- for (const node of (root as any)?.children as Node[]) {
513
- str += `${outputNode(node, Array(depth + 1).join(' '))}\n`;
514
- if ('children' in node) str += outputChildren(node, depth + 1);
576
+ for (const child of ((node as any)?.children || []) as Node[]) {
577
+ str += `${outputNode(child, Array(depth + 1).join(' '))}\n`;
578
+ if ('children' in child) str += outputChildren(child, depth + 1);
515
579
  }
516
580
  return str;
517
581
  };
518
582
 
519
583
  const children = outputChildren(root);
520
584
  log.limits(
521
- `${outputNode(root, ' ')}${children ? `\n${children}` : ''}`,
522
- 100
585
+ `${outputNode(root || {}, ' ', true)}${children ? `\n${children}` : ''}`,
586
+ logLimit
523
587
  );
524
588
  };
@@ -0,0 +1,7 @@
1
+ export const deconstructApiError = (error: MappedError) => {
2
+ let inner = '';
3
+ if (error.data?.[0]) {
4
+ inner = `${error.data?.[0].Field}: ${error.data?.[0].Message}`;
5
+ }
6
+ return `${error.message} ${inner}`;
7
+ };
package/src/util/find.ts CHANGED
@@ -2,7 +2,18 @@ export const findByIdOrName = (arr: any[], idOrName: string, exact = false) =>
2
2
  arr.find(
3
3
  r =>
4
4
  r.id === idOrName ||
5
- r.name.toLowerCase() === idOrName.toLowerCase()
5
+ (typeof r.name === 'string' &&
6
+ r.name.toLowerCase() === idOrName.toLowerCase()) ||
7
+ (typeof r.name === 'object' &&
8
+ Object.values<string>(r.name || {})?.[0].toLowerCase() ===
9
+ idOrName.toLowerCase())
6
10
  ) ||
7
11
  (!exact &&
8
- arr.find(r => r.name.toLowerCase().includes(idOrName.toLowerCase())));
12
+ arr.find(
13
+ r =>
14
+ (typeof r.name === 'string' &&
15
+ r.name.toLowerCase().includes(idOrName.toLowerCase())) ||
16
+ (typeof r.name === 'object' &&
17
+ Object.values<string>(r.name || {})?.[0].toLowerCase() ===
18
+ idOrName.toLowerCase())
19
+ ));
@@ -2,7 +2,12 @@
2
2
  import chalk from 'chalk';
3
3
  import dateFormat from 'dateformat';
4
4
  import deepCleaner from 'deep-cleaner';
5
- import { ansiEscapeCodes, first, strlen } from 'printable-characters';
5
+ import {
6
+ ansiEscapeCodes,
7
+ first,
8
+ partition,
9
+ strlen,
10
+ } from 'printable-characters';
6
11
  // import ProgressBar from 'progress';
7
12
  import { isSysError, tryStringify } from '.';
8
13
 
@@ -225,24 +230,39 @@ export class Logger {
225
230
  else console.log(content);
226
231
  };
227
232
 
228
- static limits = (content: string, displayLength = 30) => {
229
- const consoleWidth = process.stdout.columns;
230
- console.info(
231
- consoleWidth
232
- ? content
233
- .split('\n')
234
- .slice(0, consoleWidth ? displayLength : undefined)
235
- .map((line: string) =>
236
- consoleWidth && strlen(line) > consoleWidth
237
- ? first(line, consoleWidth)
238
- : line
239
- )
240
- .join('\n')
241
- : content.replace(ansiEscapeCodes, '')
242
- );
233
+ static limits = (
234
+ content: string,
235
+ displayLength = 30,
236
+ consoleWidth = process.stdout.columns,
237
+ logMethod: Function = console.info
238
+ ) => {
239
+ if (consoleWidth) {
240
+ content
241
+ .split('\n')
242
+ .slice(0, consoleWidth ? displayLength : undefined)
243
+ .map((line: string) =>
244
+ logMethod(
245
+ line
246
+ .split('~n')
247
+ .map(l =>
248
+ consoleWidth && strlen(l) > consoleWidth
249
+ ? first(l, consoleWidth)
250
+ : l
251
+ )
252
+ .join('\n')
253
+ )
254
+ )
255
+ .join('\n');
256
+ } else {
257
+ logMethod(content.replace(ansiEscapeCodes, ''));
258
+ }
259
+
243
260
  const tableArray = content.split('\n');
244
261
  if (consoleWidth && tableArray.length > displayLength)
245
- console.info(`\n`, `- and ${tableArray.length - displayLength} more...`);
262
+ console.info(
263
+ `\n`,
264
+ `- and ${tableArray.length - displayLength} more...\n`
265
+ );
246
266
  };
247
267
  }
248
268
 
@@ -265,6 +285,59 @@ export const logError: LogErrorFunc = (
265
285
  return null;
266
286
  };
267
287
 
288
+ export const addNewLines = (
289
+ message = '',
290
+ newLineSeparater = '\n',
291
+ atPosition = process.stdout.columns
292
+ ) => {
293
+ if (message === '' || atPosition === 0) {
294
+ return '';
295
+ }
296
+
297
+ let result = '';
298
+ let lengthCounter = 0;
299
+
300
+ // Partition the message string into an array of
301
+ // [nonPrintable, printable][]
302
+ const partitioned = partition(message);
303
+ const addSeparater = () => {
304
+ // If line length counter has exceeded the console width
305
+ // add a new line separater and reset the line length counter
306
+ if (lengthCounter >= atPosition) {
307
+ result += newLineSeparater;
308
+ lengthCounter = 0;
309
+ }
310
+ };
311
+
312
+ // Loop through the partitioned message parts
313
+ for (const [nonPrintable, printable] of partitioned) {
314
+ // Convert string to array as this will provide accurate
315
+ // lengths and splicing methods with all unicode chars
316
+ const textParts = Array.from(printable);
317
+ // Splice the remaining allowable line length from the text parts array
318
+ const text = textParts.splice(0, atPosition - lengthCounter);
319
+ // In the first iteration append the non printable unicode chars
320
+ // to the beginning of the spliced text
321
+ result += nonPrintable + text.join('');
322
+ // Keep a count of the current line length
323
+ // as one line of output could span multiple "partitions"
324
+ lengthCounter += text.length;
325
+ addSeparater();
326
+
327
+ // Handle any remaining text in this "partition"
328
+ while (textParts.length) {
329
+ // Splice the remaining allowable line length from the text parts array
330
+ const text = textParts.splice(0, atPosition - lengthCounter);
331
+ // Append the spliced text to the result
332
+ result += text.join('');
333
+ // Increase line length counter
334
+ lengthCounter += text.length;
335
+ addSeparater();
336
+ }
337
+ }
338
+ return result;
339
+ };
340
+
268
341
  export const progress = {
269
342
  current: { interrupt: (x: string) => {} },
270
343
  active: false,
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const LIB_VERSION = "1.0.12-beta.5";
1
+ export const LIB_VERSION = "1.0.12-beta.7";