backport 8.1.0 → 8.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/backportRun.js +5 -14
  2. package/dist/entrypoint.cli.js +1 -1
  3. package/dist/lib/cherrypickAndCreateTargetPullRequest.d.ts +1 -3
  4. package/dist/lib/cherrypickAndCreateTargetPullRequest.js +6 -2
  5. package/dist/lib/child-process-promisified.js +5 -3
  6. package/dist/lib/env.d.ts +3 -1
  7. package/dist/lib/env.js +2 -2
  8. package/dist/lib/getTargetBranches.d.ts +1 -1
  9. package/dist/lib/getTargetBranches.js +1 -1
  10. package/dist/lib/getTargetBranches.test.js +11 -7
  11. package/dist/lib/github/v3/addLabelsToPullRequest.js +1 -1
  12. package/dist/lib/github/v3/addReviewersToPullRequest.js +1 -1
  13. package/dist/lib/github/v3/createPullRequest.js +6 -6
  14. package/dist/lib/github/v3/createStatusComment.js +6 -4
  15. package/dist/lib/github/v3/createStatusComment.test.js +108 -3
  16. package/dist/lib/github/v4/apiRequestV4.js +7 -7
  17. package/dist/lib/github/v4/validateTargetBranches.d.ts +14 -0
  18. package/dist/lib/github/v4/validateTargetBranches.js +46 -0
  19. package/dist/lib/github/v4/validateTargetBranches.private.test.d.ts +1 -0
  20. package/dist/lib/github/v4/validateTargetBranches.private.test.js +51 -0
  21. package/dist/lib/logger.d.ts +2 -0
  22. package/dist/lib/logger.js +20 -14
  23. package/dist/options/cliArgs.d.ts +6 -6
  24. package/dist/options/cliArgs.js +3 -3
  25. package/dist/options/cliArgs.test.js +10 -10
  26. package/dist/options/config/readConfigFile.d.ts +5 -5
  27. package/dist/options/options.d.ts +4 -4
  28. package/dist/options/options.js +4 -0
  29. package/dist/runSequentially.d.ts +1 -3
  30. package/dist/runSequentially.js +2 -3
  31. package/dist/test/e2e/cli/different-merge-strategies.private.test.js +1 -1
  32. package/dist/test/e2e/cli/entrypoint.cli.private.test.js +7 -260
  33. package/dist/test/e2e/cli/error-handling-interactive-mode.private.test.d.ts +1 -0
  34. package/dist/test/e2e/cli/error-handling-interactive-mode.private.test.js +80 -0
  35. package/dist/test/e2e/cli/error-handling-non-interactive-mode.private.test.d.ts +1 -0
  36. package/dist/test/e2e/cli/error-handling-non-interactive-mode.private.test.js +199 -0
  37. package/dist/test/e2e/cli/interactive-error-handling.private.test.d.ts +1 -0
  38. package/dist/test/e2e/cli/interactive-error-handling.private.test.js +80 -0
  39. package/dist/test/e2e/cli/non-interactive-error-handling.private.test.d.ts +1 -0
  40. package/dist/test/e2e/cli/non-interactive-error-handling.private.test.js +198 -0
  41. package/dist/test/e2e/cli/repo-with-backportrc-removed.private.test.js +1 -1
  42. package/dist/test/e2e/cli/runBackportViaCli.js +1 -1
  43. package/dist/utils/packageVersion.d.ts +1 -1
  44. package/dist/utils/packageVersion.js +1 -1
  45. package/package.json +5 -5
  46. package/yarn.lock +60 -55
@@ -8,7 +8,6 @@ const chalk_1 = __importDefault(require("chalk"));
8
8
  const BackportError_1 = require("./lib/BackportError");
9
9
  const env_1 = require("./lib/env");
10
10
  const getCommits_1 = require("./lib/getCommits");
11
- const getGitConfigAuthor_1 = require("./lib/getGitConfigAuthor");
12
11
  const getTargetBranches_1 = require("./lib/getTargetBranches");
13
12
  const createStatusComment_1 = require("./lib/github/v3/createStatusComment");
14
13
  const apiRequestV4_1 = require("./lib/github/v4/apiRequestV4");
@@ -19,7 +18,7 @@ const cliArgs_1 = require("./options/cliArgs");
19
18
  const options_1 = require("./options/options");
20
19
  const runSequentially_1 = require("./runSequentially");
