@commercetools-frontend/deployment-cli 0.0.6 → 0.0.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,5 +1,3 @@
1
- import _asyncToGenerator from '@babel/runtime-corejs3/helpers/esm/asyncToGenerator';
2
- import _regeneratorRuntime from '@babel/runtime-corejs3/regenerator';
3
1
  import _sliceInstanceProperty from '@babel/runtime-corejs3/core-js-stable/instance/slice';
4
2
  import mri from 'mri';
5
3
  import _concatInstanceProperty from '@babel/runtime-corejs3/core-js-stable/instance/concat';
@@ -9,56 +7,37 @@ import _mapInstanceProperty from '@babel/runtime-corejs3/core-js-stable/instance
9
7
  import _filterInstanceProperty from '@babel/runtime-corejs3/core-js-stable/instance/filter';
10
8
  import _startsWithInstanceProperty from '@babel/runtime-corejs3/core-js-stable/instance/starts-with';
11
9
  import { cosmiconfig } from 'cosmiconfig';
12
- import merge from 'lodash.merge';
10
+ import merge from 'lodash/merge';
13
11
  import prompts from 'prompts';
14
12
  import pRetry from 'p-retry';
15
13
  import _slicedToArray from '@babel/runtime-corejs3/helpers/esm/slicedToArray';
16
14
  import _URLSearchParams from '@babel/runtime-corejs3/core-js-stable/url-search-params';
17
- import _Object$entries2 from '@babel/runtime-corejs3/core-js-stable/object/entries';
15
+ import _Object$entries from '@babel/runtime-corejs3/core-js-stable/object/entries';
18
16
  import _Promise from '@babel/runtime-corejs3/core-js-stable/promise';
19
17
  import _JSON$stringify from '@babel/runtime-corejs3/core-js-stable/json/stringify';
20
18
  import fetch from 'node-fetch';
21
19
 
22
- function loadConfig() {
23
- return _loadConfig.apply(this, arguments);
24
- }
25
- function _loadConfig() {
26
- _loadConfig = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
27
- var deploymentConfigExplorer, defaultConfig, cosmiconfigResult, mergedConfig;
28
- return _regeneratorRuntime.wrap(function _callee$(_context7) {
29
- while (1) switch (_context7.prev = _context7.next) {
30
- case 0:
31
- deploymentConfigExplorer = cosmiconfig('deployment');
32
- defaultConfig = {
33
- CircleCI: {
34
- apiBaseUrl: 'https://circleci.com/api/v2',
35
- deploymentWorkflowName: 'test_build_and_deploy',
36
- pagination: {
37
- maxPages: 42,
38
- pagesForPipelineSelection: 5
39
- }
40
- },
41
- MerchantCenter: {}
42
- };
43
- _context7.prev = 2;
44
- _context7.next = 5;
45
- return deploymentConfigExplorer.search();
46
- case 5:
47
- cosmiconfigResult = _context7.sent;
48
- mergedConfig = merge(defaultConfig, cosmiconfigResult === null || cosmiconfigResult === void 0 ? void 0 : cosmiconfigResult.config);
49
- return _context7.abrupt("return", mergedConfig);
50
- case 10:
51
- _context7.prev = 10;
52
- _context7.t0 = _context7["catch"](2);
53
- console.warn(_context7.t0);
54
- throw new Error('Failed loading a deployment configuration. Create a cosmiconfig for `deployment` for example `deployment.config.cjs`.');
55
- case 14:
56
- case "end":
57
- return _context7.stop();
20
+ async function loadConfig() {
21
+ const deploymentConfigExplorer = cosmiconfig('deployment');
22
+ const defaultConfig = {
23
+ CircleCI: {
24
+ apiBaseUrl: 'https://circleci.com/api/v2',
25
+ deploymentWorkflowName: 'test_build_and_deploy',
26
+ pagination: {
27
+ maxPages: 42,
28
+ pagesForPipelineSelection: 5
58
29
  }
59
- }, _callee, null, [[2, 10]]);
60
- }));
61
- return _loadConfig.apply(this, arguments);
30
+ },
31
+ MerchantCenter: {}
32
+ };
33
+ try {
34
+ const cosmiconfigResult = await deploymentConfigExplorer.search();
35
+ const mergedConfig = merge(defaultConfig, cosmiconfigResult === null || cosmiconfigResult === void 0 ? void 0 : cosmiconfigResult.config);
36
+ return mergedConfig;
37
+ } catch (e) {
38
+ console.warn(e);
39
+ throw new Error('Failed loading a deployment configuration. Create a cosmiconfig for `deployment` for example `deployment.config.cjs`.');
40
+ }
62
41
  }
