@contentstack/cli-cm-import 1.5.10 → 1.6.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.
Files changed (110) hide show
  1. package/README.md +6 -14
  2. package/bin/dev +17 -0
  3. package/bin/dev.cmd +3 -0
  4. package/bin/run +6 -0
  5. package/bin/run.cmd +3 -0
  6. package/lib/commands/cm/stacks/import.d.ts +10 -0
  7. package/lib/commands/cm/stacks/import.js +111 -0
  8. package/lib/config/index.d.ts +3 -0
  9. package/lib/config/index.js +372 -0
  10. package/lib/import/index.d.ts +1 -0
  11. package/lib/import/index.js +8 -0
  12. package/lib/import/module-importer.d.ts +13 -0
  13. package/lib/import/module-importer.js +70 -0
  14. package/lib/import/modules/assets.d.ts +63 -0
  15. package/lib/import/modules/assets.js +265 -0
  16. package/lib/import/modules/base-class.d.ts +69 -0
  17. package/lib/import/modules/base-class.js +165 -0
  18. package/lib/import/modules/index.d.ts +2 -0
  19. package/lib/import/modules/index.js +19 -0
  20. package/lib/import/modules/locales.d.ts +31 -0
  21. package/lib/import/modules/locales.js +152 -0
  22. package/lib/import/modules-js/assets.d.ts +33 -0
  23. package/lib/import/modules-js/assets.js +415 -0
  24. package/lib/import/modules-js/content-types.d.ts +33 -0
  25. package/lib/import/modules-js/content-types.js +176 -0
  26. package/lib/import/modules-js/custom-roles.d.ts +15 -0
  27. package/lib/import/modules-js/custom-roles.js +141 -0
  28. package/lib/import/modules-js/entries.d.ts +54 -0
  29. package/lib/import/modules-js/entries.js +1260 -0
  30. package/lib/import/modules-js/environments.d.ts +13 -0
  31. package/lib/import/modules-js/environments.js +85 -0
  32. package/lib/import/modules-js/extensions.d.ts +17 -0
  33. package/lib/import/modules-js/extensions.js +86 -0
  34. package/lib/import/modules-js/global-fields.d.ts +13 -0
  35. package/lib/import/modules-js/global-fields.js +109 -0
  36. package/lib/import/modules-js/index.d.ts +1 -0
  37. package/lib/import/modules-js/index.js +33 -0
  38. package/lib/import/modules-js/labels.d.ts +20 -0
  39. package/lib/import/modules-js/labels.js +148 -0
  40. package/lib/import/modules-js/locales.d.ts +24 -0
  41. package/lib/import/modules-js/locales.js +196 -0
  42. package/lib/import/modules-js/marketplace-apps.d.ts +60 -0
  43. package/lib/import/modules-js/marketplace-apps.js +409 -0
  44. package/lib/import/modules-js/webhooks.d.ts +17 -0
  45. package/lib/import/modules-js/webhooks.js +85 -0
  46. package/lib/import/modules-js/workflows.d.ts +18 -0
  47. package/lib/import/modules-js/workflows.js +132 -0
  48. package/lib/types/default-config.d.ts +130 -0
  49. package/lib/types/default-config.js +2 -0
  50. package/lib/types/import-config.d.ts +51 -0
  51. package/lib/types/import-config.js +2 -0
  52. package/lib/types/index.d.ts +30 -0
  53. package/lib/types/index.js +2 -0
  54. package/lib/utils/asset-helper.d.ts +4 -0
  55. package/lib/utils/asset-helper.js +387 -0
  56. package/lib/utils/backup-handler.d.ts +2 -0
  57. package/lib/utils/backup-handler.js +31 -0
  58. package/lib/utils/common-helper.d.ts +20 -0
  59. package/lib/utils/common-helper.js +244 -0
  60. package/lib/utils/content-type-helper.d.ts +49 -0
  61. package/lib/utils/content-type-helper.js +143 -0
  62. package/lib/utils/entries-helper.d.ts +4 -0
  63. package/lib/utils/entries-helper.js +252 -0
  64. package/lib/utils/extension-helper.d.ts +10 -0
  65. package/lib/utils/extension-helper.js +72 -0
  66. package/lib/utils/file-helper.d.ts +14 -0
  67. package/lib/utils/file-helper.js +140 -0
  68. package/lib/utils/import-config-handler.d.ts +3 -0
  69. package/lib/utils/import-config-handler.js +73 -0
  70. package/lib/utils/index.d.ts +12 -0
  71. package/lib/utils/index.js +29 -0
  72. package/lib/utils/interactive.d.ts +2 -0
  73. package/lib/utils/interactive.js +23 -0
  74. package/lib/utils/logger.d.ts +8 -0
  75. package/lib/utils/logger.js +154 -0
  76. package/lib/utils/login-handler.d.ts +8 -0
  77. package/lib/utils/login-handler.js +53 -0
  78. package/lib/utils/marketplace-app-helper.d.ts +4 -0
  79. package/lib/utils/marketplace-app-helper.js +31 -0
  80. package/messages/index.json +1 -7
  81. package/oclif.manifest.json +2 -2
  82. package/package.json +47 -21
  83. package/src/app.js +0 -217
  84. package/src/commands/cm/stacks/import.js +0 -161
  85. package/src/config/default.js +0 -352
  86. package/src/lib/import/assets.js +0 -495
  87. package/src/lib/import/content-types.js +0 -201
  88. package/src/lib/import/custom-roles.js +0 -169
  89. package/src/lib/import/entries.js +0 -1480
  90. package/src/lib/import/environments.js +0 -106
  91. package/src/lib/import/extensions.js +0 -108
  92. package/src/lib/import/global-fields.js +0 -135
  93. package/src/lib/import/labels.js +0 -175
  94. package/src/lib/import/locales.js +0 -216
  95. package/src/lib/import/marketplace-apps.js +0 -542
  96. package/src/lib/import/webhooks.js +0 -113
  97. package/src/lib/import/workflows.js +0 -166
  98. package/src/lib/util/extensionsUidReplace.js +0 -67
  99. package/src/lib/util/fs.js +0 -124
  100. package/src/lib/util/import-flags.js +0 -187
  101. package/src/lib/util/index.js +0 -222
  102. package/src/lib/util/log.js +0 -144
  103. package/src/lib/util/login.js +0 -58
  104. package/src/lib/util/lookupReplaceAssets.js +0 -366
  105. package/src/lib/util/lookupReplaceEntries.js +0 -250
  106. package/src/lib/util/marketplace-app-helper.js +0 -31
  107. package/src/lib/util/removeReferenceFields.js +0 -59
  108. package/src/lib/util/schemaTemplate.js +0 -38
  109. package/src/lib/util/supress-mandatory-fields.js +0 -34
  110. package/src/lib/util/upload.js +0 -56
