@contentstack/cli-cm-export 0.1.1-beta.8 → 0.1.1-beta.9

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.
package/README.md CHANGED
@@ -18,7 +18,7 @@ $ npm install -g @contentstack/cli-cm-export
18
18
  $ csdx COMMAND
19
19
  running command...
20
20
  $ csdx (-v|--version|version)
21
- @contentstack/cli-cm-export/0.1.1-beta.8 linux-x64 node-v12.22.1
21
+ @contentstack/cli-cm-export/0.1.1-beta.9 linux-x64 node-v12.18.4
22
22
  $ csdx --help [COMMAND]
23
23
  USAGE
24
24
  $ csdx COMMAND
@@ -41,11 +41,13 @@ USAGE
41
41
 
42
42
  OPTIONS
43
43
  -A, --auth-token to use auth token
44
+ -B, --branch=branch [optional] branch name
44
45
  -a, --management-token-alias=management-token-alias alias of the management token
45
46
  -c, --config=config [optional] path of the config
46
47
  -d, --data=data path or location to store the data
47
48
  -m, --module=module [optional] specific module name
48
49
  -s, --stack-uid=stack-uid API key of the source stack
50
+ -t, --content-type=content-type [optional] content type
49
51
  --secured-assets [optional] use when assets are secured
50
52
 
51
53
  DESCRIPTION
@@ -61,7 +63,10 @@ EXAMPLES
61
63
  csdx cm:export -a <management_token_alias>
62
64
  csdx cm:export -a <management_token_alias> -d <path/to/export/destination/dir>
63
65
  csdx cm:export -a <management_token_alias> -c <path/to/config/file>