63
42
  function throwIfConfigurationLacksRequiredValues(parsedConfiguration) {
64
43
  if (!parsedConfiguration.CircleCI.projectName) {
@@ -66,21 +45,21 @@ function throwIfConfigurationLacksRequiredValues(parsedConfiguration) {
66
45
  }
67
46
  }
68
47
  function throwIfRequiredEnvironmentVariableIsUnset(requiredEnvironmentVariables) {
69
- _forEachInstanceProperty(requiredEnvironmentVariables).call(requiredEnvironmentVariables, function (nameOfRequiredEnvironmentVariable) {
70
- var valueOfRequiredEnvironmentVariable = process.env[nameOfRequiredEnvironmentVariable];
48
+ _forEachInstanceProperty(requiredEnvironmentVariables).call(requiredEnvironmentVariables, nameOfRequiredEnvironmentVariable => {
49
+ const valueOfRequiredEnvironmentVariable = process.env[nameOfRequiredEnvironmentVariable];
71
50
  if (!valueOfRequiredEnvironmentVariable) throw new Error("Missing '".concat(nameOfRequiredEnvironmentVariable, "' environment variable"));
72
51
  });
73
52
  }
74
- var promptOptions = {
75
- applicationSelect: function applicationSelect(_ref) {
76
- var packages = _ref.packages;
53
+ const promptOptions = {
54
+ applicationSelect: _ref => {
55
+ let packages = _ref.packages;
77
56
  return {
78
57
  type: 'select',
79
58
  name: 'applicationName',
80
59
  message: 'Select an application',
81
- choices: _mapInstanceProperty(packages).call(packages, function (_ref2) {
82
- var packageJson = _ref2.packageJson;
83
- var applicationName = packageJson.name.replace('@commercetools-local/application-', '');
60
+ choices: _mapInstanceProperty(packages).call(packages, _ref2 => {
61
+ let packageJson = _ref2.packageJson;
62
+ const applicationName = packageJson.name.replace('@commercetools-local/application-', '');
84
63
  return {
85
64
  title: applicationName,
86
65
  value: applicationName
@@ -88,13 +67,13 @@ var promptOptions = {
88
67
  })
89
68
  };
90
69
  },
91
- deploymentPipelineSelect: function deploymentPipelineSelect(_ref3) {
92
- var deploymentPipelines = _ref3.deploymentPipelines;
70
+ deploymentPipelineSelect: _ref3 => {
71
+ let deploymentPipelines = _ref3.deploymentPipelines;
93
72
  return {
94
73
  type: 'select',
95
74
  name: 'deploymentPipeline',
96
75
  message: 'Select the revision you would like to deploy',
97
- choices: _mapInstanceProperty(deploymentPipelines).call(deploymentPipelines, function (deploymentPipeline) {
76
+ choices: _mapInstanceProperty(deploymentPipelines).call(deploymentPipelines, deploymentPipeline => {
98
77
  var _context, _context2;
99
78
  return {
100
79
  title: _concatInstanceProperty(_context = _concatInstanceProperty(_context2 = "".concat(deploymentPipeline.vcs.revision.substring(0, 7), " - ")).call(_context2, deploymentPipeline.vcs.commit.subject, " <")).call(_context, deploymentPipeline.trigger.actor.login, ">"),
@@ -103,9 +82,9 @@ var promptOptions = {
103
82
  })
104
83
  };
105
84
  },
106
- deploymentConfirmation: function deploymentConfirmation(_ref4) {
85
+ deploymentConfirmation: _ref4 => {
107
86
  var _context3;
108
- var approvalJob = _ref4.approvalJob,
87
+ let approvalJob = _ref4.approvalJob,
109
88
  revision = _ref4.revision;
110
89
  return {
111
90
  type: 'toggle',
@@ -117,183 +96,108 @@ var promptOptions = {
117
96
  };
118
97
  }
119
98
  };
120
- function paginateToDeploymentPipeline(_x) {
121
- return _paginateToDeploymentPipeline.apply(this, arguments);
122
- }
123
- function _paginateToDeploymentPipeline() {
124
- _paginateToDeploymentPipeline = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(_ref5) {
125
- var circleCiApis, buildRevision, branch, debug, maxPages, deploymentPipeline, nextPageToken, i, _context8, _context9, pipelineRequest, pipelines, nonScheduledPipelines, _context10, _context11;
126
- return _regeneratorRuntime.wrap(function _callee2$(_context13) {
127
- while (1) switch (_context13.prev = _context13.next) {
128
- case 0:
129
- circleCiApis = _ref5.circleCiApis, buildRevision = _ref5.buildRevision, branch = _ref5.branch, debug = _ref5.debug, maxPages = _ref5.maxPages;
130
- i = 0;
131
- case 2:
132
- if (!(i < maxPages)) {
133
- _context13.next = 16;
134
- break;
135
- }
136
- // eslint-disable-next-line no-await-in-loop
137
- pipelineRequest = circleCiApis.pipelines({
138
- pageToken: nextPageToken,
139
- branch: branch
140
- });
141
- _context13.next = 6;
142
- return pipelineRequest.execute({
143
- debug: debug
144
- });
145
- case 6:
146
- pipelines = _context13.sent;
147
- nextPageToken = pipelines.next_page_token;
148
- nonScheduledPipelines = _filterInstanceProperty(_context8 = _filterInstanceProperty(_context9 = pipelines.items).call(_context9, isNonScheduledPipeline)).call(_context8, isNonErroredPipeline);
149
- if (buildRevision) {
150
- console.log(_concatInstanceProperty(_context10 = _concatInstanceProperty(_context11 = "\uD83D\uDD04 Trying to find pipeline with revision ".concat(buildRevision, ". Attempt ")).call(_context11, i + 1, " out of ")).call(_context10, maxPages, "."));
151
- deploymentPipeline = _findInstanceProperty(nonScheduledPipelines).call(nonScheduledPipelines, function (pipeline) {
152
- var _context12;
153
- return _startsWithInstanceProperty(_context12 = pipeline.vcs.revision).call(_context12, buildRevision);
154
- });
155
- } else {
156
- deploymentPipeline = nonScheduledPipelines[0];
157
- }
158
- if (!deploymentPipeline) {
159
- _context13.next = 13;
160
- break;
161
- }
162
- console.log("\u2139\uFE0F Using pipeline for deployment with revision ".concat(deploymentPipeline.vcs.revision, "."));
163
- return _context13.abrupt("break", 16);
164
- case 13:
165
- i++;
166
- _context13.next = 2;
167
- break;
168
- case 16:
169
- return _context13.abrupt("return", deploymentPipeline);
170
- case 17:
171
- case "end":
172
- return _context13.stop();
173
- }
174
- }, _callee2);
175
- }));
176
- return _paginateToDeploymentPipeline.apply(this, arguments);
177
- }
178
- function collectDeploymentPipelines(_x2) {
179
- return _collectDeploymentPipelines.apply(this, arguments);
180
- }
181
- function _collectDeploymentPipelines() {
182
- _collectDeploymentPipelines = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(_ref6) {
183
- var circleCiApis, branch, pagesForPipelineSelection, debug, deploymentPipelines, nextPageToken, i, _context14, _context15, pipelinesRequest, pipelines, nonScheduledPipelines;
184
- return _regeneratorRuntime.wrap(function _callee3$(_context16) {
185
- while (1) switch (_context16.prev = _context16.next) {
186
- case 0:
187
- circleCiApis = _ref6.circleCiApis, branch = _ref6.branch, pagesForPipelineSelection = _ref6.pagesForPipelineSelection, debug = _ref6.debug;
188
- deploymentPipelines = [];
189
- i = 0;
190
- case 3:
191
- if (!(i < pagesForPipelineSelection)) {
192
- _context16.next = 13;
193
- break;
194
- }
195
- // eslint-disable-next-line no-await-in-loop
196
- pipelinesRequest = circleCiApis.pipelines({
197
- pageToken: nextPageToken,
198
- branch: branch
199
- });
200
- _context16.next = 7;
201
- return pipelinesRequest.execute({
202
- debug: debug
203
- });
204
- case 7:
205
- pipelines = _context16.sent;
206
- nonScheduledPipelines = _filterInstanceProperty(_context14 = _filterInstanceProperty(_context15 = pipelines.items).call(_context15, isNonScheduledPipeline)).call(_context14, isNonErroredPipeline);
207
- deploymentPipelines = _concatInstanceProperty(deploymentPipelines).call(deploymentPipelines, nonScheduledPipelines);
208
- case 10:
209
- i++;
210
- _context16.next = 3;
211
- break;
212
- case 13:
213
- return _context16.abrupt("return", deploymentPipelines);
214
- case 14:
215
- case "end":
216
- return _context16.stop();
217
- }
218
- }, _callee3);
219
- }));
220
- return _collectDeploymentPipelines.apply(this, arguments);
99
+ async function paginateToDeploymentPipeline(_ref5) {
100
+ let circleCiApis = _ref5.circleCiApis,
101
+ buildRevision = _ref5.buildRevision,
102
+ branch = _ref5.branch,
103
+ debug = _ref5.debug,
104
+ maxPages = _ref5.maxPages;
105
+ let deploymentPipeline;
106
+ let nextPageToken;
107
+ // eslint-disable-next-line no-plusplus
108
+ for (let i = 0; i < maxPages; i++) {
109
+ var _context4, _context5;
110
+ // eslint-disable-next-line no-await-in-loop
111
+
112
+ const pipelineRequest = circleCiApis.pipelines({
113
+ pageToken: nextPageToken,
114
+ branch
115
+ });
116
+ const pipelines = await pipelineRequest.execute({
117
+ debug
118
+ });
119
+ nextPageToken = pipelines.next_page_token;
120
+ const nonScheduledPipelines = _filterInstanceProperty(_context4 = _filterInstanceProperty(_context5 = pipelines.items).call(_context5, isNonScheduledPipeline)).call(_context4, isNonErroredPipeline);
121
+ if (buildRevision) {
122
+ var _context6, _context7;
123
+ console.log(_concatInstanceProperty(_context6 = _concatInstanceProperty(_context7 = "\uD83D\uDD04 Trying to find pipeline with revision ".concat(buildRevision, ". Attempt ")).call(_context7, i + 1, " out of ")).call(_context6, maxPages, "."));
124
+ deploymentPipeline = _findInstanceProperty(nonScheduledPipelines).call(nonScheduledPipelines, pipeline => {
125
+ var _context8;
126
+ return _startsWithInstanceProperty(_context8 = pipeline.vcs.revision).call(_context8, buildRevision);
127
+ });
128
+ } else {
129
+ deploymentPipeline = nonScheduledPipelines[0];
130
+ }
131
+ if (deploymentPipeline) {
132
+ console.log("\u2139\uFE0F Using pipeline for deployment with revision ".concat(deploymentPipeline.vcs.revision, "."));
133
+ break;
134
+ }
135
+ }
136
+ return deploymentPipeline;
221
137
  }
222
- function waitForDeploymentPipelinePrompt(_x3) {
223
- return _waitForDeploymentPipelinePrompt.apply(this, arguments);
138
+ async function collectDeploymentPipelines(_ref6) {
139
+ let circleCiApis = _ref6.circleCiApis,
140
+ branch = _ref6.branch,
141
+ pagesForPipelineSelection = _ref6.pagesForPipelineSelection,
142
+ debug = _ref6.debug;
143
+ let deploymentPipelines = [];
144
+ let nextPageToken;
145
+ // eslint-disable-next-line no-plusplus
146
+ for (let i = 0; i < pagesForPipelineSelection; i++) {
147
+ var _context9, _context10;
148
+ // eslint-disable-next-line no-await-in-loop
149
+ const pipelinesRequest = circleCiApis.pipelines({
150
+ pageToken: nextPageToken,
151
+ branch
152
+ });
153
+ const pipelines = await pipelinesRequest.execute({
154
+ debug
155
+ });
156
+ const nonScheduledPipelines = _filterInstanceProperty(_context9 = _filterInstanceProperty(_context10 = pipelines.items).call(_context10, isNonScheduledPipeline)).call(_context9, isNonErroredPipeline);
157
+ deploymentPipelines = _concatInstanceProperty(deploymentPipelines).call(deploymentPipelines, nonScheduledPipelines);
158
+ }
159
+ return deploymentPipelines;
224
160
  }
225
- function _waitForDeploymentPipelinePrompt() {
226
- _waitForDeploymentPipelinePrompt = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(_ref7) {
227
- var circleCiApis, branch, pagesForPipelineSelection, debug, deploymentPipelines, deploymentPipelinePrompt, revision;
228
- return _regeneratorRuntime.wrap(function _callee4$(_context17) {
229
- while (1) switch (_context17.prev = _context17.next) {
230
- case 0:
231
- circleCiApis = _ref7.circleCiApis, branch = _ref7.branch, pagesForPipelineSelection = _ref7.pagesForPipelineSelection, debug = _ref7.debug;
232
- _context17.next = 3;
233
- return collectDeploymentPipelines({
234
- branch: branch,
235
- pagesForPipelineSelection: pagesForPipelineSelection,
236
- circleCiApis: circleCiApis,
237
- debug: debug
238
- });
239
- case 3:
240
- deploymentPipelines = _context17.sent;
241
- _context17.next = 6;
242
- return prompts(
243
- // @ts-expect-error prompts is not typed
244
- promptOptions.deploymentPipelineSelect({
245
- deploymentPipelines: deploymentPipelines
246
- }));
247
- case 6:
248
- deploymentPipelinePrompt = _context17.sent;
249
- revision = deploymentPipelinePrompt.deploymentPipeline.vcs.revision;
250
- if (revision) {
251
- _context17.next = 11;
252
- break;
253
- }
254
- console.log('☝️ Please select a revision or specify it as a CLI argument via `--build-revision`.');
255
- throw new Error('No revision specified.');
256
- case 11:
257
- return _context17.abrupt("return", deploymentPipelinePrompt.deploymentPipeline);
258
- case 12:
259
- case "end":
260
- return _context17.stop();
261
- }
262
- }, _callee4);
161
+ async function waitForDeploymentPipelinePrompt(_ref7) {
162
+ let circleCiApis = _ref7.circleCiApis,
163
+ branch = _ref7.branch,
164
+ pagesForPipelineSelection = _ref7.pagesForPipelineSelection,
165
+ debug = _ref7.debug;
166
+ const deploymentPipelines = await collectDeploymentPipelines({
167
+ branch,
168
+ pagesForPipelineSelection,
169
+ circleCiApis,
170
+ debug
171
+ });
172
+ const deploymentPipelinePrompt = await prompts(
173
+ // @ts-expect-error prompts is not typed
174
+ promptOptions.deploymentPipelineSelect({
175
+ deploymentPipelines
263
176
  }));
264
- return _waitForDeploymentPipelinePrompt.apply(this, arguments);
265
- }
266
- function waitForConfirmationPrompt(_x4) {
267
- return _waitForConfirmationPrompt.apply(this, arguments);
177
+ const revision = deploymentPipelinePrompt.deploymentPipeline.vcs.revision;
178
+ if (!revision) {
179
+ console.log('☝️ Please select a revision or specify it as a CLI argument via `--build-revision`.');
180
+ throw new Error('No revision specified.');
181
+ }
182
+ return deploymentPipelinePrompt.deploymentPipeline;
268
183
  }
269
- function _waitForConfirmationPrompt() {
270
- _waitForConfirmationPrompt = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(_ref8) {
271
- var approvalJob, revision;
272
- return _regeneratorRuntime.wrap(function _callee5$(_context18) {
273
- while (1) switch (_context18.prev = _context18.next) {
274
- case 0:
275
- approvalJob = _ref8.approvalJob, revision = _ref8.revision;
276
- return _context18.abrupt("return", prompts(
277
- // @ts-expect-error prompts is not typed
278
- promptOptions.deploymentConfirmation({
279
- approvalJob: approvalJob,
280
- revision: revision
281
- })));
282
- case 2:
283
- case "end":
284
- return _context18.stop();
285
- }
286
- }, _callee5);
184
+ async function waitForConfirmationPrompt(_ref8) {
185
+ let approvalJob = _ref8.approvalJob,
186
+ revision = _ref8.revision;
187
+ return prompts(
188
+ // @ts-expect-error prompts is not typed
189
+ promptOptions.deploymentConfirmation({
190
+ approvalJob,
191
+ revision
287
192
  }));
288
- return _waitForConfirmationPrompt.apply(this, arguments);
289
193
  }
290
194
  function getJobUrl(_ref9) {
291
- var _context4, _context5, _context6;
292
- var pipelineNumber = _ref9.pipelineNumber,
195
+ var _context11, _context12, _context13;
196
+ let pipelineNumber = _ref9.pipelineNumber,
293
197
  workflowId = _ref9.workflowId,
294
198
  jobNumber = _ref9.jobNumber,
295
199
  projectName = _ref9.projectName;
296
- return _concatInstanceProperty(_context4 = _concatInstanceProperty(_context5 = _concatInstanceProperty(_context6 = "https://app.circleci.com/pipelines/github/commercetools/".concat(projectName, "/")).call(_context6, pipelineNumber, "/workflows/")).call(_context5, workflowId, "/jobs/")).call(_context4, jobNumber);
200
+ return _concatInstanceProperty(_context11 = _concatInstanceProperty(_context12 = _concatInstanceProperty(_context13 = "https://app.circleci.com/pipelines/github/commercetools/".concat(projectName, "/")).call(_context13, pipelineNumber, "/workflows/")).call(_context12, workflowId, "/jobs/")).call(_context11, jobNumber);
297
201
  }
298
202
  function isNonScheduledPipeline(pipeline) {
299
203
  return pipeline.trigger.type !== 'schedule' && pipeline.trigger.type !== 'scheduled_pipeline';
@@ -301,458 +205,274 @@ function isNonScheduledPipeline(pipeline) {
301
205
  function isNonErroredPipeline(pipeline) {
302
206
  return pipeline.state !== 'errored';
303
207
  }
304
- function waitForDeploymentJobNumber(_x5, _x6) {
305
- return _waitForDeploymentJobNumber.apply(this, arguments);
306
- }
307
- function _waitForDeploymentJobNumber() {
308
- _waitForDeploymentJobNumber = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(_ref10, _ref11) {
309
- var workflowId, deploymentJob, circleCiApis, debug, fetchDeploymentJobNumber, deploymentJobNumber;
310
- return _regeneratorRuntime.wrap(function _callee7$(_context22) {
311
- while (1) switch (_context22.prev = _context22.next) {
312
- case 0:
313
- workflowId = _ref10.workflowId, deploymentJob = _ref10.deploymentJob, circleCiApis = _ref10.circleCiApis;
314
- debug = _ref11.debug;
315
- fetchDeploymentJobNumber = /*#__PURE__*/function () {
316
- var _ref12 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6() {
317
- var _context19;
318
- var jobsRequest, jobs, applicationDeploymentJob;
319
- return _regeneratorRuntime.wrap(function _callee6$(_context20) {
320
- while (1) switch (_context20.prev = _context20.next) {
321
- case 0:
322
- jobsRequest = circleCiApis.jobs({
323
- workflowId: workflowId
324
- });
325
- _context20.next = 3;
326
- return jobsRequest.execute({
327
- debug: debug
328
- });
329
- case 3:
330
- jobs = _context20.sent;
331
- applicationDeploymentJob = _findInstanceProperty(_context19 = jobs.items).call(_context19, function (job) {
332
- return job.name === deploymentJob;
333
- });
334
- if (!(!applicationDeploymentJob || applicationDeploymentJob.status === 'blocked')) {
335
- _context20.next = 7;
336
- break;
337
- }
338
- throw new Error('Deployment job not yet running. Retrying.');
339
- case 7:
340
- return _context20.abrupt("return", applicationDeploymentJob.job_number);
341
- case 8:
342
- case "end":
343
- return _context20.stop();
344
- }
345
- }, _callee6);
346
- }));
347
- return function fetchDeploymentJobNumber() {
348
- return _ref12.apply(this, arguments);
349
- };
350
- }();
351
- _context22.next = 5;
352
- return pRetry(fetchDeploymentJobNumber, {
353
- onFailedAttempt: function onFailedAttempt(error) {
354
- var _context21;
355
- console.log(_concatInstanceProperty(_context21 = "\uD83D\uDD04 Trying to find deployment job. Attempt ".concat(error.attemptNumber, " with ")).call(_context21, error.retriesLeft, " retries left."));
356
- },
357
- retries: 10
358
- });
359
- case 5:
360
- deploymentJobNumber = _context22.sent;
361
- return _context22.abrupt("return", deploymentJobNumber);
362
- case 7:
363
- case "end":
364
- return _context22.stop();
365
- }
366
- }, _callee7);
367
- }));
368
- return _waitForDeploymentJobNumber.apply(this, arguments);
208
+ async function waitForDeploymentJobNumber(_ref10, _ref11) {
209
+ let workflowId = _ref10.workflowId,
210
+ deploymentJob = _ref10.deploymentJob,
211
+ circleCiApis = _ref10.circleCiApis;
212
+ let debug = _ref11.debug;
213
+ const fetchDeploymentJobNumber = async () => {
214
+ var _context14;
215
+ const jobsRequest = circleCiApis.jobs({
216
+ workflowId
217
+ });
218
+ const jobs = await jobsRequest.execute({
219
+ debug
220
+ });
221
+ const applicationDeploymentJob = _findInstanceProperty(_context14 = jobs.items).call(_context14, job => job.name === deploymentJob);
222
+ if (!applicationDeploymentJob || applicationDeploymentJob.status === 'blocked') {
223
+ throw new Error('Deployment job not yet running. Retrying.');
224
+ }
225
+ return applicationDeploymentJob.job_number;
226
+ };
227
+ const deploymentJobNumber = await pRetry(fetchDeploymentJobNumber, {
228
+ onFailedAttempt: error => {
229
+ var _context15;
230
+ console.log(_concatInstanceProperty(_context15 = "\uD83D\uDD04 Trying to find deployment job. Attempt ".concat(error.attemptNumber, " with ")).call(_context15, error.retriesLeft, " retries left."));
231
+ },
232
+ retries: 10
233
+ });
234
+ return deploymentJobNumber;
369
235
  }
370
236
 
371
- function approve(_x, _x2, _x3) {
372
- return _approve.apply(this, arguments);
373
- }
374
- function _approve() {
375
- _approve = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(cliFlags, config, circleCiApis) {
376
- var _config$CircleCI$pagi, _config$CircleCI$pagi2, _config$CircleCI$pagi3, _config$CircleCI$pagi4, _context2, _context3, _context5, _confirmationPrompt;
377
- var approvalJob, deploymentJob, _config$deployments, _context, requestedDeployment, deploymentPipeline, workflowsRequest, workflows, buildAndDeployWorkflow, workflowId, jobsRequest, jobs, applicationApprovalJob, applicationApprovalJobId, _context4, confirmationPrompt, approvalRequest, _context6, _context7, deploymentJobNumber;
378
- return _regeneratorRuntime.wrap(function _callee$(_context8) {
379
- while (1) switch (_context8.prev = _context8.next) {
380
- case 0:
381
- if (!cliFlags.deployment) {
382
- _context8.next = 9;
383
- break;
384
- }
385
- requestedDeployment = (_config$deployments = config.deployments) === null || _config$deployments === void 0 ? void 0 : _config$deployments[cliFlags.deployment];
386
- if (requestedDeployment) {
387
- _context8.next = 4;
388
- break;
389
- }
390
- throw new Error("\u26A0\uFE0F Deployment ".concat(cliFlags.deployment, " not found in configuration. Make sure it exists."));
391
- case 4:
392
- approvalJob = requestedDeployment.jobs.approval;
393
- deploymentJob = requestedDeployment.jobs.deployment;
394
- console.log(_concatInstanceProperty(_context = "\u2139\uFE0F Approving requested deployment ".concat(cliFlags.deployment, " with approval job ")).call(_context, approvalJob, "."));
395
- _context8.next = 12;
396
- break;
397
- case 9:
398
- approvalJob = cliFlags.approvalJob;
399
- deploymentJob = cliFlags.deploymentJob;
400
- console.log("\u2139\uFE0F Approving with approval job ".concat(approvalJob, "."));
401
- case 12:
402
- if (!cliFlags.yes) {
403
- _context8.next = 18;
404
- break;
405
- }
406
- _context8.next = 15;
407
- return paginateToDeploymentPipeline({
408
- circleCiApis: circleCiApis,
409
- buildRevision: cliFlags.buildRevision,
410
- branch: cliFlags.branch,
411
- debug: cliFlags.debug,
412
- maxPages: (_config$CircleCI$pagi = (_config$CircleCI$pagi2 = config.CircleCI.pagination) === null || _config$CircleCI$pagi2 === void 0 ? void 0 : _config$CircleCI$pagi2.maxPages) !== null && _config$CircleCI$pagi !== void 0 ? _config$CircleCI$pagi : 1
413
- });
414
- case 15:
415
- _context8.t0 = _context8.sent;
416
- _context8.next = 21;
417
- break;
418
- case 18:
419
- _context8.next = 20;
420
- return waitForDeploymentPipelinePrompt({
421
- branch: cliFlags.branch,
422
- circleCiApis: circleCiApis,
423
- pagesForPipelineSelection: (_config$CircleCI$pagi3 = (_config$CircleCI$pagi4 = config.CircleCI.pagination) === null || _config$CircleCI$pagi4 === void 0 ? void 0 : _config$CircleCI$pagi4.pagesForPipelineSelection) !== null && _config$CircleCI$pagi3 !== void 0 ? _config$CircleCI$pagi3 : 1,
424
- debug: cliFlags.debug
425
- });
426
- case 20:
427
- _context8.t0 = _context8.sent;
428
- case 21:
429
- deploymentPipeline = _context8.t0;
430
- if (deploymentPipeline) {
431
- _context8.next = 24;
432
- break;
433
- }
434
- throw new Error("\u26A0\uFE0F No workflow called ".concat(config.CircleCI.deploymentWorkflowName, " found in any pipeline for deployment."));
435
- case 24:
436
- console.log("\u2139\uFE0F Found pipeline for deployment with revision ".concat(deploymentPipeline.vcs.revision, "."));
437
- workflowsRequest = circleCiApis.workflows({
438
- pipelineId: deploymentPipeline.id
439
- });
440
- _context8.next = 28;
441
- return workflowsRequest.execute({
442
- debug: cliFlags.debug
443
- });
444
- case 28:
445
- workflows = _context8.sent;
446
- buildAndDeployWorkflow = _findInstanceProperty(_context2 = workflows.items).call(_context2, function (workflow) {
447
- return workflow.name === config.CircleCI.deploymentWorkflowName;
448
- });
449
- if (buildAndDeployWorkflow) {
450
- _context8.next = 32;
451
- break;
452
- }
453
- throw new Error("\u26A0\uFE0F No workflow called ".concat(config.CircleCI.deploymentWorkflowName, " found for deployment."));
454
- case 32:
455
- workflowId = buildAndDeployWorkflow.id;
456
- console.log("\u2139\uFE0F Found workflow to build and deploy with id ".concat(workflowId, "."));
457
- jobsRequest = circleCiApis.jobs({
458
- workflowId: workflowId
459
- });
460
- _context8.next = 37;
461
- return jobsRequest.execute({
462
- debug: cliFlags.debug
463
- });
464
- case 37:
465
- jobs = _context8.sent;
466
- console.log("\u2139\uFE0F Found jobs for workflow.");
467
- applicationApprovalJob = _findInstanceProperty(_context3 = jobs.items).call(_context3, function (job) {
468
- return job.name === approvalJob;
469
- });
470
- applicationApprovalJobId = applicationApprovalJob === null || applicationApprovalJob === void 0 ? void 0 : applicationApprovalJob.id;
471
- if (applicationApprovalJobId) {
472
- _context8.next = 43;
473
- break;
474
- }
475
- throw new Error(_concatInstanceProperty(_context4 = "\u270C\uFE0F Could not find deployment approval job named ".concat(approvalJob, " at revision ")).call(_context4, deploymentPipeline.vcs.revision, ". Maybe try again later."));
476
- case 43:
477
- console.log(_concatInstanceProperty(_context5 = "\u2139\uFE0F Found deployment approval job named ".concat(approvalJob, " with id ")).call(_context5, applicationApprovalJobId, "."));
478
- if (cliFlags.yes) {
479
- _context8.next = 48;
480
- break;
481
- }
482
- _context8.next = 47;
483
- return waitForConfirmationPrompt({
484
- approvalJob: approvalJob,
485
- revision: deploymentPipeline.vcs.revision
486
- });
487
- case 47:
488
- confirmationPrompt = _context8.sent;
489
- case 48:
490
- if (!(cliFlags.yes || (_confirmationPrompt = confirmationPrompt) !== null && _confirmationPrompt !== void 0 && _confirmationPrompt.confirmed)) {
491
- _context8.next = 71;
492
- break;
493
- }
494
- if (cliFlags.dryRun) {
495
- console.log("\uD83D\uDE4A Not approving deployment job due to dry run.");
496
- } else {
497
- console.log("\u2139\uFE0F Approving deployment job.");
498
- }
499
- approvalRequest = circleCiApis.approve({
500
- workflowId: workflowId,
501
- approvalRequestId: applicationApprovalJobId
502
- });
503
- _context8.next = 53;
504
- return approvalRequest.execute({
505
- debug: cliFlags.debug,
506
- skip: cliFlags.dryRun
507
- });
508
- case 53:
509
- if (!cliFlags.yes) {
510
- _context8.next = 57;
511
- break;
512
- }
513
- console.log("\u2139\uFE0F Skipping determining deployment job approved by ".concat(approvalJob, " due to '--yes' flag. Please check CircleCI manually."));
514
- _context8.next = 69;
515
- break;
516
- case 57:
517
- if (!cliFlags.dryRun) {
518
- _context8.next = 61;
519
- break;
520
- }
521
- console.log("\u270C\uFE0F Dry running hence could not determine deployment job approved by ".concat(approvalJob, "."));
522
- _context8.next = 69;
523
- break;
524
- case 61:
525
- if (!deploymentJob) {
526
- _context8.next = 68;
527
- break;
528
- }
529
- _context8.next = 64;
530
- return waitForDeploymentJobNumber({
531
- workflowId: workflowId,
532
- deploymentJob: deploymentJob,
533
- circleCiApis: circleCiApis
534
- }, {
535
- debug: cliFlags.debug,
536
- dryRun: cliFlags.dryRun,
537
- yes: cliFlags.yes
538
- });
539
- case 64:
540
- deploymentJobNumber = _context8.sent;
541
- console.log(_concatInstanceProperty(_context6 = _concatInstanceProperty(_context7 = "\uD83D\uDE4C The deployment via ".concat(approvalJob, " at revision ")).call(_context7, deploymentPipeline.vcs.revision, " is running at: ")).call(_context6, getJobUrl({
542
- projectName: config.CircleCI.projectName,
543
- pipelineNumber: deploymentPipeline.number,
544
- workflowId: workflowId,
545
- jobNumber: deploymentJobNumber
546
- })));
547
- _context8.next = 69;
548
- break;
549
- case 68:
550
- console.log("\u2139\uFE0F Skipping determining deployment job as no '--deployment-job' name to wait for was passed. Please check CircleCI manually.");
551
- case 69:
552
- _context8.next = 72;
553
- break;
554
- case 71:
555
- console.log("\u2139\uFE0F Not approving deployment job. Confirm the prompt or use '--yes' option.");
556
- case 72:
557
- case "end":
558
- return _context8.stop();
559
- }
560
- }, _callee);
561
- }));
562
- return _approve.apply(this, arguments);
237
+ async function approve(cliFlags, config, circleCiApis) {
238
+ var _config$CircleCI$pagi, _config$CircleCI$pagi2, _config$CircleCI$pagi3, _config$CircleCI$pagi4, _context2, _context3, _context5, _confirmationPrompt;
239
+ let approvalJob;
240
+ let deploymentJob;
241
+ if (cliFlags.deployment) {
242
+ var _config$deployments, _context;
243
+ const requestedDeployment = (_config$deployments = config.deployments) === null || _config$deployments === void 0 ? void 0 : _config$deployments[cliFlags.deployment];
244
+ if (!requestedDeployment) {
245
+ throw new Error("\u26A0\uFE0F Deployment ".concat(cliFlags.deployment, " not found in configuration. Make sure it exists."));
246
+ }
247
+ approvalJob = requestedDeployment.jobs.approval;
248
+ deploymentJob = requestedDeployment.jobs.deployment;
249
+ console.log(_concatInstanceProperty(_context = "\u2139\uFE0F Approving requested deployment ".concat(cliFlags.deployment, " with approval job ")).call(_context, approvalJob, "."));
250
+ } else {
251
+ approvalJob = cliFlags.approvalJob;
252
+ deploymentJob = cliFlags.deploymentJob;
253
+ console.log("\u2139\uFE0F Approving with approval job ".concat(approvalJob, "."));
254
+ }
255
+ const deploymentPipeline = cliFlags.yes ? await paginateToDeploymentPipeline({
256
+ circleCiApis,
257
+ buildRevision: cliFlags.buildRevision,
258
+ branch: cliFlags.branch,
259
+ debug: cliFlags.debug,
260
+ maxPages: (_config$CircleCI$pagi = (_config$CircleCI$pagi2 = config.CircleCI.pagination) === null || _config$CircleCI$pagi2 === void 0 ? void 0 : _config$CircleCI$pagi2.maxPages) !== null && _config$CircleCI$pagi !== void 0 ? _config$CircleCI$pagi : 1
261
+ }) : await waitForDeploymentPipelinePrompt({
262
+ branch: cliFlags.branch,
263
+ circleCiApis,
264
+ pagesForPipelineSelection: (_config$CircleCI$pagi3 = (_config$CircleCI$pagi4 = config.CircleCI.pagination) === null || _config$CircleCI$pagi4 === void 0 ? void 0 : _config$CircleCI$pagi4.pagesForPipelineSelection) !== null && _config$CircleCI$pagi3 !== void 0 ? _config$CircleCI$pagi3 : 1,
265
+ debug: cliFlags.debug
266
+ });
267
+ if (!deploymentPipeline) {
268
+ throw new Error("\u26A0\uFE0F No workflow called ".concat(config.CircleCI.deploymentWorkflowName, " found in any pipeline for deployment."));
269
+ }
270
+ console.log("\u2139\uFE0F Found pipeline for deployment with revision ".concat(deploymentPipeline.vcs.revision, "."));
271
+ const workflowsRequest = circleCiApis.workflows({
272
+ pipelineId: deploymentPipeline.id
273
+ });
274
+ const workflows = await workflowsRequest.execute({
275
+ debug: cliFlags.debug
276
+ });
277
+ const buildAndDeployWorkflow = _findInstanceProperty(_context2 = workflows.items).call(_context2, workflow => workflow.name === config.CircleCI.deploymentWorkflowName);
278
+ if (!buildAndDeployWorkflow) {
279
+ throw new Error("\u26A0\uFE0F No workflow called ".concat(config.CircleCI.deploymentWorkflowName, " found for deployment."));
280
+ }
281
+ const workflowId = buildAndDeployWorkflow.id;
282
+ console.log("\u2139\uFE0F Found workflow to build and deploy with id ".concat(workflowId, "."));
283
+ const jobsRequest = circleCiApis.jobs({
284
+ workflowId
285
+ });
286
+ const jobs = await jobsRequest.execute({
287
+ debug: cliFlags.debug
288
+ });
289
+ console.log("\u2139\uFE0F Found jobs for workflow.");
290
+ const applicationApprovalJob = _findInstanceProperty(_context3 = jobs.items).call(_context3, job => job.name === approvalJob);
291
+ const applicationApprovalJobId = applicationApprovalJob === null || applicationApprovalJob === void 0 ? void 0 : applicationApprovalJob.id;
292
+ if (!applicationApprovalJobId) {
293
+ var _context4;
294
+ throw new Error(_concatInstanceProperty(_context4 = "\u270C\uFE0F Could not find deployment approval job named ".concat(approvalJob, " at revision ")).call(_context4, deploymentPipeline.vcs.revision, ". Maybe try again later."));
295
+ }
296
+ console.log(_concatInstanceProperty(_context5 = "\u2139\uFE0F Found deployment approval job named ".concat(approvalJob, " with id ")).call(_context5, applicationApprovalJobId, "."));
297
+ let confirmationPrompt;
298
+ if (!cliFlags.yes) {
299
+ confirmationPrompt = await waitForConfirmationPrompt({
300
+ approvalJob: approvalJob,
301
+ revision: deploymentPipeline.vcs.revision
302
+ });
303
+ }
304
+ if (cliFlags.yes || (_confirmationPrompt = confirmationPrompt) !== null && _confirmationPrompt !== void 0 && _confirmationPrompt.confirmed) {
305
+ if (cliFlags.dryRun) {
306
+ console.log("\uD83D\uDE4A Not approving deployment job due to dry run.");
307
+ } else {
308
+ console.log("\u2139\uFE0F Approving deployment job.");
309
+ }
310
+ const approvalRequest = circleCiApis.approve({
311
+ workflowId,
312
+ approvalRequestId: applicationApprovalJobId
313
+ });
314
+ await approvalRequest.execute({
315
+ debug: cliFlags.debug,
316
+ skip: cliFlags.dryRun
317
+ });
318
+ if (cliFlags.yes) {
319
+ console.log("\u2139\uFE0F Skipping determining deployment job approved by ".concat(approvalJob, " due to '--yes' flag. Please check CircleCI manually."));
320
+ } else if (cliFlags.dryRun) {
321
+ console.log("\u270C\uFE0F Dry running hence could not determine deployment job approved by ".concat(approvalJob, "."));
322
+ } else if (deploymentJob) {
323
+ var _context6, _context7;
324
+ const deploymentJobNumber = await waitForDeploymentJobNumber({
325
+ workflowId,
326
+ deploymentJob,
327
+ circleCiApis
328
+ }, {
329
+ debug: cliFlags.debug,
330
+ dryRun: cliFlags.dryRun,
331
+ yes: cliFlags.yes
332
+ });
333
+ console.log(_concatInstanceProperty(_context6 = _concatInstanceProperty(_context7 = "\uD83D\uDE4C The deployment via ".concat(approvalJob, " at revision ")).call(_context7, deploymentPipeline.vcs.revision, " is running at: ")).call(_context6, getJobUrl({
334
+ projectName: config.CircleCI.projectName,
335
+ pipelineNumber: deploymentPipeline.number,
336
+ workflowId,
337
+ jobNumber: deploymentJobNumber
338
+ })));
339
+ } else {
340
+ console.log("\u2139\uFE0F Skipping determining deployment job as no '--deployment-job' name to wait for was passed. Please check CircleCI manually.");
341
+ }
342
+ } else {
343
+ console.log("\u2139\uFE0F Not approving deployment job. Confirm the prompt or use '--yes' option.");
344
+ }
563
345
  }
564
346
 
565
- function processCircleCiResponse(_x) {
566
- return _processCircleCiResponse.apply(this, arguments);
567
- }
568
- function _processCircleCiResponse() {
569
- _processCircleCiResponse = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(response) {
570
- var _context4, _context5, errorJson, errorText;
571
- return _regeneratorRuntime.wrap(function _callee2$(_context6) {
572
- while (1) switch (_context6.prev = _context6.next) {
573
- case 0:
574
- if (response.ok) {
575
- _context6.next = 14;
576
- break;
577
- }
578
- _context6.prev = 1;
579
- _context6.next = 4;
580
- return response.json();
581
- case 4:
582
- errorJson = _context6.sent;
583
- if (errorJson.message.match(/job already approved/i)) {
584
- console.log('ℹ️ Deployment job is already approved.');
585
- process.exit(0);
586
- }
587
- _context6.next = 10;
588
- break;
589
- case 8:
590
- _context6.prev = 8;
591
- _context6.t0 = _context6["catch"](1);
592
- case 10:
593
- _context6.next = 12;
594
- return response.text();
595
- case 12:
596
- errorText = _context6.sent;
597
- throw new Error(_concatInstanceProperty(_context4 = _concatInstanceProperty(_context5 = "".concat(response.status, ": Network response was not ok.\n\n Status text is ")).call(_context5, response.statusText, " and text is ")).call(_context4, errorText, "."));
598
- case 14:
599
- return _context6.abrupt("return", response.json());
600
- case 15:
601
- case "end":
602
- return _context6.stop();
347
+ async function processCircleCiResponse(response) {
348
+ if (!response.ok) {
349
+ var _context, _context2;
350
+ /**
351
+ * NOTE:
352
+ * Trying to handle known but undocumented responses of the CircleCI API.
353
+ *
354
+ * 1. Message: Already approved job
355
+ * Deployment was already triggered manually or by train the day before.
356
+ */
357
+ try {
358
+ const errorJson = await response.json();
359
+ if (errorJson.message.match(/job already approved/i)) {
360
+ console.log('ℹ️ Deployment job is already approved.');
361
+ process.exit(0);
603
362
  }
604
- }, _callee2, null, [[1, 8]]);
605
- }));
606
- return _processCircleCiResponse.apply(this, arguments);
363
+ } catch (e) {
364
+ // ignore
365
+ }
366
+ const errorText = await response.text();
367
+ throw new Error(_concatInstanceProperty(_context = _concatInstanceProperty(_context2 = "".concat(response.status, ": Network response was not ok.\n\n Status text is ")).call(_context2, response.statusText, " and text is ")).call(_context, errorText, "."));
368
+ }
369
+ return response.json();
607
370
  }
608
371
  function createCircleCiClient(_ref) {
609
- var projectName = _ref.projectName,
372
+ let projectName = _ref.projectName,
610
373
  apiBaseUrl = _ref.apiBaseUrl;
611
- function _execute2(_x2) {
612
- return _execute.apply(this, arguments);
613
- }
614
- function _execute() {
615
- _execute = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(api) {
616
- var _context2;
617
- var _ref6,
618
- skip,
619
- debug,
620
- url,
621
- urlSearchParams,
622
- _i,
623
- _Object$entries,
624
- _ref7,
625
- _ref8,
626
- key,
627
- value,
628
- response,
629
- processedCircleCiResponse,
630
- _args = arguments;
631
- return _regeneratorRuntime.wrap(function _callee$(_context3) {
632
- while (1) switch (_context3.prev = _context3.next) {
633
- case 0:
634
- _ref6 = _args.length > 1 && _args[1] !== undefined ? _args[1] : {}, skip = _ref6.skip, debug = _ref6.debug;
635
- url = _concatInstanceProperty(_context2 = "".concat(apiBaseUrl)).call(_context2, api.url);
636
- if (api.params && api.method === 'GET') {
637
- urlSearchParams = new _URLSearchParams();
638
- for (_i = 0, _Object$entries = _Object$entries2(api.params); _i < _Object$entries.length; _i++) {
639
- _ref7 = _Object$entries[_i];
640
- _ref8 = _slicedToArray(_ref7, 2);
641
- key = _ref8[0];
642
- value = _ref8[1];
643
- if (value !== null && value !== undefined) {
644
- urlSearchParams.append(key, value);
645
- }
646
- }
647
- url += "?".concat(urlSearchParams.toString());
648
- }
649
- if (!skip) {
650
- _context3.next = 6;
651
- break;
652
- }
653
- if (debug) {
654
- console.log("\uD83C\uDFED Skipping CircleCI call API at: ".concat(url, "."));
655
- }
656
-
657
- // @ts-expect-error
658
- return _context3.abrupt("return", _Promise.resolve());
659
- case 6:
660
- if (debug) {
661
- console.log("\uD83C\uDFED Calling CircleCI API at: ".concat(url, "."));
662
- }
663
- _context3.prev = 7;
664
- _context3.next = 10;
665
- return fetch(url, {
666
- headers: api.headers,
667
- method: api.method,
668
- body: api.method === 'POST' ? _JSON$stringify(api.params) : undefined
669
- });
670
- case 10:
671
- response = _context3.sent;
672
- _context3.next = 13;
673
- return processCircleCiResponse(response);
674
- case 13:
675
- processedCircleCiResponse = _context3.sent;
676
- return _context3.abrupt("return", processedCircleCiResponse);
677
- case 17:
678
- _context3.prev = 17;
679
- _context3.t0 = _context3["catch"](7);
680
- console.log("\u26A0\uFE0F Calling CircleCI API at: ".concat(url, " failed."));
681
- throw _context3.t0;
682
- case 21:
683
- case "end":
684
- return _context3.stop();
374
+ async function execute(api) {
375
+ var _context3;
376
+ let _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
377
+ skip = _ref2.skip,
378
+ debug = _ref2.debug;
379
+ let url = _concatInstanceProperty(_context3 = "".concat(apiBaseUrl)).call(_context3, api.url);
380
+ if (api.params && api.method === 'GET') {
381
+ const urlSearchParams = new _URLSearchParams();
382
+ for (const _ref3 of _Object$entries(api.params)) {
383
+ var _ref4 = _slicedToArray(_ref3, 2);
384
+ const key = _ref4[0];
385
+ const value = _ref4[1];
386
+ if (value !== null && value !== undefined) {
387
+ urlSearchParams.append(key, value);
685
388
  }
686
- }, _callee, null, [[7, 17]]);
687
- }));
688
- return _execute.apply(this, arguments);
389
+ }
390
+ url += "?".concat(urlSearchParams.toString());
391
+ }
392
+ if (skip) {
393
+ if (debug) {
394
+ console.log("\uD83C\uDFED Skipping CircleCI call API at: ".concat(url, "."));
395
+ }
396
+
397
+ // @ts-expect-error
398
+ return _Promise.resolve();
399
+ }
400
+ if (debug) {
401
+ console.log("\uD83C\uDFED Calling CircleCI API at: ".concat(url, "."));
402
+ }
403
+ try {
404
+ const response = await fetch(url, {
405
+ headers: api.headers,
406
+ method: api.method,
407
+ body: api.method === 'POST' ? _JSON$stringify(api.params) : undefined
408
+ });
409
+ const processedCircleCiResponse = await processCircleCiResponse(response);
410
+ return processedCircleCiResponse;
411
+ } catch (error) {
412
+ console.log("\u26A0\uFE0F Calling CircleCI API at: ".concat(url, " failed."));
413
+ throw error;
414
+ }
689
415
  }
690
416
  return {
691
- pipelines: function pipelines() {
692
- var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
693
- pageToken = _ref2.pageToken,
694
- _ref2$projectSlug = _ref2.projectSlug,
695
- projectSlug = _ref2$projectSlug === void 0 ? "gh/commercetools/".concat(projectName) : _ref2$projectSlug,
696
- _ref2$branch = _ref2.branch,
697
- branch = _ref2$branch === void 0 ? 'main' : _ref2$branch;
417
+ pipelines: function () {
418
+ let _ref5 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
419
+ pageToken = _ref5.pageToken,
420
+ _ref5$projectSlug = _ref5.projectSlug,
421
+ projectSlug = _ref5$projectSlug === void 0 ? "gh/commercetools/".concat(projectName) : _ref5$projectSlug,
422
+ _ref5$branch = _ref5.branch,
423
+ branch = _ref5$branch === void 0 ? 'main' : _ref5$branch;
698
424
  return {
699
- execute: function execute(options) {
700
- return _execute2({
701
- url: "/project/".concat(projectSlug, "/pipeline"),
702
- headers: {
703
- 'Content-Type': 'application/json',
704
- // The CLI throws if this is not present on environment
705
- 'Circle-Token': process.env.CIRCLE_TOKEN
706
- },
707
- method: 'GET',
708
- params: {
709
- branch: branch,
710
- 'page-token': pageToken
711
- }
712
- }, options);
713
- }
425
+ execute: options => execute({
426
+ url: "/project/".concat(projectSlug, "/pipeline"),
427
+ headers: {
428
+ 'Content-Type': 'application/json',
429
+ // The CLI throws if this is not present on environment
430
+ 'Circle-Token': process.env.CIRCLE_TOKEN
431
+ },
432
+ method: 'GET',
433
+ params: {
434
+ branch,
435
+ 'page-token': pageToken
436
+ }
437
+ }, options)
714
438
  };
715
439
  },
716
- workflows: function workflows(_ref3) {
717
- var pipelineId = _ref3.pipelineId;
440
+ workflows: _ref6 => {
441
+ let pipelineId = _ref6.pipelineId;
718
442
  return {
719
- execute: function execute(options) {
720
- return _execute2({
721
- url: "/pipeline/".concat(pipelineId, "/workflow"),
722
- headers: {
723
- 'Content-Type': 'application/json',
724
- // The CLI throws if this is not present on environment
725
- 'Circle-Token': process.env.CIRCLE_TOKEN
726
- },
727
- method: 'GET'
728
- }, options);
729
- }
443
+ execute: options => execute({
444
+ url: "/pipeline/".concat(pipelineId, "/workflow"),
445
+ headers: {
446
+ 'Content-Type': 'application/json',
447
+ // The CLI throws if this is not present on environment
448
+ 'Circle-Token': process.env.CIRCLE_TOKEN
449
+ },
450
+ method: 'GET'
451
+ }, options)
730
452
  };
731
453
  },
732
- jobs: function jobs(_ref4) {
733
- var workflowId = _ref4.workflowId;
454
+ jobs: _ref7 => {
455
+ let workflowId = _ref7.workflowId;
734
456
  return {
735
- execute: function execute(options) {
736
- return _execute2({
737
- url: "/workflow/".concat(workflowId, "/job"),
738
- headers: {
739
- 'Content-Type': 'application/json',
740
- // The CLI throws if this is not present on environment
741
- 'Circle-Token': process.env.CIRCLE_TOKEN
742
- },
743
- method: 'GET'
744
- }, options);
745
- }
457
+ execute: options => execute({
458
+ url: "/workflow/".concat(workflowId, "/job"),
459
+ headers: {
460
+ 'Content-Type': 'application/json',
461
+ // The CLI throws if this is not present on environment
462
+ 'Circle-Token': process.env.CIRCLE_TOKEN
463
+ },
464
+ method: 'GET'
465
+ }, options)
746
466
  };
747
467
  },
748
- approve: function approve(_ref5) {
749
- var workflowId = _ref5.workflowId,
750
- approvalRequestId = _ref5.approvalRequestId;
468
+ approve: _ref8 => {
469
+ let workflowId = _ref8.workflowId,
470
+ approvalRequestId = _ref8.approvalRequestId;
751
471
  return {
752
- execute: function execute(options) {
753
- var _context;
754
- return _execute2({
755
- url: _concatInstanceProperty(_context = "/workflow/".concat(workflowId, "/approve/")).call(_context, approvalRequestId, " "),
472
+ execute: options => {
473
+ var _context4;
474
+ return execute({
475
+ url: _concatInstanceProperty(_context4 = "/workflow/".concat(workflowId, "/approve/")).call(_context4, approvalRequestId, " "),
756
476
  headers: {
757
477
  'Content-Type': 'application/json',
758
478
  // The CLI throws if this is not present on environment
@@ -766,53 +486,41 @@ function createCircleCiClient(_ref) {
766
486
  };
767
487
  }
768
488
 
769
- function run() {
770
- return _run.apply(this, arguments);
771
- }
772
- function _run() {
773
- _run = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
774
- var config, circleCiApis, _context, cliFlags, cliCommands, cliCommand;
775
- return _regeneratorRuntime.wrap(function _callee$(_context2) {
776
- while (1) switch (_context2.prev = _context2.next) {
777
- case 0:
778
- _context2.next = 2;
779
- return loadConfig();
780
- case 2:
781
- config = _context2.sent;
782
- throwIfConfigurationLacksRequiredValues(config);
783
- circleCiApis = createCircleCiClient({
784
- projectName: config.CircleCI.projectName,
785
- apiBaseUrl: config.CircleCI.apiBaseUrl
786
- });
787
- _context2.prev = 5;
788
- cliFlags = mri(_sliceInstanceProperty(_context = process.argv).call(_context, 2), {
789
- alias: {
790
- help: ['h']
791
- },
792
- boolean: ['dry-run', 'debug', 'yes'],
793
- default: {
794
- branch: 'main'
795
- }
796
- });
797
- cliCommands = cliFlags._;
798
- if (cliCommands.length === 0 ||
799
- // @ts-expect-error mri is not typed for the help command.
800
- cliCommands.help && cliCommands.length === 0) {
801
- console.log("\nUsage: deployment-cli [command] [flags]\n\nDisplays help information.\n\nCommand:\n approve Approves a job and by this triggers a deployment of a component. It requires a \"CIRCLE_TOKEN\" environment variable (https://circleci.com/docs/2.0/managing-api-tokens/).\n\nOptions:\n --approval-job The name of the approval job to approve a deployment with.\n --deployment-job (optional) The name of the deployment job triggered by the approval job. If passed the CLI will print a URL to the deployment triggered on CircleCI.\n --deployment (optional) The name of a deployment configured in the configuration file.\n --build-revision <git-sha> (optional) The git commit SHA that needs to be deployed. If not specified, the last successful pipeline is used.\n --branch (optional) The git branch to deploy from. If not specified, defaults to 'main'.\n --yes (optional) Skip all confirmation prompts. Useful in Continuous integration (CI) to automatically answer confirmation questions.\n\nGeneral options:\n --dry-run (optional) Simulate a deployment.\n --debug (optional) Print additional debug information.\n");
802
- process.exit(0);
803
- }
804
- cliCommand = cliCommands[0];
805
- if (cliFlags['dry-run']) {
806
- console.log("\n \uD83D\uDE4A Do not worry. This is a dry run!\n ");
807
- }
808
- console.log("\uD83C\uDFC3 Running ".concat(cliCommand, " command"));
809
- _context2.t0 = cliCommand;
810
- _context2.next = _context2.t0 === 'approve' ? 15 : 19;
811
- break;
812
- case 15:
489
+ async function run() {
490
+ const config = await loadConfig();
491
+ throwIfConfigurationLacksRequiredValues(config);
492
+ const circleCiApis = createCircleCiClient({
493
+ projectName: config.CircleCI.projectName,
494
+ apiBaseUrl: config.CircleCI.apiBaseUrl
495
+ });
496
+ try {
497
+ var _context;
498
+ const cliFlags = mri(_sliceInstanceProperty(_context = process.argv).call(_context, 2), {
499
+ alias: {
500
+ help: ['h']
501
+ },
502
+ boolean: ['dry-run', 'debug', 'yes'],
503
+ default: {
504
+ branch: 'main'
505
+ }
506
+ });
507
+ const cliCommands = cliFlags._;
508
+ if (cliCommands.length === 0 ||
509
+ // @ts-expect-error mri is not typed for the help command.
510
+ cliCommands.help && cliCommands.length === 0) {
511
+ console.log("\nUsage: deployment-cli [command] [flags]\n\nDisplays help information.\n\nCommand:\n approve Approves a job and by this triggers a deployment of a component. It requires a \"CIRCLE_TOKEN\" environment variable (https://circleci.com/docs/2.0/managing-api-tokens/).\n\nOptions:\n --approval-job The name of the approval job to approve a deployment with.\n --deployment-job (optional) The name of the deployment job triggered by the approval job. If passed the CLI will print a URL to the deployment triggered on CircleCI.\n --deployment (optional) The name of a deployment configured in the configuration file.\n --build-revision <git-sha> (optional) The git commit SHA that needs to be deployed. If not specified, the last successful pipeline is used.\n --branch (optional) The git branch to deploy from. If not specified, defaults to 'main'.\n --yes (optional) Skip all confirmation prompts. Useful in Continuous integration (CI) to automatically answer confirmation questions.\n\nGeneral options:\n --dry-run (optional) Simulate a deployment.\n --debug (optional) Print additional debug information.\n");
512
+ process.exit(0);
513
+ }
514
+ const cliCommand = cliCommands[0];
515
+ if (cliFlags['dry-run']) {
516
+ console.log("\n \uD83D\uDE4A Do not worry. This is a dry run!\n ");
517
+ }
518
+ console.log("\uD83C\uDFC3 Running ".concat(cliCommand, " command"));
519
+ switch (cliCommand) {
520
+ case 'approve':
521
+ {
813
522
  throwIfRequiredEnvironmentVariableIsUnset(['CIRCLE_TOKEN']);
814
- _context2.next = 18;
815
- return approve({
523
+ await approve({
816
524
  deployment: cliFlags.deployment,
817
525
  branch: cliFlags.branch,
818
526
  approvalJob: cliFlags['approval-job'],
@@ -822,25 +530,16 @@ function _run() {
822
530
  debug: cliFlags.debug,
823
531
  dryRun: cliFlags['dry-run']
824
532
  }, config, circleCiApis);
825
- case 18:
826
533
  process.exit(0);
827
- case 19:
828
- throw new Error("\uD83D\uDC80 Unknown command \"".concat(cliCommand, "\"."));
829
- case 20:
830
- _context2.next = 26;
831
- break;
832
- case 22:
833
- _context2.prev = 22;
834
- _context2.t1 = _context2["catch"](5);
835
- console.error(_context2.t1);
836
- process.exit(1);
837
- case 26:
838
- case "end":
839
- return _context2.stop();
840
- }
841
- }, _callee, null, [[5, 22]]);
842
- }));
843
- return _run.apply(this, arguments);
534
+ }
535
+ // eslint-disable-next-line no-fallthrough
536
+ default:
537
+ throw new Error("\uD83D\uDC80 Unknown command \"".concat(cliCommand, "\"."));
538
+ }
539
+ } catch (error) {
540
+ console.error(error);
541
+ process.exit(1);
542
+ }
844
543
  }
845
544
 
846
545
  export { run };