@@ -0,0 +1,154 @@
1
+ "use strict";
2
+ /*!
3
+ * Contentstack Export
4
+ * Copyright (c) 2019 Contentstack LLC
5
+ * MIT Licensed
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.unlinkFileLogger = exports.log = void 0;
9
+ const tslib_1 = require("tslib");
10
+ const winston = tslib_1.__importStar(require("winston"));
11
+ const path = tslib_1.__importStar(require("path"));
12
+ const mkdirp_1 = tslib_1.__importDefault(require("mkdirp"));
13
+ const slice = Array.prototype.slice;
14
+ const ansiRegexPattern = [
15
+ '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
16
+ '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))',
17
+ ].join('|');
18
+ function returnString(args) {
19
+ var returnStr = '';
20
+ if (args && args.length) {
21
+ returnStr = args
22
+ .map(function (item) {
23
+ if (item && typeof item === 'object') {
24
+ try {
25
+ return JSON.stringify(item).replace(/authtoken\":\d"blt................/g, 'authtoken":"blt....');
26
+ }
27
+ catch (error) { }
28
+ return item;
29
+ }
30
+ return item;
31
+ })
32
+ .join(' ')
33
+ .trim();
34
+ }
35
+ returnStr = returnStr.replace(new RegExp(ansiRegexPattern, 'g'), '').trim();
36
+ return returnStr;
37
+ }
38
+ var myCustomLevels = {
39
+ levels: {
40
+ warn: 1,
41
+ info: 2,
42
+ debug: 3,
43
+ },
44
+ colors: {
45
+ //colors aren't being used anywhere as of now, we're using chalk to add colors while logging
46
+ info: 'blue',
47
+ debug: 'green',
48
+ warn: 'yellow',
49
+ error: 'red',
50
+ },
51
+ };
52
+ let logger;
53
+ let errorLogger;
54
+ let successTransport;
55
+ let errorTransport;
56
+ function init(_logPath) {
57
+ if (!logger || !errorLogger) {
58
+ var logsDir = path.resolve(_logPath, 'logs', 'export');
59
+ // Create dir if doesn't already exist
60
+ mkdirp_1.default.sync(logsDir);
61
+ successTransport = {
62
+ filename: path.join(logsDir, 'success.log'),
63
+ maxFiles: 20,
64
+ maxsize: 1000000,
65
+ tailable: true,
66
+ level: 'info',
67
+ };
68
+ errorTransport = {
69
+ filename: path.join(logsDir, 'error.log'),
70
+ maxFiles: 20,
71
+ maxsize: 1000000,
72
+ tailable: true,
73
+ level: 'error',
74
+ };
75
+ logger = winston.createLogger({
76
+ transports: [
77
+ new winston.transports.File(successTransport),
78
+ new winston.transports.Console({ format: winston.format.simple() }),
79
+ ],
80
+ levels: myCustomLevels.levels,
81
+ });
82
+ errorLogger = winston.createLogger({
83
+ transports: [
84
+ new winston.transports.File(errorTransport),
85
+ new winston.transports.Console({
86
+ level: 'error',
87
+ format: winston.format.combine(winston.format.colorize({ all: true, colors: { error: 'red' } }), winston.format.simple()),
88
+ }),
89
+ ],
90
+ levels: { error: 0 },
91
+ });
92
+ }
93
+ return {
94
+ log: function (message) {
95
+ let args = slice.call(arguments);
96
+ let logString = returnString(args);
97
+ if (logString) {
98
+ logger.log('info', logString);
99
+ }
100
+ },
101
+ warn: function () {
102
+ let args = slice.call(arguments);
103
+ let logString = returnString(args);
104
+ if (logString) {
105
+ logger.log('warn', logString);
106
+ }
107
+ },
108
+ error: function (message) {
109
+ let args = slice.call(arguments);
110
+ let logString = returnString(args);
111
+ if (logString) {
112
+ errorLogger.log('error', logString);
113
+ }
114
+ },
115
+ debug: function () {
116
+ let args = slice.call(arguments);
117
+ let logString = returnString(args);
118
+ if (logString) {
119
+ logger.log('debug', logString);
120
+ }
121
+ },
122
+ };
123
+ }
124
+ const log = async (config, message, type) => {
125
+ config.data = config.data || path.join(__dirname, 'logs');
126
+ // ignoring the type argument, as we are not using it to create a logfile anymore
127
+ if (type !== 'error') {
128
+ // removed type argument from init method
129
+ init(config.data).log(message);
130
+ }
131
+ else {
132
+ init(config.data).error(message);
133
+ }
134
+ };
135
+ exports.log = log;
136
+ const unlinkFileLogger = () => {
137
+ if (logger) {
138
+ const transports = logger.transports;
139
+ transports.forEach((transport) => {
140
+ if (transport.name === 'file') {
141
+ logger.remove(transport);
142
+ }
143
+ });
144
+ }
145
+ if (errorLogger) {
146
+ const transports = errorLogger.transports;
147
+ transports.forEach((transport) => {
148
+ if (transport.name === 'file') {
149
+ errorLogger.remove(transport);
150
+ }
151
+ });
152
+ }
153
+ };
154
+ exports.unlinkFileLogger = unlinkFileLogger;
@@ -0,0 +1,8 @@
1
+ /*!
2
+ * Contentstack Import
3
+ * Copyright (c) 2019 Contentstack LLC
4
+ * MIT Licensed
5
+ */
6
+ import { ImportConfig } from '../types';
7
+ declare const login: (config: ImportConfig) => Promise<any>;
8
+ export default login;
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ /* eslint-disable max-statements-per-line */
3
+ /* eslint-disable no-console */
4
+ /* eslint-disable no-empty */
5
+ /*!
6
+ * Contentstack Import
7
+ * Copyright (c) 2019 Contentstack LLC
8
+ * MIT Licensed
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ const logger_1 = require("./logger");
12
+ const cli_utilities_1 = require("@contentstack/cli-utilities");
13
+ const login = async (config) => {
14
+ const client = await (0, cli_utilities_1.managementSDKClient)(config);
15
+ if (config.email && config.password) {
16
+ const { user: { authtoken = null } = {} } = await client.login({ email: config.email, password: config.password });
17
+ if (authtoken) {
18
+ config.headers = {
19
+ api_key: config.source_stack,
20
+ access_token: config.access_token,
21
+ authtoken: config.authtoken,
22
+ 'X-User-Agent': 'contentstack-export/v',
23
+ };
24
+ (0, logger_1.log)(config, 'Contentstack account authenticated successfully!', 'success');
25
+ return config;
26
+ }
27
+ else {
28
+ throw new Error('Invalid auth token received after login');
29
+ }
30
+ }
31
+ else if (config.management_token) {
32
+ return config;
33
+ }
34
+ else if ((0, cli_utilities_1.isAuthenticated)()) {
35
+ const stackAPIClient = client.stack({
36
+ api_key: config.target_stack,
37
+ management_token: config.management_token,
38
+ });
39
+ const stack = await stackAPIClient.fetch().catch((error) => {
40
+ var _a;
41
+ let errorstack_key = (_a = error === null || error === void 0 ? void 0 : error.errors) === null || _a === void 0 ? void 0 : _a.api_key;
42
+ if (errorstack_key) {
43
+ (0, logger_1.log)(config, 'Stack Api key ' + errorstack_key[0] + 'Please enter valid Key', 'error');
44
+ throw error;
45
+ }
46
+ (0, logger_1.log)(config, error === null || error === void 0 ? void 0 : error.errorMessage, 'error');
47
+ throw error;
48
+ });
49
+ config.destinationStackName = stack.name;
50
+ return config;
51
+ }
52
+ };
53
+ exports.default = login;
@@ -0,0 +1,4 @@
1
+ import { HttpClient } from '@contentstack/cli-utilities';
2
+ import { ImportConfig } from '../types';
3
+ export declare const getAllStackSpecificApps: (developerHubBaseUrl: string, httpClient: HttpClient, config: ImportConfig) => Promise<any>;
4
+ export declare const getDeveloperHubUrl: (config: ImportConfig) => Promise<string>;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getDeveloperHubUrl = exports.getAllStackSpecificApps = void 0;
4
+ const cli_utilities_1 = require("@contentstack/cli-utilities");
5
+ const logger_1 = require("./logger");
6
+ const { formatError } = require('.');
7
+ const getAllStackSpecificApps = (developerHubBaseUrl, httpClient, config) => {
8
+ return httpClient
9
+ .get(`${developerHubBaseUrl}/installations?target_uids=${config.target_stack}`)
10
+ .then(({ data }) => data.data)
11
+ .catch((error) => (0, logger_1.log)(config, `Failed to export marketplace-apps ${formatError(error)}`, 'error'));
12
+ };
13
+ exports.getAllStackSpecificApps = getAllStackSpecificApps;
14
+ const getDeveloperHubUrl = async (config) => {
15
+ const { cma, name } = cli_utilities_1.configHandler.get('region') || {};
16
+ let developerHubBaseUrl = config.developerHubUrls[cma];
17
+ if (!developerHubBaseUrl) {
18
+ developerHubBaseUrl = await cli_utilities_1.cliux.inquire({
19
+ type: 'input',
20
+ name: 'name',
21
+ validate: (url) => {
22
+ if (!url)
23
+ return "Developer-hub URL can't be empty.";
24
+ return true;
25
+ },
26
+ message: `Enter the developer-hub base URL for the ${name} region -`,
27
+ });
28
+ }
29
+ return developerHubBaseUrl.startsWith('http') ? developerHubBaseUrl : `https://${developerHubBaseUrl}`;
30
+ };
31
+ exports.getDeveloperHubUrl = getDeveloperHubUrl;
@@ -1,7 +1 @@
1
- {
2
- "promptMessageList": {
3
- "promptMasterLocale": "Provide the master locale of the destination stack",
4
- "promptTargetStack": "Provide the API Key of the destination stack",
5
- "promptPathStoredData": "Provide the path of the stored content"
6
- }
7
- }
1
+ {}
@@ -1,9 +1,9 @@
1
1
  {
2
- "version": "1.5.10",
2
+ "version": "1.6.0",
3
3
  "commands": {
4
4
  "cm:stacks:import": {
5
5
  "id": "cm:stacks:import",
6
- "description": "Import script for importing the content into the new stack\n...\nOnce you export content from the source stack, import it to your destination stack by using the cm:stacks:import command.\n",
6
+ "description": "Import content from a stack",
7
7
  "strict": true,
8
8
  "usage": "cm:stacks:import [-c <value>] [-k <value>] [-d <value>] [-a <value>] [--module <value>] [--backup-dir <value>] [--branch <value>] [--import-webhook-status disable|current]",
9
9
  "pluginName": "@contentstack/cli-cm-import",
package/package.json CHANGED
@@ -1,42 +1,77 @@
1
1
  {
2
2
  "name": "@contentstack/cli-cm-import",
3
3
  "description": "Contentstack CLI plugin to import content into stack",
4
- "version": "1.5.10",
4
+ "version": "1.6.0",
5
5
  "author": "Contentstack",
6
6
  "bugs": "https://github.com/contentstack/cli/issues",
7
7
  "dependencies": {
8
- "@contentstack/cli-command": "^1.2.9",
9
- "@contentstack/cli-utilities": "^1.4.5",
8
+ "@contentstack/cli-command": "^1.2.0",
9
+ "@contentstack/cli-utilities": "^1.5.0",
10
+ "@contentstack/management": "^1.8.0",
10
11
  "@oclif/config": "^1.18.3",
12
+ "@oclif/core": "^2.3.0",
11
13
  "big-json": "^3.2.0",
12
14
  "bluebird": "^3.7.2",
13
15
  "chalk": "^4.1.2",
14
16
  "debug": "^4.1.0",
15
- "fs-extra": "^11.1.1",
16
17
  "lodash": "^4.17.20",
17
18
  "marked": "^4.0.17",
19
+ "merge": "^2.1.1",
18
20
  "mkdirp": "^1.0.4",
21
+ "ncp": "^2.0.0",
19
22
  "promise-limit": "^2.7.0",
23
+ "tslib": "^2.4.1",
20
24
  "winston": "^3.7.2"
21
25
  },
22
26
  "devDependencies": {
23
27
  "@oclif/test": "^1.2.6",
28
+ "@types/bluebird": "^3.5.38",
29
+ "@types/chai": "^4.2.18",
30
+ "@types/mkdirp": "^1.0.2",
31
+ "@types/mocha": "^8.2.2",
32
+ "@types/ncp": "^2.0.5",
33
+ "@types/node": "^14.14.32",
34
+ "@types/sinon": "^10.0.2",
35
+ "@types/tar": "^4.0.3",
36
+ "@typescript-eslint/eslint-plugin": "^5.48.2",
24
37
  "chai": "^4.2.0",
25
38
  "eslint": "^8.18.0",
26
39
  "eslint-config-oclif": "^4.0.0",
27
40
  "globby": "^10.0.2",
28
41
  "mocha": "^10.0.0",
29
42
  "nyc": "^15.1.0",
30
- "oclif": "^3.8.1"
43
+ "oclif": "^3.8.1",
44
+ "rimraf": "^2.7.1",
45
+ "sinon": "^11.1.1",
46
+ "tmp": "^0.2.1",
47
+ "ts-node": "^10.9.1",
48
+ "typescript": "^4.9.3"
49
+ },
50
+ "scripts": {
51
+ "build": "npm run clean && npm run compile",
52
+ "clean": "rm -rf ./lib ./node_modules tsconfig.build.tsbuildinfo",
53
+ "compile": "tsc -b tsconfig.json",
54
+ "postpack": "rm -f oclif.manifest.json",
55
+ "prepack": "pnpm compile && oclif manifest && oclif readme",
56
+ "version": "oclif readme && git add README.md",
57
+ "test:report": "tsc -p test && nyc --reporter=lcov --extension .ts mocha --forbid-only \"test/**/*.test.ts\"",
58
+ "pretest": "tsc -p test",
59
+ "test": "nyc --extension .ts mocha --forbid-only \"test/**/*.test.ts\"",
60
+ "posttest": "npm run lint",
61
+ "lint": "eslint src/**/*.ts",
62
+ "format": "eslint src/**/*.ts --fix",
63
+ "test:integration": "mocha --forbid-only \"test/run.test.js\" --integration-test --timeout 60000",
64
+ "test:unit": "mocha --forbid-only \"test/unit/*.test.ts\""
31
65
  },
