@contentstack/cli-cm-export 0.1.1-beta.7 → 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.
@@ -7,55 +7,70 @@
7
7
  * MIT Licensed
8
8
  */
9
9
 
10
- var chalk = require('chalk')
11
- var {addlogs} = require('../util/log')
12
- let stack = require('../util/contentstack-management-sdk')
13
- let client
10
+ var chalk = require('chalk');
11
+ var { addlogs } = require('../util/log');
12
+ let stack = require('../util/contentstack-management-sdk');
13
+ let client;
14
14
 
15
- module.exports.login = config => {
16
- client = stack.Client(config)
15
+ module.exports.login = (config) => {
16
+ client = stack.Client(config);
17
17
  return new Promise(function (resolve, reject) {
18
18
  if (config.email && config.password) {
19
19
  // eslint-disable-next-line no-console
20
- console.log('Logging into Contentstack')
21
- return client.login({email: config.email, password: config.password})
22
- .then(function (response) {
23
- // eslint-disable-next-line no-console
24
- console.log(chalk.green('Contentstack account authenticated successfully!'))
25
- config.authtoken = response.user.authtoken
26
- config.headers = {
27
- api_key: config.source_stack,
28
- access_token: config.access_token,
29
- authtoken: config.authtoken,
30
- 'X-User-Agent': 'contentstack-export/v',
31
- }
32
- return resolve(config)
33
- }).catch(function (error) {
34
- return reject(error)
35
- })
36
- } if (!config.email && !config.password && config.source_stack && config.access_token) {
37
- addlogs(config, chalk.yellow('Content types, entries, assets, labels, global fields, extensions modules will be exported'), 'success')
38
- addlogs(config, chalk.yellow('Email, password, or management token is not set in the config, cannot export Webhook and label modules'), 'success')
20
+ console.log('Logging into Contentstack');
21
+ client
22
+ .login({ email: config.email, password: config.password })
23
+ .then(function (response) {
24
+ // eslint-disable-next-line no-console
25
+ console.log(chalk.green('Contentstack account authenticated successfully!'));
26
+ config.authtoken = response.user.authtoken;
27
+ config.headers = {
28
+ api_key: config.source_stack,
29
+ access_token: config.access_token,
30
+ authtoken: config.authtoken,
31
+ 'X-User-Agent': 'contentstack-export/v',
32
+ };
33
+ resolve(config);
34
+ })
35
+ .catch(function (error) {
36
+ reject(error);
37
+ });
38
+ } else if (!config.email && !config.password && config.source_stack && config.access_token) {
39
+ addlogs(
40
+ config,
41
+ chalk.yellow('Content types, entries, assets, labels, global fields, extensions modules will be exported'),
42
+ 'success',
43
+ );
44
+ addlogs(
45
+ config,
46
+ chalk.yellow(
47
+ 'Email, password, or management token is not set in the config, cannot export Webhook and label modules',
48
+ ),
49
+ 'success',
50
+ );
39
51
  config.headers = {
40
52
  api_key: config.source_stack,
41
53
  access_token: config.access_token,
42
54
  'X-User-Agent': 'contentstack-export/v',
43
- }
44
- return resolve(config)
45
- // eslint-disable-next-line no-else-return
55
+ };
56
+ resolve(config);
57
+ // eslint-disable-next-line no-else-return
46
58
  } else if (config.auth_token && !config.management_token) {
47
- client.stack({api_key: config.source_stack, management_token: config.management_token}).users()
48
- .then(function () {
49
- return resolve()
50
- }).catch(error => {
51
- if (error.errors.api_key) {
52
- return reject(error)
53
- }
54
- addlogs(config, error.errorMessage, 'error')
55
- return reject(error)
56
- })
59
+ client
60
+ .stack({ api_key: config.source_stack, management_token: config.management_token })
61
+ .users()
62
+ .then(function () {
63
+ resolve();
64
+ })
65
+ .catch((error) => {
66
+ if (error.errors.api_key) {
67
+ return reject(error);
68
+ }
69
+ addlogs(config, error.errorMessage, 'error');
70
+ reject(error);
71
+ });
57
72
  } else if (config.management_token) {
58
- return resolve()
73
+ resolve();
59
74
  }
60
- })
61
- }
75
+ });
76
+ };
@@ -0,0 +1,53 @@
1
+ const mkdirp = require('mkdirp');
2
+ const path = require('path');
3
+ const helper = require('./helper');
4
+ const { HttpClient } = require('@contentstack/cli-utilities');
5
+
6
+ const setupBranches = async (config, branch) => {
7
+ if (typeof config !== 'object') {
8
+ throw new Error('Invalid config to setup the branch');
9
+ }
10
+ let branches = [];
11
+ const headers = { api_key: config.source_stack }
12
+
13
+ if (config.auth_token) {
14
+ headers['authtoken'] = config.auth_token
15
+ } else if (config.management_token) {
16
+ headers['authorization'] = config.management_token
17
+ }
18
+
19
+ if (typeof branch === 'string') {
20
+ // check branch exists
21
+ const result = await HttpClient.create()
22
+ .headers(headers)
23
+ .get(`https://${config.host}/v3/stacks/branches/${branch}`);
24
+
25
+ if (result && typeof result.data === 'object' && typeof result.data.branch === 'object') {
26
+ branches.push(result.data.branch);
27
+ } else {
28
+ throw new Error('No branch found with the name ' + branch);
29
+ }
30
+ } else {
31
+ try {
32
+ const result = await HttpClient.create()
33
+ .headers(headers)
34
+ .get(`https://${config.host}/v3/stacks/branches`);
35
+
36
+ if (result && result.data && Array.isArray(result.data.branches) && result.data.branches.length > 0) {
37
+ branches = result.data.branches;
38
+ } else {
39
+ branches.push('main');
40
+ }
41
+ } catch (error) {
42
+ return;
43
+ }
44
+ }
45
+
46
+ mkdirp.sync(config.data);
47
+ // create branch info file
48
+ helper.writeFile(path.join(config.data, 'branches.json'), branches);
49
+ // add branches list in the
50
+ config.branches = branches;
51
+ };
52
+
53
+ module.exports = setupBranches;
@@ -1,123 +0,0 @@
1
- /* eslint-disable complexity */
2
- const {Command, flags} = require('@contentstack/cli-command')
3
- const {configWithMToken,
4
- parameterWithMToken,
5
- withoutParameterMToken,
6
- configWithAuthToken,
7
- parametersWithAuthToken,
8
- withoutParametersWithAuthToken,
9
- } = require('../../lib/util/export-flags')
10
- const Configstore = require('configstore')
11
- const credStore = new Configstore('contentstack_cli')
12
-
13
- class ExportCommand extends Command {
14
- async run() {
15
- const {flags} = this.parse(ExportCommand)
16
- const extConfig = flags.config
17
- let sourceStack = flags['stack-uid']
18
- const alias = flags['management-token-alias']
19
- const authToken = flags['auth-token']
20
- const securedAssets = flags['secured-assets']
21
- const data = flags.data
22
- const moduleName = flags.module
23
- let _authToken = credStore.get('authtoken')
24
- let host = this.region
25
- let cmaHost = host.cma.split('//')
26
- let cdaHost = host.cda.split('//')
27
- host.cma = cmaHost[1]
28
- host.cda = cdaHost[1]
29
-
30
- if (alias && alias !== undefined) {
31
- let managementTokens = this.getToken(alias)
32
- if (managementTokens && managementTokens !== undefined) {
33
- if (extConfig && extConfig !== undefined) {
34
- configWithMToken(
35
- extConfig,
36
- managementTokens,
37
- host,
38
- securedAssets
39
- )
40
- } else if (data) {
41
- parameterWithMToken(
42
- managementTokens,
43
- data,
44
- moduleName,
45
- host,
46
- _authToken,
47
- securedAssets
48
- )
49
- } else if (data === undefined && sourceStack === undefined) {
50
- withoutParameterMToken(
51
- managementTokens,
52
- moduleName,
53
- host,
54
- _authToken,
55
- securedAssets
56
- )
57
- } else {
58
- this.log('Please provide a valid command. Run "csdx cm:export --help" command to view the command usage')
59
- }
60
- } else {
61
- this.log(alias + ' management token is not present, please add managment token first')
62
- }
63
- } else if (authToken && authToken !== undefined && _authToken && _authToken !== undefined) {
64
- if (extConfig && extConfig !== undefined) {
65
- configWithAuthToken(
66
- extConfig,
67
- _authToken,
68
- moduleName,
69
- host,
70
- securedAssets
71
- )
72
- } else if (sourceStack && data) {
73
- return parametersWithAuthToken(
74
- _authToken,
75
- sourceStack,
76
- data,
77
- moduleName,
78
- host,
79
- securedAssets
80
- )
81
- } else if (data === undefined && sourceStack === undefined) {
82
- withoutParametersWithAuthToken(
83
- _authToken,
84
- moduleName,
85
- host,
86
- securedAssets
87
- )
88
- } else {
89
- this.log('Please provide a valid command. Run "csdx cm:export --help" command to view the command usage')
90
- }
91
- } else {
92
- this.log('Provide the alias for management token or auth token')
93
- }
94
- // return
95
- }
96
- }
97
-
98
- ExportCommand.description = `Export content from a stack
99
- ...
100
- Export content from one stack to another
101
- `
102
- ExportCommand.examples = [
103
- 'csdx cm:export -A',
104
- 'csdx cm:export -A -s <stack_ApiKey> -d <path/of/export/destination/dir>',
105
- 'csdx cm:export -A -c <path/to/config/dir>',
106
- 'csdx cm:export -A -m <single module name>',
107
- 'csdx cm:export -A --secured-assets',
108
- 'csdx cm:export -a <management_token_alias>',
109
- 'csdx cm:export -a <management_token_alias> -d <path/to/export/destination/dir>',
110
- 'csdx cm:export -a <management_token_alias> -c <path/to/config/file>'
111
- ]
112
-
113
- ExportCommand.flags = {
114
- config: flags.string({char: 'c', description: '[optional] path of the config'}),
115
- 'stack-uid': flags.string({char: 's', description: 'API key of the source stack'}),
116
- data: flags.string({char: 'd', description: 'path or location to store the data'}),
117
- 'management-token-alias': flags.string({char: 'a', description: 'alias of the management token'}),
118
- 'auth-token': flags.boolean({char: 'A', description: 'to use auth token'}),
119
- module: flags.string({char: 'm', description: '[optional] specific module name'}),
120
- 'secured-assets': flags.boolean({description: '[optional] use when assets are secured'}),
121
- }
122
-
123
- module.exports = ExportCommand
@@ -1,83 +0,0 @@
1
- /*!
2
- * Contentstack Export
3
- * Copyright (c) 2019 Contentstack LLC
4
- * MIT Licensed
5
- */
6
-
7
- 'use strict';
8
-
9
- var Bluebird = require('bluebird');
10
- var request = Bluebird.promisify(require('request'));
11
- var debug = require('debug')('util:requests');
12
- //var pkg = require('../../package');
13
- var app = require('../../app');
14
-
15
- var MAX_RETRY_LIMIT = 8;
16
-
17
- function validate(req) {
18
- if (typeof req !== 'object') {
19
- throw new Error(`Invalid params passed for request\n${JSON.stringify(arguments)}`);
20
- }
21
- if (typeof req.uri === 'undefined' && typeof req.url === 'undefined') {
22
- throw new Error(`Missing uri in request!\n${JSON.stringify(req)}`);
23
- }
24
- if (typeof req.method === 'undefined') {
25
- debug(`${req.uri || req.url} had no method, setting it as 'GET'`);
26
- req.method = 'GET';
27
- }
28
- if (typeof req.json === 'undefined') {
29
- req.json = true;
30
- }
31
- if (typeof req.headers === 'undefined') {
32
- debug(`${req.uri || req.url} had no headers`);
33
- var config = app.getConfig();
34
- req.headers = config.headers;
35
- }
36
- }
37
-
38
- var makeCall = module.exports = function(req, RETRY) {
39
- return new Bluebird(function (resolve, reject) {
40
- try {
41
- validate(req);
42
- if (typeof RETRY !== 'number') {
43
- RETRY = 1;
44
- } else if (RETRY > MAX_RETRY_LIMIT) {
45
- return reject(new Error('Max retry limit exceeded!'));
46
- }
47
- debug(`${req.method.toUpperCase()}: ${req.uri || req.url}`);
48
- return request(req).then(function (response) {
49
- var timeDelay;
50
- if (response.statusCode >= 200 && response.statusCode <= 399) {
51
- return resolve(response);
52
- } else if (response.statusCode === 429) {
53
- timeDelay = Math.pow(Math.SQRT2, RETRY) * 100;
54
- debug(`API rate limit exceeded.\nReceived ${response.statusCode} status\nBody ${JSON.stringify(response)}`);
55
- debug(`Retrying ${req.uri || req.url} with ${timeDelay} sec delay`);
56
- return setTimeout(function (req, RETRY) {
57
- return makeCall(req, RETRY)
58
- .then(resolve)
59
- .catch(reject);
60
- }, timeDelay, req, RETRY);
61
- } else if (response.statusCode >= 500) {
62
- // retry, with delay
63
- timeDelay = Math.pow(Math.SQRT2, RETRY) * 100;
64
- debug(`Recevied ${response.statusCode} status\nBody ${JSON.stringify(response)}`);
65
- debug(`Retrying ${req.uri || req.url} with ${timeDelay} sec delay`);
66
- RETRY++;
67
- return setTimeout(function (req, RETRY) {
68
- return makeCall(req, RETRY)
69
- .then(resolve)
70
- .catch(reject);
71
- }, timeDelay, req, RETRY);
72
- } else {
73
- debug(`Request failed\n${JSON.stringify(req)}`);
74
- debug(`Response received\n${JSON.stringify(response)}`);
75
- return reject(response);
76
- }
77
- }).catch(reject);
78
- } catch (error) {
79
- debug(error);
80
- return reject(error);
81
- }
82
- });
83
- };