21
20
  async function backportRun({ processArgs, optionsFromModule = {}, exitCodeOnFailure, }) {
22
- const { interactive, logFilePath } = (0, cliArgs_1.getEarlyArguments)(processArgs, optionsFromModule);
21
+ const { interactive, logFilePath } = (0, cliArgs_1.getRuntimeArguments)(processArgs, optionsFromModule);
23
22
  const logger = (0, logger_1.initLogger)({ interactive, logFilePath });
24
23
  let optionsFromCliArgs;
25
24
  try {
@@ -42,10 +41,7 @@ async function backportRun({ processArgs, optionsFromModule = {}, exitCodeOnFail
42
41
  let commits = [];
43
42
  const spinner = (0, ora_1.ora)(interactive).start('Initializing...');
44
43
  try {
45
- options = await (0, options_1.getOptions)({
46
- optionsFromCliArgs,
47
- optionsFromModule,
48
- });
44
+ options = await (0, options_1.getOptions)({ optionsFromCliArgs, optionsFromModule });
49
45
  logger.info('Backporting options', options);
50
46
  spinner.stop();
51
47
  commits = await (0, getCommits_1.getCommits)(options);
@@ -55,15 +51,11 @@ async function backportRun({ processArgs, optionsFromModule = {}, exitCodeOnFail
55
51
  }
56
52
  const targetBranches = await (0, getTargetBranches_1.getTargetBranches)(options, commits);
57
53
  logger.info('Target branches', targetBranches);
58
- const [gitConfigAuthor] = await Promise.all([
59
- (0, getGitConfigAuthor_1.getGitConfigAuthor)(options),
60
- (0, setupRepo_1.setupRepo)(options),
61
- ]);
54
+ await (0, setupRepo_1.setupRepo)(options);
62
55
  const results = await (0, runSequentially_1.runSequentially)({
63
56
  options,
64
57
  commits,
65
58
  targetBranches,
66
- gitConfigAuthor,
67
59
  });
68
60
  logger.info('Results', results);
69
61
  const backportResponse = {
@@ -122,8 +114,7 @@ function outputError({ e, logFilePath, }) {
122
114
  (0, logger_1.consoleLog)(chalk_1.default.bold('⚠️ Ouch! An unhandled error occured 😿'));
123
115
  (0, logger_1.consoleLog)(e.stack ? e.stack : e.message);
124
116
  (0, logger_1.consoleLog)('Please open an issue in https://github.com/sqren/backport/issues or contact me directly on https://twitter.com/sorenlouv');
125
- (0, logger_1.consoleLog)(chalk_1.default.italic(`For additional details see the logs: ${(0, env_1.getLogfilePath)({
126
- logFilePath,
127
- })}`));
117
+ const infoLogPath = (0, env_1.getLogfilePath)({ logFilePath, logLevel: 'info' });
118
+ (0, logger_1.consoleLog)(chalk_1.default.italic(`For additional details see the logs: ${infoLogPath}`));
128
119
  }
129
120
  }
@@ -5,7 +5,7 @@ const cliArgs_1 = require("./options/cliArgs");
5
5
  const processArgs = process.argv.slice(2);
6
6
  // this is the entrypoint when running from command line
7
7
  (0, backportRun_1.backportRun)({ processArgs, exitCodeOnFailure: true }).then((backportResponse) => {
8
- const { interactive, ls } = (0, cliArgs_1.getEarlyArguments)(processArgs);
8
+ const { interactive, ls } = (0, cliArgs_1.getRuntimeArguments)(processArgs);
9
9
  if (!interactive || ls) {
10
10
  // eslint-disable-next-line no-console
11
11
  console.log(JSON.stringify(backportResponse));
@@ -1,11 +1,9 @@
1
1
  import { ValidConfigOptions } from '../options/options';
2
- import { GitConfigAuthor } from './getGitConfigAuthor';
3
2
  import { Commit } from './sourceCommit/parseSourceCommit';
4
- export declare function cherrypickAndCreateTargetPullRequest({ options, commits, targetBranch, gitConfigAuthor, }: {
3
+ export declare function cherrypickAndCreateTargetPullRequest({ options, commits, targetBranch, }: {
5
4
  options: ValidConfigOptions;
6
5
  commits: Commit[];
7
6
  targetBranch: string;
8
- gitConfigAuthor?: GitConfigAuthor;
9
7
  }): Promise<{
10
8
  url: string;
11
9
  number: number;
@@ -10,6 +10,7 @@ const BackportError_1 = require("./BackportError");
10
10
  const child_process_promisified_1 = require("./child-process-promisified");
11
11
  const env_1 = require("./env");
12
12
  const getCommitsWithoutBackports_1 = require("./getCommitsWithoutBackports");
13
+ const getGitConfigAuthor_1 = require("./getGitConfigAuthor");
13
14
  const git_1 = require("./git");
14
15
  const commitFormatters_1 = require("./github/commitFormatters");
15
16
  const addAssigneesToPullRequest_1 = require("./github/v3/addAssigneesToPullRequest");
@@ -21,11 +22,14 @@ const logger_1 = require("./logger");
21
22
  const ora_1 = require("./ora");
22
23
  const prompts_1 = require("./prompts");
23
24
  const sequentially_1 = require("./sequentially");
24
- async function cherrypickAndCreateTargetPullRequest({ options, commits, targetBranch, gitConfigAuthor, }) {
25
+ async function cherrypickAndCreateTargetPullRequest({ options, commits, targetBranch, }) {
25
26
  const backportBranch = getBackportBranchName(targetBranch, commits);
26
27
  const repoForkOwner = (0, git_1.getRepoForkOwner)(options);
27
28
  (0, logger_1.consoleLog)(`\n${chalk_1.default.bold(`Backporting to ${targetBranch}:`)}`);
28
- await (0, git_1.createBackportBranch)({ options, targetBranch, backportBranch });
29
+ const [gitConfigAuthor] = await Promise.all([
30
+ (0, getGitConfigAuthor_1.getGitConfigAuthor)(options),
31
+ (0, git_1.createBackportBranch)({ options, targetBranch, backportBranch }),
32
+ ]);
29
33
  await (0, sequentially_1.sequentially)(commits, (commit) => waitForCherrypick(options, commit, targetBranch, gitConfigAuthor));
30
34
  if (options.dryRun) {
31
35
  (0, ora_1.ora)(options.interactive).succeed('Dry run complete');
@@ -28,13 +28,14 @@ async function spawnPromise(cmd, cmdArgs, cwd) {
28
28
  stderr += data;
29
29
  });
30
30
  subprocess.on('close', (code) => {
31
+ const fullCmd = `${cmd} ${cmdArgs.join(' ')}`;
32
+ logger_1.logger.info(`Running command: "${fullCmd}"`);
31
33
  if (code === 0 || code === null) {
32
- logger_1.logger.verbose(`spawn success "${cmdArgs}"`);
33
34
  resolve({ cmdArgs, code, stderr, stdout });
34
35
  }
35
36
  else {
36
37
  const err = new SpawnError({ cmdArgs, code, stderr, stdout });
37
- logger_1.logger.info('spawn error', err);
38
+ logger_1.logger.verbose(`Error when running command: "${fullCmd}"`, err);
38
39
  reject(err);
39
40
  }
40
41
  });
@@ -47,7 +48,8 @@ exports.spawnPromise = spawnPromise;
47
48
  exports.spawnOriginal = child_process_1.default.spawn;
48
49
  class SpawnError extends Error {
49
50
  constructor(context) {
50
- const message = `Code: ${context.code}; Args: ${JSON.stringify(context.cmdArgs)}; ${context.stderr.trim()}`;
51
+ const cmdArgs = context.cmdArgs.join(' ');
52
+ const message = `Code: ${context.code}, Args: "${cmdArgs}", Message: ${context.stderr.trim()}`;
51
53
  super(message);
52
54
  Error.captureStackTrace(this, SpawnError);
53
55
  this.name = 'SpawnError';
package/dist/lib/env.d.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import { ValidConfigOptions } from '../options/options';
2
+ import { LogLevel } from './logger';
2
3
  export declare function getBackportDirPath(): string;
3
- export declare function getLogfilePath({ logFilePath }: {
4
+ export declare function getLogfilePath({ logFilePath, logLevel, }: {
4
5
  logFilePath?: string;
6
+ logLevel: LogLevel;
5
7
  }): string;
6
8
  export declare function getGlobalConfigPath(globalConfigFile: string | undefined): string;
7
9
  export declare function getRepoPath({ repoOwner, repoName, dir }: ValidConfigOptions): string;
package/dist/lib/env.js CHANGED
@@ -10,11 +10,11 @@ function getBackportDirPath() {
10
10
  return path_1.default.join((0, os_1.homedir)(), '.backport');
11
11
  }
12
12
  exports.getBackportDirPath = getBackportDirPath;
13
- function getLogfilePath({ logFilePath }) {
13
+ function getLogfilePath({ logFilePath, logLevel, }) {
14
14
  if (logFilePath) {
15
15
  return path_1.default.resolve(logFilePath);
16
16
  }
17
- return path_1.default.join((0, os_1.homedir)(), '.backport', 'backport.log');
17
+ return path_1.default.join((0, os_1.homedir)(), '.backport', `backport.${logLevel}.log`);
18
18
  }
19
19
  exports.getLogfilePath = getLogfilePath;
20
20
  function getGlobalConfigPath(globalConfigFile) {
@@ -1,5 +1,5 @@
1
1
  import { TargetBranchChoice } from '../options/ConfigOptions';
2
2
  import { ValidConfigOptions } from '../options/options';
3
3
  import { Commit } from './sourceCommit/parseSourceCommit';
4
- export declare function getTargetBranches(options: ValidConfigOptions, commits: Commit[]): string[] | Promise<string[]>;
4
+ export declare function getTargetBranches(options: ValidConfigOptions, commits: Commit[]): Promise<string[]>;
5
5
  export declare function getTargetBranchChoices(options: ValidConfigOptions, missingTargetBranches: string[], sourceBranch: string): TargetBranchChoice[];
@@ -4,7 +4,7 @@ exports.getTargetBranchChoices = exports.getTargetBranches = void 0;
4
4
  const lodash_1 = require("lodash");
5
5
  const BackportError_1 = require("./BackportError");
6
6
  const prompts_1 = require("./prompts");
7
- function getTargetBranches(options, commits) {
7
+ async function getTargetBranches(options, commits) {
8
8
  // target branches already specified (in contrast to letting the user choose from a list)
9
9
  if (!(0, lodash_1.isEmpty)(options.targetBranches)) {
10
10
  return options.targetBranches;
@@ -24,6 +24,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
26
  const getTargetBranches_1 = require("./getTargetBranches");
27
+ const validateTargetBranches = __importStar(require("./github/v4/validateTargetBranches"));
27
28
  const prompts = __importStar(require("./prompts"));
28
29
  describe('getTargetBranches', () => {
29
30
  let promptSpy;
@@ -76,8 +77,11 @@ describe('getTargetBranches', () => {
76
77
  });
77
78
  describe('when `options.targetBranches` is not empty', () => {
78
79
  let branches;
79
- beforeEach(() => {
80
- branches = (0, getTargetBranches_1.getTargetBranches)({
80
+ beforeEach(async () => {
81
+ jest
82
+ .spyOn(validateTargetBranches, 'validateTargetBranches')
83
+ .mockResolvedValueOnce();
84
+ branches = await (0, getTargetBranches_1.getTargetBranches)({
81
85
  targetBranches: ['branchA', 'branchB'],
82
86
  targetBranchChoices: [],
83
87
  multipleBranches: false,
@@ -91,16 +95,16 @@ describe('getTargetBranches', () => {
91
95
  });
92
96
  });
93
97
  describe('when interactive=false', () => {
94
- it('should throw when there are no missing backports', () => {
98
+ it('should throw when there are no missing backports', async () => {
95
99
  const commits = [];
96
- expect(() => {
100
+ await expect(() => {
97
101
  return (0, getTargetBranches_1.getTargetBranches)({
98
102
  expectedTargetPullRequests: [],
99
103
  interactive: false,
100
104
  }, commits);
101
- }).toThrow('There are no branches to backport to. Aborting.');
105
+ }).rejects.toThrowError('There are no branches to backport to. Aborting.');
102
106
  });
103
- it('should return missing backports', () => {
107
+ it('should return missing backports', async () => {
104
108
  const commits = [
105
109
  {
106
110
  expectedTargetPullRequests: [
@@ -110,7 +114,7 @@ describe('getTargetBranches', () => {
110
114
  ],
111
115
  },
112
116
  ];
113
- const targetBranches = (0, getTargetBranches_1.getTargetBranches)({ interactive: false }, commits);
117
+ const targetBranches = await (0, getTargetBranches_1.getTargetBranches)({ interactive: false }, commits);
114
118
  expect(targetBranches).toEqual(['7.x']);
115
119
  });
116
120
  });
@@ -24,7 +24,7 @@ async function addLabelsToPullRequest({ githubApiBaseUrlV3, repoName, repoOwner,
24
24
  }
25
25
  catch (e) {
26
26
  spinner.fail();
27
- logger_1.logger.info(`Could not add labels to PR ${pullNumber}`, e);
27
+ logger_1.logger.error(`Could not add labels to PR ${pullNumber}`, e);
28
28
  }
29
29
  }
30
30
  exports.addLabelsToPullRequest = addLabelsToPullRequest;
@@ -26,7 +26,7 @@ async function addReviewersToPullRequest({ githubApiBaseUrlV3, repoName, repoOwn
26
26
  //@ts-expect-error
27
27
  const message = e.response?.data?.message;
28
28
  spinner.fail(`Adding reviewers. ${message ? message : ''}`);
29
- logger_1.logger.info(`Could not add reviewers to PR ${pullNumber}`, e);
29
+ logger_1.logger.error(`Could not add reviewers to PR ${pullNumber}`, e);
30
30
  }
31
31
  }
32
32
  exports.addReviewersToPullRequest = addReviewersToPullRequest;
@@ -44,7 +44,7 @@ async function createPullRequest({ options, prPayload, }) {
44
44
  }
45
45
  }
46
46
  catch (e) {
47
- logger_1.logger.info('Could not retrieve existing pull request', e);
47
+ logger_1.logger.error('Could not retrieve existing pull request', e);
48
48
  // swallow error
49
49
  }
50
50
  spinner.fail();
@@ -73,9 +73,9 @@ ${commitMessages}
73
73
  ### Questions ?
74
74
  Please refer to the [Backport tool documentation](https://github.com/sqren/backport)`;
75
75
  return (options.prDescription ?? defaultPrDescription)
76
- .replace('{targetBranch}', targetBranch)
77
- .replace('{commitMessages}', commitMessages)
78
- .replace('{defaultPrDescription}', defaultPrDescription);
76
+ .replaceAll('{targetBranch}', targetBranch)
77
+ .replaceAll('{commitMessages}', commitMessages)
78
+ .replaceAll('{defaultPrDescription}', defaultPrDescription);
79
79
  }
80
80
  exports.getPullRequestBody = getPullRequestBody;
81
81
  function getTitle({ options, commits, targetBranch, }) {
@@ -84,8 +84,8 @@ function getTitle({ options, commits, targetBranch, }) {
84
84
  .join(' | ');
85
85
  const defaultPrTitle = '[{targetBranch}] {commitMessages}';
86
86
  return (options.prTitle ?? defaultPrTitle)
87
- .replace('{targetBranch}', targetBranch)
88
- .replace('{commitMessages}', commitMessages)
87
+ .replaceAll('{targetBranch}', targetBranch)
88
+ .replaceAll('{commitMessages}', commitMessages)
89
89
  .slice(0, 240);
90
90
  }
91
91
  exports.getTitle = getTitle;
@@ -3,7 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getCommentBody = exports.createStatusComment = void 0;
4
4
  const rest_1 = require("@octokit/rest");
5
5
  const packageVersion_1 = require("../../../utils/packageVersion");
6
- const redact_1 = require("../../../utils/redact");
7
6
  const BackportError_1 = require("../../BackportError");
8
7
  const logger_1 = require("../../logger");
9
8
  const commitFormatters_1 = require("../commitFormatters");
@@ -33,12 +32,12 @@ async function createStatusComment({ options, backportResponse, }) {
33
32
  owner: repoOwner,
34
33
  repo: repoName,
35
34
  issue_number: commit.sourcePullRequest.number,
36
- body: (0, redact_1.redact)(options.accessToken, body),
35
+ body: (0, logger_1.redactAccessToken)(body),
37
36
  });
38
37
  }));
39
38
  }
40
39
  catch (e) {
41
- logger_1.logger.info(`Could not create status comment `, e);
40
+ logger_1.logger.error(`Could not create status comment `, e);
42
41
  }
43
42
  }
44
43
  exports.createStatusComment = createStatusComment;
@@ -107,7 +106,10 @@ ${manualBackportCommand}${questionsAndLinkToBackport}${packageVersionSection}`;
107
106
  `**Backport failed because of merge conflicts**${unmergedBackportsSection}`,
108
107
  ];
109
108
  }
110
- return ['❌', result.targetBranch, result.error.message];
109
+ const message = result.status === 'handled-error'
110
+ ? result.error.message
111
+ : 'An unhandled error occurred. Please see the logs for details';
112
+ return ['❌', result.targetBranch, message];
111
113
  })
112
114
  .map((line) => line.join('|'))
113
115
  .join('|\n|');
@@ -5,10 +5,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const nock_1 = __importDefault(require("nock"));
7
7
  const BackportError_1 = require("../../BackportError");
8
+ const logger_1 = require("../../logger");
8
9
  const createStatusComment_1 = require("./createStatusComment");
10
+ jest.unmock('../../logger');
9
11
  describe('createStatusComment', () => {
10
12
  it('redacts accessToken if it is included in the error message', async () => {
11
13
  const accessToken = 'ghp_abcdefg';
14
+ (0, logger_1.setAccessToken)(accessToken);
12
15
  const scope = (0, nock_1.default)('https://api.github.com')
13
16
  .post('/repos/elastic/kibana/issues/100/comments')
14
17
  .reply(200, 'some response');
@@ -158,8 +161,8 @@ describe('getCommentBody', () => {
158
161
 
159
162
  | Status | Branch | Result |
160
163
  |:------:|:------:|:------|
161
- |❌|7.x|My boom error!|
162
- |❌|7.1|My boom error!|
164
+ |❌|7.x|An unhandled error occurred. Please see the logs for details|
165
+ |❌|7.1|An unhandled error occurred. Please see the logs for details|
163
166
 
164
167
  ### Manual backport
165
168
  To create the backport manually run:
@@ -213,7 +216,7 @@ describe('getCommentBody', () => {
213
216
  | Status | Branch | Result |
214
217
  |:------:|:------:|:------|
215
218
  |✅|7.x|[<img src=\\"https://img.shields.io/github/pulls/detail/state/elastic/kibana/55\\">](url-to-pr-55)|
216
- |❌|7.1|My boom error!|
219
+ |❌|7.1|An unhandled error occurred. Please see the logs for details|
217
220
 
218
221
  Note: Successful backport PRs will be merged automatically after passing CI.
219
222
 
@@ -450,6 +453,108 @@ describe('getCommentBody', () => {
450
453
  ### Questions ?
451
454
  Please refer to the [Backport tool documentation](https://github.com/sqren/backport)
452
455
 
456
+ <!--- Backport version: 1.2.3-mocked -->"
457
+ `);
458
+ });
459
+ it('does not post a comment when `publishStatusCommentOnFailure = false`', () => {
460
+ const params = getParams({ publishStatusCommentOnFailure: false });
461
+ expect((0, createStatusComment_1.getCommentBody)(params)).toBe(undefined);
462
+ });
463
+ });
464
+ describe("when target branch doesn't exist", () => {
465
+ const getParams = (opts) => ({
466
+ options: {
467
+ interactive: true,
468
+ repoName: 'kibana',
469
+ repoOwner: 'elastic',
470
+ autoMerge: true,
471
+ backportBinary: 'node scripts/backport',
472
+ ...opts,
473
+ },
474
+ pullNumber: 55,
475
+ backportResponse: {
476
+ status: 'success',
477
+ commits: [],
478
+ results: [
479
+ {
480
+ targetBranch: 'main',
481
+ status: 'handled-error',
482
+ error: new BackportError_1.BackportError('The branch "main" is invalid or doesn\'t exist'),
483
+ },
484
+ ],
485
+ },
486
+ });
487
+ it('posts a comment when `publishStatusCommentOnFailure = true`', () => {
488
+ const params = getParams({
489
+ publishStatusCommentOnFailure: true,
490
+ });
491
+ expect((0, createStatusComment_1.getCommentBody)(params)).toMatchInlineSnapshot(`
492
+ "## 💔 All backports failed
493
+
494
+ | Status | Branch | Result |
495
+ |:------:|:------:|:------|
496
+ |❌|main|The branch \\"main\\" is invalid or doesn't exist|
497
+
498
+ ### Manual backport
499
+ To create the backport manually run:
500
+ \`\`\`
501
+ node scripts/backport --pr 55
502
+ \`\`\`
503
+
504
+ ### Questions ?
505
+ Please refer to the [Backport tool documentation](https://github.com/sqren/backport)
506
+
507
+ <!--- Backport version: 1.2.3-mocked -->"
508
+ `);
509
+ });
510
+ it('does not post a comment when `publishStatusCommentOnFailure = false`', () => {
511
+ const params = getParams({ publishStatusCommentOnFailure: false });
512
+ expect((0, createStatusComment_1.getCommentBody)(params)).toBe(undefined);
513
+ });
514
+ });
515
+ describe('when target branch is invalid', () => {
516
+ const getParams = (opts) => ({
517
+ options: {
518
+ interactive: true,
519
+ repoName: 'kibana',
520
+ repoOwner: 'elastic',
521
+ autoMerge: true,
522
+ backportBinary: 'node scripts/backport',
523
+ ...opts,
524
+ },
525
+ pullNumber: 55,
526
+ backportResponse: {
527
+ status: 'success',
528
+ commits: [],
529
+ results: [
530
+ {
531
+ targetBranch: '--foo',
532
+ status: 'unhandled-error',
533
+ error: new BackportError_1.BackportError('The branch "--foo" does not exist'),
534
+ },
535
+ ],
536
+ },
537
+ });
538
+ it('posts a comment when `publishStatusCommentOnFailure = true`', () => {
539
+ const params = getParams({
540
+ publishStatusCommentOnFailure: true,
541
+ });
542
+ expect((0, createStatusComment_1.getCommentBody)(params)).toMatchInlineSnapshot(`
543
+ "## 💔 All backports failed
544
+
545
+ | Status | Branch | Result |
546
+ |:------:|:------:|:------|
547
+ |❌|--foo|An unhandled error occurred. Please see the logs for details|
548
+
549
+ ### Manual backport
550
+ To create the backport manually run:
551
+ \`\`\`
552
+ node scripts/backport --pr 55
553
+ \`\`\`
554
+
555
+ ### Questions ?
556
+ Please refer to the [Backport tool documentation](https://github.com/sqren/backport)
557
+
453
558
  <!--- Backport version: 1.2.3-mocked -->"
454
559
  `);
455
560
  });
@@ -34,6 +34,7 @@ async function apiRequestV4({ githubApiBaseUrlV4 = 'https://api.github.com/graph
34
34
  query,
35
35
  variables,
36
36
  githubResponse: e.response,
37
+ didThrow: true,
37
38
  });
38
39
  throw new GithubV4Exception(e.response, e.message);
39
40
  }
@@ -41,14 +42,13 @@ async function apiRequestV4({ githubApiBaseUrlV4 = 'https://api.github.com/graph
41
42
  }
42
43
  }
43
44
  exports.apiRequestV4 = apiRequestV4;
44
- function addDebugLogs({ githubApiBaseUrlV4, query, variables, githubResponse, }) {
45
+ function addDebugLogs({ githubApiBaseUrlV4, query, variables, githubResponse, didThrow = false, }) {
45
46
  const gqlQueryName = getQueryName(query);
46
- logger_1.logger.info(`POST ${githubApiBaseUrlV4} (name:${gqlQueryName}, status: ${githubResponse.status})`);
47
- logger_1.logger.info(`Query name ${gqlQueryName}`);
48
- logger_1.logger.info(`Query: ${query}`);
49
- logger_1.logger.info('Variables:', variables);
50
- logger_1.logger.info('Response headers:', githubResponse.headers);
51
- logger_1.logger.info('Response data:', githubResponse.data);
47
+ logger_1.logger.info(`POST ${githubApiBaseUrlV4} (name:${gqlQueryName}, status: ${githubResponse.status}${didThrow ? ', EXCEPTION THROWN' : ''})`);
48
+ logger_1.logger.verbose(`Query: ${query}`);
49
+ logger_1.logger.verbose('Variables:', variables);
50
+ logger_1.logger.verbose('Response headers:', githubResponse.headers);
51
+ logger_1.logger.verbose('Response data:', githubResponse.data);
52
52
  }
53
53
  class GithubV4Exception extends Error {
54
54
  constructor(githubResponse, errorMessage) {
@@ -0,0 +1,14 @@
1
+ export interface TargetBranchResponse {
2
+ repository: {
3
+ ref: {
4
+ id: string;
5
+ } | null;
6
+ };
7
+ }
8
+ export declare function validateTargetBranches({ accessToken, repoName, repoOwner, targetBranches, githubApiBaseUrlV4, }: {
9
+ accessToken: string;
10
+ repoOwner: string;
11
+ repoName: string;
12
+ targetBranches?: string[];
13
+ githubApiBaseUrlV4?: string;
14
+ }): Promise<void>;
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.validateTargetBranches = void 0;
7
+ const graphql_tag_1 = __importDefault(require("graphql-tag"));
8
+ const BackportError_1 = require("../../BackportError");
9
+ const apiRequestV4_1 = require("./apiRequestV4");
10
+ async function fetchTargetBranch({ accessToken, repoName, repoOwner, branchName, githubApiBaseUrlV4 = 'https://api.github.com/graphql', }) {
11
+ const query = (0, graphql_tag_1.default) `
12
+ query doesBranchExist(
13
+ $repoOwner: String!
14
+ $repoName: String!
15
+ $branchName: String!
16
+ ) {
17
+ repository(owner: $repoOwner, name: $repoName) {
18
+ ref(qualifiedName: $branchName) {
19
+ id
20
+ }
21
+ }
22
+ }
23
+ `;
24
+ const res = await (0, apiRequestV4_1.apiRequestV4)({
25
+ githubApiBaseUrlV4,
26
+ accessToken,
27
+ query,
28
+ variables: { repoOwner, repoName, branchName },
29
+ });
30
+ if (!res.repository.ref) {
31
+ throw new BackportError_1.BackportError(`The branch "${branchName}" does not exist`);
32
+ }
33
+ return res.repository.ref;
34
+ }
35
+ async function validateTargetBranches({ accessToken, repoName, repoOwner, targetBranches = [], githubApiBaseUrlV4, }) {
36
+ await Promise.all(targetBranches.map((targetBranch) => {
37
+ return fetchTargetBranch({
38
+ accessToken,
39
+ repoName,
40
+ repoOwner,
41
+ branchName: targetBranch,
42
+ githubApiBaseUrlV4,
43
+ });
44
+ }));
45
+ }
46
+ exports.validateTargetBranches = validateTargetBranches;
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const getDevAccessToken_1 = require("../../../test/private/getDevAccessToken");
4
+ const validateTargetBranches_1 = require("./validateTargetBranches");
5
+ const accessToken = (0, getDevAccessToken_1.getDevAccessToken)();
6
+ describe('validateTargetBranches', () => {
7
+ describe('no branches', () => {
8
+ it('resolves', async () => {
9
+ const options = {
10
+ repoOwner: 'backport-org',
11
+ repoName: 'repo-with-target-branches',
12
+ accessToken,
13
+ targetBranches: [],
14
+ };
15
+ expect(await (0, validateTargetBranches_1.validateTargetBranches)(options)).toEqual(undefined);
16
+ });
17
+ });
18
+ describe('one invalid and one valid branch', () => {
19
+ it('throws', async () => {
20
+ const options = {
21
+ repoOwner: 'backport-org',
22
+ repoName: 'repo-with-target-branches',
23
+ accessToken,
24
+ targetBranches: ['production', 'foo'],
25
+ };
26
+ await expect(() => (0, validateTargetBranches_1.validateTargetBranches)(options)).rejects.toThrowError('The branch "foo" does not exist');
27
+ });
28
+ });
29
+ describe('two valid branches', () => {
30
+ it('resolves', async () => {
31
+ const options = {
32
+ repoOwner: 'backport-org',
33
+ repoName: 'repo-with-target-branches',
34
+ accessToken,
35
+ targetBranches: ['production', 'staging'],
36
+ };
37
+ expect(await (0, validateTargetBranches_1.validateTargetBranches)(options)).toEqual(undefined);
38
+ });
39
+ });
40
+ describe('two invalid branches', () => {
41
+ it('throws', async () => {
42
+ const options = {
43
+ repoOwner: 'backport-org',
44
+ repoName: 'repo-with-target-branches',
45
+ accessToken,
46
+ targetBranches: ['foo', 'bar'],
47
+ };
48
+ await expect(() => (0, validateTargetBranches_1.validateTargetBranches)(options)).rejects.toThrow(/The branch "(foo|bar)" does not exist/);
49
+ });
50
+ });
51
+ });
@@ -7,3 +7,5 @@ export declare function initLogger({ interactive, accessToken, logFilePath, }: {
7
7
  }): winston.Logger;
8
8
  export declare function consoleLog(message: string): void;
9
9
  export declare function setAccessToken(accessToken: string): void;
10
+ export declare function redactAccessToken(str: string): string;
11
+ export declare type LogLevel = 'error' | 'warn' | 'info' | 'verbose' | 'debug';