66
+ csdx cm:export -A -m <single module name>
67
+ csdx cm:export -A -m <single module name> -t <content type>
68
+ csdx cm:export -A -B [optional] branch name
64
69
  ```
65
70
 
66
- _See code: [src/commands/cm/export.js](https://github.com/contentstack/cli/blob/v0.1.1-beta.8/packages/contentstack-export/src/commands/cm/export.js)_
71
+ _See code: [src/commands/cm/export.js](https://github.com/contentstack/cli/blob/v0.1.1-beta.9/packages/contentstack-export/src/commands/cm/export.js)_
67
72
  <!-- commandsstop -->
@@ -1 +1 @@
1
- {"version":"0.1.1-beta.8","commands":{"cm:export":{"id":"cm:export","description":"Export content from a stack\n...\nExport content from one stack to another\n","pluginName":"@contentstack/cli-cm-export","pluginType":"core","aliases":[],"examples":["csdx cm:export -A","csdx cm:export -A -s <stack_ApiKey> -d <path/of/export/destination/dir>","csdx cm:export -A -c <path/to/config/dir>","csdx cm:export -A -m <single module name>","csdx cm:export -A --secured-assets","csdx cm:export -a <management_token_alias>","csdx cm:export -a <management_token_alias> -d <path/to/export/destination/dir>","csdx cm:export -a <management_token_alias> -c <path/to/config/file>"],"flags":{"config":{"name":"config","type":"option","char":"c","description":"[optional] path of the config"},"stack-uid":{"name":"stack-uid","type":"option","char":"s","description":"API key of the source stack"},"data":{"name":"data","type":"option","char":"d","description":"path or location to store the data"},"management-token-alias":{"name":"management-token-alias","type":"option","char":"a","description":"alias of the management token"},"auth-token":{"name":"auth-token","type":"boolean","char":"A","description":"to use auth token","allowNo":false},"module":{"name":"module","type":"option","char":"m","description":"[optional] specific module name"},"secured-assets":{"name":"secured-assets","type":"boolean","description":"[optional] use when assets are secured","allowNo":false}},"args":[]}}}
1
+ {"version":"0.1.1-beta.9","commands":{"cm:export":{"id":"cm:export","description":"Export content from a stack\n...\nExport content from one stack to another\n","pluginName":"@contentstack/cli-cm-export","pluginType":"core","aliases":[],"examples":["csdx cm:export -A","csdx cm:export -A -s <stack_ApiKey> -d <path/of/export/destination/dir>","csdx cm:export -A -c <path/to/config/dir>","csdx cm:export -A -m <single module name>","csdx cm:export -A --secured-assets","csdx cm:export -a <management_token_alias>","csdx cm:export -a <management_token_alias> -d <path/to/export/destination/dir>","csdx cm:export -a <management_token_alias> -c <path/to/config/file>","csdx cm:export -A -m <single module name>","csdx cm:export -A -m <single module name> -t <content type>","csdx cm:export -A -B [optional] branch name"],"flags":{"config":{"name":"config","type":"option","char":"c","description":"[optional] path of the config"},"stack-uid":{"name":"stack-uid","type":"option","char":"s","description":"API key of the source stack"},"data":{"name":"data","type":"option","char":"d","description":"path or location to store the data"},"management-token-alias":{"name":"management-token-alias","type":"option","char":"a","description":"alias of the management token"},"auth-token":{"name":"auth-token","type":"boolean","char":"A","description":"to use auth token","allowNo":false},"module":{"name":"module","type":"option","char":"m","description":"[optional] specific module name"},"content-type":{"name":"content-type","type":"option","char":"t","description":"[optional] content type"},"branch":{"name":"branch","type":"option","char":"B","description":"[optional] branch name"},"secured-assets":{"name":"secured-assets","type":"boolean","description":"[optional] use when assets are secured","allowNo":false}},"args":[]}}}
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@contentstack/cli-cm-export",
3
3
  "description": "Contentstack CLI plugin to export content from stack",
4
- "version": "0.1.1-beta.8",
4
+ "version": "0.1.1-beta.9",
5
5
  "author": "Contentstack",
6
6
  "bugs": "https://github.com/contentstack/cli/issues",
7
7
  "dependencies": {
8
8
  "@contentstack/cli-command": "0.1.0-beta",
9
- "@contentstack/management": "^1.2.1",
9
+ "@contentstack/management": "github:contentstack/contentstack-management-javascript#65e8588",
10
10
  "@oclif/command": "^1.6.1",
11
11
  "@oclif/config": "^1.15.1",
12
12
  "async": "^3.2.0",
package/src/app.js CHANGED
@@ -1,90 +1,157 @@
1
1
  /* eslint-disable no-redeclare */
2
- var util = require('./lib/util')
3
- var login = require('./lib/util/login')
4
- var {addlogs} = require('./lib/util/log')
5
- const chalk = require('chalk')
6
- let path = require('path')
7
- let _ = require('lodash')
2
+ var util = require("./lib/util");
3
+ var login = require("./lib/util/login");
4
+ var { addlogs } = require("./lib/util/log");
5
+ const setupBranches = require("./lib/util/setup-branches");
6
+ const chalk = require("chalk");
7
+ let path = require("path");
8
+ let _ = require("lodash");
9
+ const cli = require("cli-ux");
8
10
 
9
11
  exports.initial = async function (config) {
10
12
  return new Promise(function (resolve, reject) {
11
- config = util.buildAppConfig(config)
12
- util.validateConfig(config)
13
+ config = util.buildAppConfig(config);
14
+ util.validateConfig(config);
13
15
  exports.getConfig = function () {
14
- return config
15
- }
16
+ return config;
17
+ };
16
18
  // try {
17
- login.login(config).then(async function () {
18
- var types = config.modules.types
19
- if (config.moduleName && config.moduleName !== undefined) {
20
- singleExport(config.moduleName, types, config)
21
- return resolve()
22
- } else {
23
- allExport(config, types).then(() => {
24
- return resolve()
25
- })
26
- }
27
- }).catch(error => {
28
- if (error.errors.api_key) {
29
- addlogs(config, chalk.red('Stack Api key ' + error.errors.api_key[0], 'Please enter valid Key', 'error'))
30
- addlogs(config, 'The log for this is stored at ' + config.data + '/export/logs', 'success')
31
- } else {
32
- let objKey = Object.keys(error.errors)
33
- addlogs(config, chalk.red('Stack fail to export, ' + objKey + '' + error.errors[objKey][0]), 'error')
34
- }
35
- })
36
- })
37
- }
19
+ login
20
+ .login(config)
21
+ .then(async function () {
22
+ //setup branches
23
+ await setupBranches(config, config.branchName);
24
+ var types = config.modules.types;
25
+ if (Array.isArray(config.branches) && config.branches.length > 0) {
26
+ for (let branch of config.branches) {
27
+ config.branchName = branch.uid;
28
+ try {
29
+ if (config.moduleName) {
30
+ await singleExport(config.moduleName, types, config, branch.uid);
31
+ } else {
32
+ await allExport(config, types, branch.uid);
33
+ }
34
+ } catch (error) {
35
+ console.log('failed export branch', branch.uid, error)
36
+ }
37
+ }
38
+ } else {
39
+ try {
40
+ if (config.moduleName) {
41
+ await singleExport(config.moduleName, types, config);
42
+ } else {
43
+ await allExport(config, types);
44
+ }
45
+ } catch (error) {
46
+ console.log('failed export contents', error)
47
+ }
48
+ }
49
+ resolve()
50
+ })
51
+ .catch((error) => {
52
+ console.log("error", error);
53
+ if (error && error.errors && error.errors.api_key) {
54
+ addlogs(
55
+ config,
56
+ chalk.red(
57
+ "Stack Api key " + error.errors.api_key[0],
58
+ "Please enter valid Key",
59
+ "error"
60
+ )
61
+ );
62
+ addlogs(
63
+ config,
64
+ "The log for this is stored at " + config.data + "/export/logs",
65
+ "success"
66
+ );
67
+ } else {
68
+ console.log("Stack fail to export")
69
+ }
70
+ reject(error)
71
+ });
72
+ });
73
+ };
38
74
 
39
- var singleExport = async (moduleName, types, config) => {
40
- var types = config.modules.types
75
+ var singleExport = async (moduleName, types, config, branchName) => {
41
76
  try {
42
77
  if (types.indexOf(moduleName) > -1) {
43
- let iterateList = ['stack', moduleName]
78
+ let iterateList;
79
+ if (config.modules.dependency && config.modules.dependency[moduleName]) {
80
+ iterateList = config.modules.dependency[moduleName];
81
+ } else {
82
+ iterateList = ["stack"];
83
+ }
84
+ iterateList.push(moduleName);
85
+
44
86
  for (let i = 0; i < iterateList.length; i++) {
45
- var exportedModule = require('./lib/export/' + iterateList[i])
46
- await exportedModule.start(config).then(function (result) {
47
- if (iterateList[i] === 'stack') {
48
- let master_locale = { master_locale: { code: result.master_locale } }
49
- config = _.merge(config, master_locale)
50
- }
51
- })
87
+
88
+ var exportedModule = require("./lib/export/" + iterateList[i]);
89
+ const result = await exportedModule.start(config, branchName);
90
+ if (result && iterateList[i] === "stack") {
91
+ let master_locale = {
92
+ master_locale: { code: result.master_locale },
93
+ };
94
+ config = _.merge(config, master_locale);
95
+ }
52
96
  }
53
- addlogs(config, moduleName + ' was exported successfully!', 'success')
54
- addlogs(config, 'The log for this is stored at ' + path.join(config.data, 'logs', 'export'), 'success')
97
+ addlogs(config, moduleName + " was exported successfully!", "success");
98
+ addlogs(
99
+ config,
100
+ "The log for this is stored at " +
101
+ path.join(config.data, "logs", "export"),
102
+ "success"
103
+ );
55
104
  } else {
56
- addlogs(config, 'Please provide valid module name.', 'error')
105
+ addlogs(config, "Please provide valid module name.", "error");
57
106
  }
107
+ return true
58
108
  } catch (error) {
59
- addlogs(config, 'Failed to migrate ' + moduleName, 'error')
60
- addlogs(config, error, 'error')
61
- addlogs(config, 'The log for this is stored at ' + path.join(config.data, 'logs', 'export'), 'error')
109
+ addlogs(config, "Failed to migrate " + moduleName, "error");
110
+ addlogs(config, error, "error");
111
+ addlogs(
112
+ config,
113
+ "The log for this is stored at " +
114
+ path.join(config.data, "logs", "export"),
115
+ "error"
116
+ );
117
+ throw error
62
118
  }
63
- }
119
+ };
64
120
 
65
- var allExport = async (config, types) => {
121
+ var allExport = async (config, types, branchName) => {
66
122
  // eslint-disable-next-line no-async-promise-executor
67
123
  return new Promise(async (resolve, reject) => {
68
124
  try {
69
125
  for (let i = 0; i < types.length; i++) {
70
- let type = types[i]
71
- var exportedModule = require('./lib/export/' + type)
72
- await exportedModule.start(config).then(result => {
73
- if (type === 'stack') {
74
- let master_locale = { master_locale: { code: result.code } }
75
- config = _.merge(config, master_locale)
76
- }
77
- return
78
- })
126
+ let type = types[i];
127
+ var exportedModule = require("./lib/export/" + type);
128
+ const result = await exportedModule.start(config, branchName);
129
+ if (result && type === "stack") {
130
+ let master_locale = { master_locale: { code: result.code } };
131
+ config = _.merge(config, master_locale);
132
+ }
79
133
  }
80
- addlogs(config, chalk.green('The content of the ' + config.source_stack + ' has been exported succesfully!'), 'success')
81
- addlogs(config, 'The log for this is stored at ' + path.join(config.data, 'logs', 'export'), 'success')
82
- return resolve()
134
+ addlogs(
135
+ config,
136
+ chalk.green(
137
+ "The content of the " +
138
+ config.source_stack +
139
+ " has been exported succesfully!"
140
+ ),
141
+ "success"
142
+ );
143
+ addlogs(
144
+ config,
145
+ "The log for this is stored at " +
146
+ path.join(config.data, "logs", "export"),
147
+ "success"
148
+ );
149
+ return resolve();
83
150
  } catch (error) {
84
151
  addlogs(config, chalk.red('Failed to migrate stack: ' + config.source_stack + '. Please check error logs for more info'), 'error')
85
152
  addlogs(config, chalk.red(error.errorMessage), 'error')
86
153
  addlogs(config, 'The log for this is stored at ' + path.join(config.data, 'logs', 'export'), 'error')
87
154
  return reject(error)
88
155
  }
89
- })
90
- }
156
+ });
157
+ };
@@ -1,25 +1,27 @@
1
1
  /* eslint-disable complexity */
2
- const {Command, flags} = require('@contentstack/cli-command')
3
- const {configWithMToken,
2
+ const { Command, flags } = require('@contentstack/cli-command')
3
+ const { configWithMToken,
4
4
  parameterWithMToken,
5
5
  withoutParameterMToken,
6
6
  configWithAuthToken,
7
7
  parametersWithAuthToken,
8
8
  withoutParametersWithAuthToken,
9
9
  } = require('../../lib/util/export-flags')
10
- const Configstore = require('configstore')
10
+ const Configstore = require('configstore')
11
11
  const credStore = new Configstore('contentstack_cli')
12
12
 
13
13
  class ExportCommand extends Command {
14
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
15
+ const exportCommandFlags = this.parse(ExportCommand).flags
16
+ const extConfig = exportCommandFlags.config
17
+ let sourceStack = exportCommandFlags['stack-uid']
18
+ const alias = exportCommandFlags['management-token-alias']
19
+ const authToken = exportCommandFlags['auth-token']
20
+ const securedAssets = exportCommandFlags['secured-assets']
21
+ const data = exportCommandFlags.data
22
+ const moduleName = exportCommandFlags.module
23
+ const contentTypes = exportCommandFlags['content-type']
24
+ const branchName = exportCommandFlags.branch;
23
25
  let _authToken = credStore.get('authtoken')
24
26
  let host = this.region
25
27
  let cmaHost = host.cma.split('//')
@@ -27,14 +29,16 @@ class ExportCommand extends Command {
27
29
  host.cma = cmaHost[1]
28
30
  host.cda = cdaHost[1]
29
31
 
30
- if (alias && alias !== undefined) {
32
+ if (alias) {
31
33
  let managementTokens = this.getToken(alias)
32
- if (managementTokens && managementTokens !== undefined) {
33
- if (extConfig && extConfig !== undefined) {
34
+ if (managementTokens) {
35
+ if (extConfig) {
34
36
  configWithMToken(
35
37
  extConfig,
36
38
  managementTokens,
37
39
  host,
40
+ contentTypes,
41
+ branchName,
38
42
  securedAssets
39
43
  )
40
44
  } else if (data) {
@@ -44,6 +48,8 @@ class ExportCommand extends Command {
44
48
  moduleName,
45
49
  host,
46
50
  _authToken,
51
+ contentTypes,
52
+ branchName,
47
53
  securedAssets
48
54
  )
49
55
  } else if (data === undefined && sourceStack === undefined) {
@@ -52,6 +58,8 @@ class ExportCommand extends Command {
52
58
  moduleName,
53
59
  host,
54
60
  _authToken,
61
+ contentTypes,
62
+ branchName,
55
63
  securedAssets
56
64
  )
57
65
  } else {
@@ -60,13 +68,15 @@ class ExportCommand extends Command {
60
68
  } else {
61
69
  this.log(alias + ' management token is not present, please add managment token first')
62
70
  }
63
- } else if (authToken && authToken !== undefined && _authToken && _authToken !== undefined) {
64
- if (extConfig && extConfig !== undefined) {
71
+ } else if (authToken && _authToken) {
72
+ if (extConfig) {
65
73
  configWithAuthToken(
66
74
  extConfig,
67
75
  _authToken,
68
76
  moduleName,
69
77
  host,
78
+ contentTypes,
79
+ branchName,
70
80
  securedAssets
71
81
  )
72
82
  } else if (sourceStack && data) {
@@ -76,6 +86,8 @@ class ExportCommand extends Command {
76
86
  data,
77
87
  moduleName,
78
88
  host,
89
+ contentTypes,
90
+ branchName,
79
91
  securedAssets
80
92
  )
81
93
  } else if (data === undefined && sourceStack === undefined) {
@@ -83,6 +95,8 @@ class ExportCommand extends Command {
83
95
  _authToken,
84
96
  moduleName,
85
97
  host,
98
+ contentTypes,
99
+ branchName,
86
100
  securedAssets
87
101
  )
88
102
  } else {
@@ -107,17 +121,22 @@ ExportCommand.examples = [
107
121
  'csdx cm:export -A --secured-assets',
108
122
  'csdx cm:export -a <management_token_alias>',
109
123
  '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>'
124
+ 'csdx cm:export -a <management_token_alias> -c <path/to/config/file>',
125
+ 'csdx cm:export -A -m <single module name>',
126
+ 'csdx cm:export -A -m <single module name> -t <content type>',
127
+ 'csdx cm:export -A -B [optional] branch name',
111
128
  ]
112
129
 
113
130
  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'}),
131
+ config: flags.string({ char: 'c', description: '[optional] path of the config' }),
132
+ 'stack-uid': flags.string({ char: 's', description: 'API key of the source stack' }),
133
+ data: flags.string({ char: 'd', description: 'path or location to store the data' }),
134
+ 'management-token-alias': flags.string({ char: 'a', description: 'alias of the management token' }),
135
+ 'auth-token': flags.boolean({ char: 'A', description: 'to use auth token' }),
136
+ module: flags.string({ char: 'm', description: '[optional] specific module name' }),
137
+ 'content-type': flags.string({ char: 't', description: '[optional] content type', multiple: true }),
138
+ branch: flags.string({ char: 'B', description: '[optional] branch name' }),
139
+ 'secured-assets': flags.boolean({ description: '[optional] use when assets are secured' }),
121
140
  }
122
141
 
123
142
  module.exports = ExportCommand
@@ -21,7 +21,7 @@ module.exports = {
21
21
  'code',
22
22
  'uid',
23
23
  'name',
24
- 'fallback_locale',
24
+ 'fallback_locale'
25
25
  ],
26
26
  },
27
27
  environments: {
@@ -141,6 +141,9 @@ module.exports = {
141
141
  dirName: 'stack',
142
142
  fileName: 'stack.json',
143
143
  },
144
+ dependency: {
145
+ entries: ['stack', 'locales', 'content-types'],
146
+ },
144
147
  },
145
148
  languagesCode: [
146
149
  'af-za',
@@ -37,9 +37,11 @@ function ExportAssets() {
37
37
 
38
38
  ExportAssets.prototype = {
39
39
  start: function (credentialConfig) {
40
+ this.assetContents = {}
41
+ this.folderData = []
40
42
  let self = this
41
43
  config = credentialConfig
42
- assetsFolderPath = path.resolve(config.data, assetConfig.dirName)
44
+ assetsFolderPath = path.resolve(config.data, (config.branchName || ""), assetConfig.dirName)
43
45
  assetContentsFile = path.resolve(assetsFolderPath, 'assets.json')
44
46
  folderJSONPath = path.resolve(assetsFolderPath, 'folders.json')
45
47
  client = stack.Client(config)
@@ -48,6 +50,7 @@ ExportAssets.prototype = {
48
50
  // Create asset folder
49
51
  mkdirp.sync(assetsFolderPath)
50
52
  return new Promise(function (resolve, reject) {
53
+ //TBD: getting all the assets should have optimized
51
54
  return self.getAssetCount().then(function (count) {
52
55
  if (typeof count !== 'number' || count === 0) {
53
56
  addlogs(config, 'No assets found', 'success')
@@ -157,7 +160,6 @@ ExportAssets.prototype = {
157
160
  })
158
161
  },
159
162
  getAssetCount: function (folder) {
160
- let self = this
161
163
  return new Promise(function (resolve, reject) {
162
164
  if (folder && typeof folder === 'boolean') {
163
165
  let queryOptions = {include_folders: true, query: {'is_dir': true}, include_count: true}
@@ -182,7 +184,6 @@ ExportAssets.prototype = {
182
184
  })
183
185
  },
184
186
  getAssetJSON: function (skip) {
185
- let self = this
186
187
  return new Promise(function (resolve, reject) {
187
188
  if (typeof skip !== 'number') {
188
189
  skip = 0
@@ -35,10 +35,16 @@ function ExportContentTypes() {
35
35
 
36
36
  ExportContentTypes.prototype = {
37
37
  start: function (credentialConfig) {
38
+ this.content_types = []
38
39
  let self = this
39
40
  config = credentialConfig
40
- contentTypesFolderPath = path.resolve(config.data, contentTypeConfig.dirName)
41
+ contentTypesFolderPath = path.resolve(config.data, (config.branchName || ""), contentTypeConfig.dirName)
42
+
41
43
  client = stack.Client(config)
44
+ // If content type id is provided then use it as part of query
45
+ if (Array.isArray(config.contentTypes) && config.contentTypes.length > 0) {
46
+ self.requestOptions.qs.uid = {'$in': config.contentTypes}
47
+ }
42
48
  // Create folder for content types
43
49
  mkdirp.sync(contentTypesFolderPath)
44
50
  addlogs(config, 'Starting content type export', 'success')
@@ -42,9 +42,9 @@ function exportEntries() {
42
42
  exportEntries.prototype.start = function (credentialConfig) {
43
43
  let self = this
44
44
  config = credentialConfig
45
- entryFolderPath = path.resolve(config.data, config.modules.entries.dirName)
46
- localesFilePath = path.resolve(config.data, config.modules.locales.dirName, config.modules.locales.fileName)
47
- schemaFilePath = path.resolve(config.data, config.modules.content_types.dirName, 'schema.json')
45
+ entryFolderPath = path.resolve(config.data, (config.branchName || ""), config.modules.entries.dirName)
46
+ localesFilePath = path.resolve(config.data, (config.branchName || ""), config.modules.locales.dirName, config.modules.locales.fileName)
47
+ schemaFilePath = path.resolve(config.data, (config.branchName || ""), config.modules.content_types.dirName, 'schema.json')
48
48
  client = stack.Client(config)
49
49
  addlogs(config, 'Starting entry migration', 'success')
50
50
  return new Promise(function (resolve, reject) {
@@ -130,7 +130,7 @@ exportEntries.prototype.getEntries = function (apiDetails) {
130
130
  },
131
131
  }
132
132
  client.stack({api_key: config.source_stack, management_token: config.management_token}).contentType(apiDetails.content_type).entry().query(queryrequestObject).find()
133
- .then(entriesList => {
133
+ .then(entriesList => {
134
134
  // /entries/content_type_uid/locale.json
135
135
  if (!fs.existsSync(path.join(entryFolderPath, apiDetails.content_type))) {
136
136
  mkdirp.sync(path.join(entryFolderPath, apiDetails.content_type))
@@ -26,11 +26,13 @@ function ExportEnvironments() {
26
26
  }
27
27
 
28
28
  ExportEnvironments.prototype.start = function (mergConfig) {
29
+ this.master = {}
30
+ this.environments = {}
29
31
  let self = this
30
32
  config = mergConfig
31
33
  addlogs(config, 'Starting environment export', 'success')
32
34
  const environmentConfig = config.modules.environments
33
- const environmentsFolderPath = path.resolve(config.data, environmentConfig.dirName)
35
+ const environmentsFolderPath = path.resolve(config.data, (config.branchName || ""), environmentConfig.dirName)
34
36
  // Create folder for environments
35
37
  mkdirp.sync(environmentsFolderPath)
36
38
  let client = stack.Client(config)
@@ -25,10 +25,12 @@ function ExportExtensions() {
25
25
  }
26
26
 
27
27
  ExportExtensions.prototype.start = function (mergeConfig) {
28
+ this.master = {}
29
+ this.extensions = {}
28
30
  addlogs(config, 'Starting extension export', 'success')
29
31
  let self = this
30
32
  config = mergeConfig
31
- let extensionsFolderPath = path.resolve(config.data, extensionConfig.dirName)
33
+ let extensionsFolderPath = path.resolve(config.data, (config.branchName || ""), extensionConfig.dirName)
32
34
  // Create folder for extensions
33
35
  mkdirp.sync(extensionsFolderPath)
34
36
  let client = stack.Client(config)
@@ -1,113 +1,139 @@
1
1
  /*!
2
- * Contentstack Export
3
- * Copyright (c) 2019 Contentstack LLC
4
- * MIT Licensed
5
- */
2
+ * Contentstack Export
3
+ * Copyright (c) 2019 Contentstack LLC
4
+ * MIT Licensed
5
+ */
6
6
 
7
- const mkdirp = require('mkdirp')
8
- const path = require('path')
9
- const chalk = require('chalk')
7
+ const mkdirp = require("mkdirp");
8
+ const path = require("path");
9
+ const chalk = require("chalk");
10
10
 
11
- const stack = require('../util/contentstack-management-sdk')
12
- const helper = require('../util/helper')
13
- const {addlogs} = require('../util/log')
14
-
15
- let config = require('../../config/default')
16
- const globalfieldsConfig = config.modules.globalfields
17
- const globalfieldsFolderPath = path.resolve(config.data, globalfieldsConfig.dirName)
18
- const validKeys = globalfieldsConfig.validKeys
19
- const limit = 100
20
-
21
- // Create folder for Global Fields
22
- mkdirp.sync(globalfieldsFolderPath)
11
+ const stack = require("../util/contentstack-management-sdk");
12
+ const helper = require("../util/helper");
13
+ const { addlogs } = require("../util/log");
23
14
 
15
+ let config = require("../../config/default");
16
+ const limit = 100;
17
+ const validKeys = config.modules.globalfields.validKeys;
18
+ let globalfieldsFolderPath;
19
+ const globalfieldsConfig = config.modules.globalfields;
24
20
  function ExportGlobalFields() {
25
- this.global_fields = []
21
+ this.global_fields = [];
26
22
  this.requestOptions = {
27
23
  qs: {
28
24
  include_count: true,
29
- asc: 'updated_at',
25
+ asc: "updated_at",
30
26
  limit: limit,
31
27
  },
32
- }
33
- this.master = {}
34
- this.globalfields = {}
28
+ };
29
+ this.master = {};
30
+ this.globalfields = {};
35
31
  }
36
32
 
37
33
  ExportGlobalFields.prototype = {
38
34
  start: function (credentialConfig) {
39
- const self = this
40
- config = credentialConfig
41
- addlogs(config, 'Starting Global Fields export', 'success')
35
+ this.master = {};
36
+ this.globalfields = {};
37
+ config = {...config, ...credentialConfig};
38
+ globalfieldsFolderPath = path.resolve(
39
+ config.data,
40
+ (config.branchName || ""),
41
+ globalfieldsConfig.dirName
42
+ );
43
+ // Create folder for Global Fields
44
+ mkdirp.sync(globalfieldsFolderPath);
45
+ const self = this;
46
+ addlogs(config, "Starting Global Fields export", "success");
42
47
  return new Promise(function (resolve, reject) {
43
48
  try {
44
- return self.getGlobalFields(null, config).then(function (result) {
45
- if (!result) {
46
- return self.writeGlobalFields().then(result => {
47
- return resolve()
48
- }).catch(error => {
49
- return reject(error)
50
- })
51
- }
52
- return resolve()
53
- }).catch(error => {
54
- return reject(error)
55
- })
49
+ return self
50
+ .getGlobalFields(null, config)
51
+ .then(function (result) {
52
+ if (!result) {
53
+ return self
54
+ .writeGlobalFields()
55
+ .then(() => {
56
+ return resolve();
57
+ })
58
+ .catch((error) => {
59
+ return reject(error);
60
+ });
61
+ }
62
+ return resolve();
63
+ })
64
+ .catch((error) => {
65
+ return reject(error);
66
+ });
56
67
  } catch (error) {
57
- return reject(error)
68
+ return reject(error);
58
69
  }
59
- })
70
+ });
60
71
  },
61
- getGlobalFields: function (skip, config) {
62
- const self = this
63
- if (typeof skip !== 'number') {
64
- skip = 0
65
- self.requestOptions.qs.skip = skip
72
+ getGlobalFields: function (skip, globalFieldConfig) {
73
+ const self = this;
74
+ if (typeof skip !== "number") {
75
+ skip = 0;
76
+ self.requestOptions.qs.skip = skip;
66
77
  } else {
67
- self.requestOptions.qs.skip = skip
78
+ self.requestOptions.qs.skip = skip;
68
79
  }
69
-
70
- let client = stack.Client(config)
80
+
81
+ let client = stack.Client(globalFieldConfig);
71
82
  return new Promise(function (resolve, reject) {
72
- client.stack({api_key: config.source_stack, management_token: config.management_token}).globalField().query(self.requestOptions.qs).find()
73
- .then(globalFieldResponse => {
74
- try {
75
- if (globalFieldResponse.items.length === 0) {
76
- addlogs(config, 'No global fields found', 'success')
77
- return resolve('No Global Fields')
78
- }
79
- globalFieldResponse.items.forEach(function (globalField) {
80
- for (const key in globalField) {
81
- if (validKeys.indexOf(key) === -1) {
82
- delete globalField[key]
83
- }
83
+ client
84
+ .stack({
85
+ api_key: globalFieldConfig.source_stack,
86
+ management_token: globalFieldConfig.management_token,
87
+ })
88
+ .globalField()
89
+ .query(self.requestOptions.qs)
90
+ .find()
91
+ .then((globalFieldResponse) => {
92
+ try {
93
+ if (globalFieldResponse.items.length === 0) {
94
+ addlogs(globalFieldConfig, "No global fields found", "success");
95
+ return resolve("No Global Fields");
84
96
  }
85
- self.global_fields.push(globalField)
86
- })
97
+ globalFieldResponse.items.forEach(function (globalField) {
98
+ for (const key in globalField) {
99
+ if (validKeys.indexOf(key) === -1) {
100
+ delete globalField[key];
101
+ }
102
+ }
103
+ self.global_fields.push(globalField);
104
+ });
87
105
 
88
- skip += limit
106
+ skip += limit;
89
107
 
90
- if (skip > globalFieldResponse.count) {
91
- return resolve()
92
- }
108
+ if (skip > globalFieldResponse.count) {
109
+ return resolve();
110
+ }
93
111
 
94
- return self.getGlobalFields(skip, config)
95
- .then(resolve)
96
- .catch(reject)
97
- } catch (error) {
98
- return reject(error)
99
- }
100
- })
101
- })
112
+ return self
113
+ .getGlobalFields(skip, globalFieldConfig)
114
+ .then(resolve)
115
+ .catch(reject);
116
+ } catch (error) {
117
+ return reject(error);
118
+ }
119
+ });
120
+ });
102
121
  },
103
122
  writeGlobalFields: function () {
104
- const self = this
123
+ const self = this;
105
124
  return new Promise(function (resolve) {
106
- helper.writeFile(path.join(globalfieldsFolderPath, globalfieldsConfig.fileName), self.global_fields)
107
- addlogs(config, chalk.green('Global Fields export completed successfully'), 'success')
108
- return resolve()
109
- })
125
+ helper.writeFile(
126
+ path.join(globalfieldsFolderPath, globalfieldsConfig.fileName),
127
+ self.global_fields
128
+ );
129
+ addlogs(
130
+ config,
131
+ chalk.green("Global Fields export completed successfully"),
132
+ "success"
133
+ );
134
+ return resolve();
135
+ });
110
136
  },
111
- }
137
+ };
112
138
 
113
- module.exports = new ExportGlobalFields()
139
+ module.exports = new ExportGlobalFields();
@@ -28,10 +28,11 @@ function ExportLabels() {
28
28
 
29
29
  ExportLabels.prototype.start = function (credentialConfig) {
30
30
  addlogs(config, 'Starting labels export', 'success')
31
+ this.labels = {}
31
32
  let self = this
32
33
  config = credentialConfig
33
34
  client = stack.Client(config)
34
- let labelsFolderPath = path.resolve(config.data, labelConfig.dirName)
35
+ let labelsFolderPath = path.resolve(config.data, (config.branchName || ""), labelConfig.dirName)
35
36
  // Create locale folder
36
37
  mkdirp.sync(labelsFolderPath)
37
38
  return new Promise(function (resolve, reject) {
@@ -34,10 +34,11 @@ function ExportLocales() {
34
34
  }
35
35
 
36
36
  ExportLocales.prototype.start = function (credentialConfig) {
37
+ this.locales = {}
37
38
  addlogs(credentialConfig, 'Starting locale export', 'success')
38
39
  let self = this
39
40
  config = credentialConfig
40
- let localesFolderPath = path.resolve(config.data, localeConfig.dirName)
41
+ let localesFolderPath = path.resolve(config.data, (config.branchName || ""), localeConfig.dirName)
41
42
  mkdirp.sync(localesFolderPath)
42
43
 
43
44
  let client = stack.Client(config)
@@ -29,10 +29,12 @@ function ExportWebhooks() {
29
29
 
30
30
  ExportWebhooks.prototype.start = function (credentialConfig) {
31
31
  addlogs(config, 'Starting webhooks export', 'success')
32
+ this.master = {}
33
+ this.webhooks = {}
32
34
  let self = this
33
35
  config = credentialConfig
34
36
  client = stack.Client(config)
35
- const webhooksFolderPath = path.resolve(config.data, webhooksConfig.dirName)
37
+ const webhooksFolderPath = path.resolve(config.data, (config.branchName || ""), webhooksConfig.dirName)
36
38
  mkdirp.sync(webhooksFolderPath)
37
39
  return new Promise(function (resolve, reject) {
38
40
  client.stack({api_key: config.source_stack, management_token: config.management_token}).webhook().fetchAll(self.requestOptions)
@@ -22,11 +22,12 @@ function ExportWorkFlows() {
22
22
 
23
23
  ExportWorkFlows.prototype.start = function (credentialConfig) {
24
24
  addlogs(config, 'Starting workflow export', 'success')
25
+ this.workflows = {}
25
26
  let self = this
26
27
  config = credentialConfig
27
28
  client = stack.Client(config)
28
29
 
29
- let workflowsFolderPath = path.resolve(config.data, workFlowConfig.dirName)
30
+ let workflowsFolderPath = path.resolve(config.data, (config.branchName || ""), workFlowConfig.dirName)
30
31
  mkdirp.sync(workflowsFolderPath)
31
32
  return new Promise(function (resolve, reject) {
32
33
  return client.stack({api_key: config.source_stack, management_token: config.management_token}).workflow().fetchAll()
@@ -8,6 +8,12 @@ exports.Client = function (config) {
8
8
  logHandler: (level, data) => {},
9
9
  }
10
10
 
11
+ if (typeof config.branchName === 'string') {
12
+ option.headers = {
13
+ branch: config.branchName,
14
+ }
15
+ }
16
+
11
17
  const client = contentstacksdk.client(option)
12
18
  return client
13
19
  }
@@ -11,24 +11,45 @@ const helper = require('../util/helper');
11
11
  let _ = require('lodash')
12
12
  const {cli} = require('cli-ux')
13
13
 
14
- exports.configWithMToken = function (config, managementTokens, host, securedAssets) {
14
+ exports.configWithMToken = function (config, managementTokens, host, contentTypes, branchName, securedAssets) {
15
15
  let externalConfig = require(config)
16
16
  defaultConfig.securedAssets = securedAssets
17
17
  defaultConfig.management_token = managementTokens.token
18
18
  defaultConfig.host = host.cma
19
19
  defaultConfig.cdn = host.cda
20
+ defaultConfig.branchName = branchName
21
+ if (moduleName) {
22
+ defaultConfig.moduleName = moduleName
23
+ // Specfic content type setting is only for entries module
24
+ if (
25
+ moduleName === 'entries' &&
26
+ Array.isArray(contentTypes) &&
27
+ contentTypes.length > 0
28
+ ) {
29
+ defaultConfig.contentTypes = contentTypes
30
+ }
31
+ }
20
32
  defaultConfig = _.merge(defaultConfig, externalConfig)
21
33
  initial(defaultConfig)
22
34
  }
23
35
 
24
- exports.parameterWithMToken = function (managementTokens, data, moduleName, host, _authToken, securedAssets) {
36
+ exports.parameterWithMToken = function (managementTokens, data, moduleName, host, _authToken, contentTypes, branchName, securedAssets) {
25
37
  defaultConfig.management_token = managementTokens.token
26
38
  defaultConfig.auth_token = _authToken
27
39
  defaultConfig.host = host.cma
28
40
  defaultConfig.cdn = host.cda
41
+ defaultConfig.branchName = branchName
29
42
  defaultConfig.securedAssets = securedAssets
30
- if (moduleName && moduleName !== undefined) {
43
+ if (moduleName) {
31
44
  defaultConfig.moduleName = moduleName
45
+ // Specfic content type setting is only for entries module
46
+ if (
47
+ moduleName === 'entries' &&
48
+ Array.isArray(contentTypes) &&
49
+ contentTypes.length > 0
50
+ ) {
51
+ defaultConfig.contentTypes = contentTypes
52
+ }
32
53
  }
33
54
  defaultConfig.source_stack = managementTokens.apiKey
34
55
  defaultConfig.data = data
@@ -36,42 +57,69 @@ exports.parameterWithMToken = function (managementTokens, data, moduleName, host
36
57
  }
37
58
 
38
59
  // using ManagementToken
39
- exports.withoutParameterMToken = async (managementTokens, moduleName, host, _authToken, securedAssets) => {
60
+ exports.withoutParameterMToken = async (managementTokens, moduleName, host, _authToken, contentTypes, branchName, securedAssets) => {
40
61
  const stackUid = managementTokens.apiKey
41
62
  const pathOfExport = await cli.prompt(message.promptMessageList.promptPathStoredData)
42
63
  defaultConfig.management_token = managementTokens.token
43
64
  defaultConfig.host = host.cma
44
65
  defaultConfig.cdn = host.cda
66
+ defaultConfig.branchName = branchName
45
67
  defaultConfig.auth_token = _authToken
46
68
  defaultConfig.securedAssets = securedAssets
47
- if (moduleName && moduleName !== undefined) {
69
+ if (moduleName) {
48
70
  defaultConfig.moduleName = moduleName
71
+ // Specfic content type setting is only for entries module
72
+ if (
73
+ moduleName === 'entries' &&
74
+ Array.isArray(contentTypes) &&
75
+ contentTypes.length > 0
76
+ ) {
77
+ defaultConfig.contentTypes = contentTypes
78
+ }
49
79
  }
50
80
  defaultConfig.source_stack = stackUid
51
81
  defaultConfig.data = pathOfExport
52
82
  initial(defaultConfig)
53
83
  }
54
84
 
55
- exports.configWithAuthToken = function (config, _authToken, moduleName, host, securedAssets) {
85
+ exports.configWithAuthToken = function (config, _authToken, moduleName, host, contentTypes, branchName, securedAssets) {
56
86
  let externalConfig = helper.readFile(path.resolve(config))
57
87
  defaultConfig.auth_token = _authToken
58
88
  defaultConfig.host = host.cma
59
89
  defaultConfig.cdn = host.cda
90
+ defaultConfig.branchName = branchName
60
91
  defaultConfig.securedAssets = securedAssets
61
- if (moduleName && moduleName !== undefined) {
92
+ if (moduleName) {
62
93
  defaultConfig.moduleName = moduleName
94
+ // Specfic content type setting is only for entries module
95
+ if (
96
+ moduleName === 'entries' &&
97
+ Array.isArray(contentTypes) &&
98
+ contentTypes.length > 0
99
+ ) {
100
+ defaultConfig.contentTypes = contentTypes
101
+ }
63
102
  }
64
103
  defaultConfig = _.merge(defaultConfig, externalConfig)
65
104
  initial(defaultConfig)
66
105
  }
67
106
 
68
- exports.parametersWithAuthToken = function (_authToken, sourceStack, data, moduleName, host, securedAssets) {
107
+ exports.parametersWithAuthToken = function (_authToken, sourceStack, data, moduleName, host, contentTypes, branchName, securedAssets) {
69
108
  return new Promise(async(resolve, reject) => {
70
109
  defaultConfig.auth_token = _authToken
71
110
  defaultConfig.source_stack = sourceStack
72
- if (moduleName && moduleName !== undefined) {
111
+ if (moduleName) {
73
112
  defaultConfig.moduleName = moduleName
113
+ // Specfic content type setting is only for entries module
114
+ if (
115
+ moduleName === 'entries' &&
116
+ Array.isArray(contentTypes) &&
117
+ contentTypes.length > 0
118
+ ) {
119
+ defaultConfig.contentTypes = contentTypes
120
+ }
74
121
  }
122
+ defaultConfig.branchName = branchName
75
123
  defaultConfig.host = host.cma
76
124
  defaultConfig.cdn = host.cda
77
125
  defaultConfig.data = data
@@ -85,15 +133,24 @@ exports.parametersWithAuthToken = function (_authToken, sourceStack, data, modul
85
133
  })
86
134
  }
87
135
 
88
- exports.withoutParametersWithAuthToken = async (_authToken, moduleName, host, securedAssets) => {
136
+ exports.withoutParametersWithAuthToken = async (_authToken, moduleName, host, contentTypes, branchName, securedAssets) => {
89
137
  const stackUid = await cli.prompt(message.promptMessageList.promptSourceStack)
90
138
  const pathOfExport = await cli.prompt(message.promptMessageList.promptPathStoredData)
91
139
  defaultConfig.auth_token = _authToken
92
140
  defaultConfig.source_stack = stackUid
93
141
  defaultConfig.securedAssets = securedAssets
94
- if (moduleName && moduleName !== undefined) {
142
+ if (moduleName) {
95
143
  defaultConfig.moduleName = moduleName
144
+ // Specfic content type setting is only for entries module
145
+ if (
146
+ moduleName === 'entries' &&
147
+ Array.isArray(contentTypes) &&
148
+ contentTypes.length > 0
149
+ ) {
150
+ defaultConfig.contentTypes = contentTypes
151
+ }
96
152
  }
153
+ defaultConfig.branchName = branchName
97
154
  defaultConfig.data = pathOfExport
98
155
  defaultConfig.host = host.cma
99
156
  defaultConfig.cdn = host.cda
@@ -18,7 +18,7 @@ module.exports.login = config => {
18
18
  if (config.email && config.password) {
19
19
  // eslint-disable-next-line no-console
20
20
  console.log('Logging into Contentstack')
21
- return client.login({email: config.email, password: config.password})
21
+ client.login({email: config.email, password: config.password})
22
22
  .then(function (response) {
23
23
  // eslint-disable-next-line no-console
24
24
  console.log(chalk.green('Contentstack account authenticated successfully!'))
@@ -29,11 +29,11 @@ module.exports.login = config => {
29
29
  authtoken: config.authtoken,
30
30
  'X-User-Agent': 'contentstack-export/v',
31
31
  }
32
- return resolve(config)
32
+ resolve(config)
33
33
  }).catch(function (error) {
34
- return reject(error)
34
+ reject(error)
35
35
  })
36
- } if (!config.email && !config.password && config.source_stack && config.access_token) {
36
+ } else if (!config.email && !config.password && config.source_stack && config.access_token) {
37
37
  addlogs(config, chalk.yellow('Content types, entries, assets, labels, global fields, extensions modules will be exported'), 'success')
38
38
  addlogs(config, chalk.yellow('Email, password, or management token is not set in the config, cannot export Webhook and label modules'), 'success')
39
39
  config.headers = {
@@ -41,21 +41,21 @@ module.exports.login = config => {
41
41
  access_token: config.access_token,
42
42
  'X-User-Agent': 'contentstack-export/v',
43
43
  }
44
- return resolve(config)
44
+ resolve(config)
45
45
  // eslint-disable-next-line no-else-return
46
46
  } else if (config.auth_token && !config.management_token) {
47
47
  client.stack({api_key: config.source_stack, management_token: config.management_token}).users()
48
48
  .then(function () {
49
- return resolve()
49
+ resolve()
50
50
  }).catch(error => {
51
51
  if (error.errors.api_key) {
52
52
  return reject(error)
53
53
  }
54
54
  addlogs(config, error.errorMessage, 'error')
55
- return reject(error)
55
+ reject(error)
56
56
  })
57
57
  } else if (config.management_token) {
58
- return resolve()
58
+ resolve()
59
59
  }
60
60
  })
61
61
  }
@@ -8,7 +8,6 @@
8
8
 
9
9
  var Bluebird = require('bluebird');
10
10
  var request = Bluebird.promisify(require('request'));
11
- var debug = require('debug')('util:requests');
12
11
  //var pkg = require('../../package');
13
12
  var app = require('../../app');
14
13
 
@@ -22,14 +21,12 @@ function validate(req) {
22
21
  throw new Error(`Missing uri in request!\n${JSON.stringify(req)}`);
23
22
  }
24
23
  if (typeof req.method === 'undefined') {
25
- debug(`${req.uri || req.url} had no method, setting it as 'GET'`);
26
24
  req.method = 'GET';
27
25
  }
28
26
  if (typeof req.json === 'undefined') {
29
27
  req.json = true;
30
28
  }
31
29
  if (typeof req.headers === 'undefined') {
32
- debug(`${req.uri || req.url} had no headers`);
33
30
  var config = app.getConfig();
34
31
  req.headers = config.headers;
35
32
  }
@@ -44,25 +41,25 @@ var makeCall = module.exports = function(req, RETRY) {
44
41
  } else if (RETRY > MAX_RETRY_LIMIT) {
45
42
  return reject(new Error('Max retry limit exceeded!'));
46
43
  }
47
- debug(`${req.method.toUpperCase()}: ${req.uri || req.url}`);
44
+ // console.log(`${req.method.toUpperCase()}: ${req.uri || req.url}`);
48
45
  return request(req).then(function (response) {
49
46
  var timeDelay;
50
47
  if (response.statusCode >= 200 && response.statusCode <= 399) {
51
48
  return resolve(response);
52
49
  } else if (response.statusCode === 429) {
53
50
  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)
51
+ // console.log(`API rate limit exceeded.\nReceived ${response.statusCode} status\nBody ${JSON.stringify(response)}`);
52
+ console.log(`Retrying ${req.uri || req.url} with ${timeDelay} sec delay`);
53
+ return setTimeout(function (reqObj, retry) {
54
+ return makeCall(reqObj, retry)
58
55
  .then(resolve)
59
56
  .catch(reject);
60
57
  }, timeDelay, req, RETRY);
61
58
  } else if (response.statusCode >= 500) {
62
59
  // retry, with delay
63
60
  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`);