32
66
  "engines": {
33
67
  "node": ">=14.0.0"
34
68
  },
35
69
  "files": [
70
+ "/bin",
71
+ "/lib",
72
+ "/messages",
36
73
  "/npm-shrinkwrap.json",
37
- "/oclif.manifest.json",
38
- "/src",
39
- "/messages"
74
+ "/oclif.manifest.json"
40
75
  ],
41
76
  "homepage": "https://github.com/contentstack/cli",
42
77
  "keywords": [
@@ -44,19 +79,10 @@
44
79
  "cli",
45
80
  "plugin"
46
81
  ],
47
- "scripts": {
48
- "pack": "npm pack && mv *.tgz ../../build",
49
- "postpack": "rm -f oclif.manifest.json",
50
- "prepack": "oclif manifest && oclif readme",
51
- "test": "nyc mocha --forbid-only \"test/**/*.test.js\"",
52
- "version": "oclif readme && git add README.md",
53
- "test:integration": "mocha --forbid-only \"test/run.test.js\" --integration-test --timeout 60000",
54
- "clean": "rm -rf ./node_modules tsconfig.build.tsbuildinfo"
55
- },
56
- "main": "./src/commands/cm/stacks/import.js",
82
+ "main": "./lib/commands/cm/stacks/import.js",
57
83
  "license": "MIT",