61
+ // console.log(`Recevied ${response.statusCode} status\nBody ${JSON.stringify(response)}`);
62
+ console.log(`Retrying ${req.uri || req.url} with ${timeDelay} sec delay`);
66
63
  RETRY++;
67
64
  return setTimeout(function (req, RETRY) {
68
65
  return makeCall(req, RETRY)
@@ -70,13 +67,11 @@ var makeCall = module.exports = function(req, RETRY) {
70
67
  .catch(reject);
71
68
  }, timeDelay, req, RETRY);
72
69
  } else {
73
- debug(`Request failed\n${JSON.stringify(req)}`);
74
- debug(`Response received\n${JSON.stringify(response)}`);
75
70
  return reject(response);
76
71
  }
77
72
  }).catch(reject);
78
73
  } catch (error) {
79
- debug(error);
74
+ console.log(error);
80
75
  return reject(error);
81
76
  }
82
77
  });
@@ -0,0 +1,62 @@
1
+ const mkdirp = require("mkdirp");
2
+ const path = require("path");
3
+ const request = require("./request");
4
+ const helper = require("./helper");
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
+
12
+ if (typeof branch === "string") {
13
+ //check branch exists
14
+ const result = await request({
15
+ url: `https://${config.host}/v3/stacks/branches/${branch}`,
16
+ headers: {
17
+ api_key: config.source_stack,
18
+ authtoken: config.auth_token,
19
+ },
20
+ });
21
+ if (
22
+ result &&
23
+ typeof result.body === "object" &&
24
+ typeof result.body.branch === "object"
25
+ ) {
26
+ branches.push(result.body.branch);
27
+ } else {
28
+ throw new Error("No branch found with the name " + branch);
29
+ }
30
+ } else {
31
+ try {
32
+ const result = await request({
33
+ url: `https://${config.host}/v3/stacks/branches`,
34
+ headers: {
35
+ api_key: config.source_stack,
36
+ authtoken: config.auth_token,
37
+ },
38
+ });
39
+
40
+ if (
41
+ result &&
42
+ result.body &&
43
+ Array.isArray(result.body.branches) &&
44
+ result.body.branches.length > 0
45
+ ) {
46
+ branches = result.body.branches;
47
+ } else {
48
+ branches.push("main");
49
+ }
50
+ } catch (error) {
51
+ return;
52
+ }
53
+ }
54
+
55
+ mkdirp.sync(config.data);
56
+ // create branch info file
57
+ helper.writeFile(path.join(config.data, "branches.json"), branches);
58
+ // add branches list in the
59
+ config.branches = branches;
60
+ };
61
+
62
+ module.exports = setupBranches;