58
84
  "oclif": {
59
- "commands": "./src/commands",
85
+ "commands": "./lib/commands",
60
86
  "bin": "csdx",
61
87
  "repositoryPrefix": "<%- repo %>/blob/main/packages/contentstack-import/<%- commandPath %>"
62
88
  },
@@ -66,8 +92,8 @@
66
92
  },
67
93
  "shortCommandName": {
68
94
  "cm:stacks:import": "IMPRT",
69
- "cm:import": "O-IMPRT"
95
+ "cm:import": "IMPRT"
70
96
  }
71
97
  },
72
98
  "repository": "https://github.com/contentstack/cli"
73
- }
99
+ }
package/src/app.js DELETED
@@ -1,217 +0,0 @@
1
- /*!
2
- * Contentstack Import
3
- * Copyright (c) 2019 Contentstack LLC
4
- * MIT Licensed
5
- */
6
-
7
- const fs = require('fs');
8
- const os = require('os');
9
- const path = require('path');
10
- const chalk = require('chalk');
11
- const { copy, copySync, removeSync } = require('fs-extra');
12
- const util = require('./lib/util/index');
13
- const login = require('./lib/util/login');
14
- const { addlogs } = require('./lib/util/log');
15
- const { managementSDKClient, isAuthenticated } = require('@contentstack/cli-utilities');
16
- const { camelCase } = require('lodash')
17
-
18
- exports.initial = (configData) => {
19
- return new Promise(async (resolve, reject) => {
20
- const config = util.initialization(configData);
21
- config.oldPath = config.data;
22
- const APIClient = await managementSDKClient(config);
23
- const stackAPIClient = APIClient.stack({ api_key: config.target_stack, management_token: config.management_token });
24
-
25
- if (configData.branchName) {
26
- await validateIfBranchExist(stackAPIClient, configData, configData.branchName).catch(() => {
27
- process.exit();
28
- });
29
- }
30
-
31
- const backupAndImportData = async (APIClient, stackAPIClient) => {
32
- if (fs.existsSync(config.data)) {
33
- let migrationBackupDirPath = path.join(process.cwd(), '_backup_' + Math.floor(Math.random() * 1000));
34
- return createBackup(migrationBackupDirPath, config)
35
- .then((basePath) => {
36
- config.data = basePath;
37
- return util.sanitizeStack(config);
38
- })
39
- .then(() => {
40
- let importRes;
41
- const types = config.modules.types;
42
-
43
- if (config.moduleName) {
44
- importRes = singleImport(APIClient, stackAPIClient, config.moduleName, types, config);
45
- } else {
46
- importRes = allImport(APIClient, stackAPIClient, config, types);
47
- }
48
-
49
- importRes.then(resolve).catch(reject);
50
- })
51
- .catch((error) => {
52
- addlogs(config, `Failed to import contents. ${util.formatError(error)}`, 'error');
53
- reject(error);
54
- process.exit(1);
55
- });
56
- } else {
57
- let filename = path.basename(config.data);
58
- addlogs(config, chalk.red(`'${filename}' Folder does not exist'`), 'error');
59
- }
60
- };
61
-
62
- if (config) {
63
- if (config.management_token || config.isAuthenticated) {
64
- await backupAndImportData(APIClient, stackAPIClient);
65
- } else if ((config.email && config.password) || isAuthenticated()) {
66
- login(config).then(backupAndImportData(APIClient, stackAPIClient)).catch(reject);
67
- } else if (config.email && config.password) {
68
- login(config)
69
- .then(backupAndImportData.apply(null, [APIClient, stackAPIClient]))
70
- .catch(reject);
71
- } else {
72
- reject('Kindly login or provide management_token');
73
- }
74
- }
75
- });
76
- };
77
-
78
- let singleImport = async (APIClient, stackAPIClient, moduleName, types, config) => {
79
- try {
80
- if (types.indexOf(moduleName) > -1) {
81
- if (!config.master_locale) {
82
- try {
83
- let masterLocalResponse = await util.masterLocalDetails(stackAPIClient);
84
- let master_locale = { code: masterLocalResponse.code };
85
- config['master_locale'] = master_locale;
86
- } catch (error) {
87
- addlogs(config, `Failed to get master locale detail from the stack ${util.formatError(error)}`, 'error');
88
- }
89
- }
90
- let ImportModule = require('./lib/import/' + moduleName);
91
- const importResponse = await new ImportModule(config, stackAPIClient, APIClient).start();
92
- if (moduleName === 'content-types') {
93
- let ctPath = path.resolve(config.data, config.modules.content_types.dirName);
94
- let fieldPath = path.join(ctPath + '/field_rules_uid.json');
95
- if (fieldPath) {
96
- await util.field_rules_update(config, ctPath);
97
- }
98
- }
99
- if (!(importResponse && importResponse.empty)) {
100
- addlogs(config, `Module '${moduleName}' imported successfully!`, 'success');
101
- }
102
- addlogs(config, 'The log for this is stored at ' + path.join(config.oldPath, 'logs', 'import'), 'success');
103
- return true;
104
- } else {
105
- addlogs(config, 'Please provide valid module name.', 'error');
106
- }
107
- } catch (error) {
108
- addlogs(config, `Failed to migrate '${moduleName}'`, 'error');
109
- addlogs(config, util.formatError(error), 'error');
110
- addlogs(config, `The log for this is stored at '${path.join(config.oldPath, 'logs', 'import')}'`, 'error');
111
- }
112
- };
113
-
114
- let allImport = async (APIClient, stackAPIClient, config, types) => {
115
- try {
116
- for (let i = 0; i < types.length; i++) {
117
- let type = types[i];
118
- if (i === 0 && !config.master_locale) {
119
- let masterLocalResponse = await util.masterLocalDetails(stackAPIClient);
120
- let master_locale = { code: masterLocalResponse.code };
121
- config['master_locale'] = master_locale;
122
- }
123
- let ImportModule = require('./lib/import/' + type);
124
- await new ImportModule(config, stackAPIClient, APIClient).start(config);
125
- }
126
- if (config.target_stack && config.source_stack) {
127
- addlogs(
128
- config,
129
- chalk.green(
130
- 'The data of the ' +
131
- (config.sourceStackName || config.source_stack) +
132
- ' stack has been imported into ' +
133
- (config.destinationStackName || config.target_stack) +
134
- ' stack successfully!',
135
- ),
136
- 'success',
137
- );
138
- addlogs(config, 'The log for this is stored at ' + path.join(config.data, 'logs', 'import'), 'success');
139
- } else {
140
- addlogs(
141
- config,
142
- chalk.green(
143
- 'Data has been imported to stack ' + (config.destinationStackName || config.target_stack) + ' succesfully!',
144
- ),
145
- 'success',
146
- );
147
- addlogs(config, 'The log for this is stored at ' + path.join(config.oldPath, 'logs', 'import'), 'success');
148
- }
149
- return true;
150
- } catch (error) {
151
- addlogs(
152
- config,
153
- `Failed to migrate stack '${(config.destinationStackName || config.target_stack)}'. Please check error logs for more info`,
154
- 'error',
155
- );
156
- addlogs(config, util.formatError(error), 'error');
157
- addlogs(config, `The log for this is stored at '${path.join(config.oldPath, 'logs', 'import')}'`, 'error');
158
- }
159
- };
160
-
161
- const createBackup = (backupDirPath, config) => {
162
- return new Promise((resolve, reject) => {
163
- if (config.hasOwnProperty('useBackedupDir') && fs.existsSync(config.useBackedupDir)) {
164
- return resolve(config.useBackedupDir);
165
- }
166
-
167
- if (path.isAbsolute(config.data)) {
168
- copy(config.data, backupDirPath, (error) => {
169
- if (error) {
170
- return reject(error);
171
- }
172
- return resolve(backupDirPath);
173
- });
174
- } else {
175
- //handle mac error :- Cannot copy to a subdirectory of itself
176
- if (config.data === "." || config.data === "./") {
177
- const tempDestination = `${os.platform() === 'darwin' ? '/private/tmp' : '/tmp'}/${camelCase(backupDirPath)}`;
178
- copySync(config.data, tempDestination);
179
- copySync(tempDestination, backupDirPath);
180
- removeSync(tempDestination);
181
- return resolve(backupDirPath);
182
- } else {
183
- copy(config.data, backupDirPath,(error) => {
184
- if (error) {
185
- return reject(error);
186
- }
187
- return resolve(backupDirPath);
188
- });
189
- }
190
- }
191
- });
192
- };
193
-
194
- const validateIfBranchExist = async (stackAPIClient, config, branch) => {
195
- return new Promise(async (resolve, reject) => {
196
- try {
197
- const data = await stackAPIClient
198
- .branch(branch)
199
- .fetch()
200
- .catch((_err) => {});
201
- if (data && typeof data === 'object') {
202
- if (data.error_message) {
203
- addlogs(config, data.error_message, 'error');
204
- addlogs(config, `No branch found with the name '${branch}`, 'error');
205
- reject({ message: 'No branch found with the name ' + branch, error: error_message });
206
- } else {
207
- resolve(data);
208
- }
209
- } else {
210
- reject({ message: 'No branch found with the name ' + branch, error: {} });
211
- }
212
- } catch (error) {
213
- addlogs(config, `No branch found with the name '${branch}`, 'error');
214
- reject({ message: 'No branch found with the name ' + branch, error });
215
- }
216
- });
217
- };