backport 8.4.1 → 8.4.4

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 (30) hide show
  1. package/dist/lib/author.d.ts +13 -0
  2. package/dist/lib/author.js +28 -0
  3. package/dist/lib/cherrypickAndCreateTargetPullRequest.js +26 -21
  4. package/dist/lib/cherrypickAndCreateTargetPullRequest.test.js +2 -0
  5. package/dist/lib/child-process-promisified.d.ts +1 -1
  6. package/dist/lib/child-process-promisified.js +14 -3
  7. package/dist/lib/git.d.ts +10 -7
  8. package/dist/lib/git.js +28 -6
  9. package/dist/lib/git.private.test.js +24 -4
  10. package/dist/lib/git.test.js +47 -9
  11. package/dist/lib/github/v4/apiRequestV4.js +14 -8
  12. package/dist/lib/setupRepo.test.js +5 -5
  13. package/dist/test/e2e/cli/different-merge-strategies.private.test.js +14 -14
  14. package/dist/test/e2e/cli/error-handling-interactive-mode.private.test.js +25 -12
  15. package/dist/test/e2e/cli/gracefully-handles-corrupt-repo.private.test.d.ts +1 -0
  16. package/dist/test/e2e/cli/gracefully-handles-corrupt-repo.private.test.js +52 -0
  17. package/dist/test/e2e/cli/repo-with-programatically-added-commits.mutation.test.d.ts +1 -0
  18. package/dist/test/e2e/cli/repo-with-programatically-added-commits.mutation.test.js +114 -0
  19. package/dist/test/e2e/cli/runBackportViaCli.js +2 -2
  20. package/dist/test/e2e/cli/test-that-repo-can-be-cloned.private.test.js +6 -1
  21. package/dist/test/replaceStringAndLinebreaks.d.ts +5 -0
  22. package/dist/test/replaceStringAndLinebreaks.js +8 -0
  23. package/dist/test/sandbox.d.ts +1 -0
  24. package/dist/test/sandbox.js +8 -3
  25. package/dist/utils/packageVersion.d.ts +1 -1
  26. package/dist/utils/packageVersion.js +1 -1
  27. package/package.json +20 -20
  28. package/yarn.lock +853 -955
  29. package/dist/lib/getGitConfigAuthor.d.ts +0 -6
  30. package/dist/lib/getGitConfigAuthor.js +0 -15
@@ -0,0 +1,13 @@
1
+ import { Commit } from '../entrypoint.module';
2
+ import { ValidConfigOptions } from '../options/options';
3
+ export declare type GitConfigAuthor = {
4
+ name?: string;
5
+ email?: string;
6
+ };
7
+ export declare function getGitConfigAuthor(options: ValidConfigOptions): Promise<GitConfigAuthor | undefined>;
8
+ export declare type CommitAuthor = Required<GitConfigAuthor>;
9
+ export declare function getCommitAuthor({ options, commit, gitConfigAuthor, }: {
10
+ options: ValidConfigOptions;
11
+ commit: Commit;
12
+ gitConfigAuthor?: GitConfigAuthor;
13
+ }): CommitAuthor;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getCommitAuthor = exports.getGitConfigAuthor = void 0;
4
+ const git_1 = require("./git");
5
+ async function getGitConfigAuthor(options) {
6
+ const localRepoPath = await (0, git_1.getLocalSourceRepoPath)(options);
7
+ if (!localRepoPath) {
8
+ return;
9
+ }
10
+ return {
11
+ name: await (0, git_1.getGitConfig)({ dir: localRepoPath, key: 'user.name' }),
12
+ email: await (0, git_1.getGitConfig)({ dir: localRepoPath, key: 'user.email' }),
13
+ };
14
+ }
15
+ exports.getGitConfigAuthor = getGitConfigAuthor;
16
+ function getCommitAuthor({ options, commit, gitConfigAuthor, }) {
17
+ if (options.resetAuthor) {
18
+ return {
19
+ name: options.authenticatedUsername,
20
+ email: `<${options.authenticatedUsername}@users.noreply.github.com>`,
21
+ };
22
+ }
23
+ return {
24
+ name: options.gitAuthorName ?? gitConfigAuthor?.name ?? commit.author.name,
25
+ email: options.gitAuthorEmail ?? gitConfigAuthor?.email ?? commit.author.email,
26
+ };
27
+ }
28
+ exports.getCommitAuthor = getCommitAuthor;
@@ -7,10 +7,10 @@ exports.cherrypickAndCreateTargetPullRequest = void 0;
7
7
  const chalk_1 = __importDefault(require("chalk"));
8
8
  const lodash_1 = require("lodash");
9
9
  const BackportError_1 = require("./BackportError");
10
+ const author_1 = require("./author");
10
11
  const child_process_promisified_1 = require("./child-process-promisified");
11
12
  const env_1 = require("./env");
12
13
  const getCommitsWithoutBackports_1 = require("./getCommitsWithoutBackports");
13
- const getGitConfigAuthor_1 = require("./getGitConfigAuthor");
14
14
  const git_1 = require("./git");
15
15
  const commitFormatters_1 = require("./github/commitFormatters");
16
16
  const addAssigneesToPullRequest_1 = require("./github/v3/addAssigneesToPullRequest");
@@ -23,13 +23,25 @@ const logger_1 = require("./logger");
23
23
  const ora_1 = require("./ora");
24
24
  const prompts_1 = require("./prompts");
25
25
  const sequentially_1 = require("./sequentially");
26
+ function getSourceBranchFromCommits(commits) {
27
+ // sourceBranch should be the same for all commits, so picking `sourceBranch` from the first commit should be fine 🤞
28
+ // this is specifically needed when backporting a PR like `backport --pr 123` and the source PR was merged to a non-default (aka non-master) branch.
29
+ const { sourceBranch } = commits[0];
30
+ return sourceBranch;
31
+ }
26
32
  async function cherrypickAndCreateTargetPullRequest({ options, commits, targetBranch, }) {
27
33
  const backportBranch = getBackportBranchName(targetBranch, commits);
28
34
  const repoForkOwner = (0, git_1.getRepoForkOwner)(options);
29
35
  (0, logger_1.consoleLog)(`\n${chalk_1.default.bold(`Backporting to ${targetBranch}:`)}`);
36
+ const sourceBranch = getSourceBranchFromCommits(commits);
30
37
  const [gitConfigAuthor] = await Promise.all([
31
- (0, getGitConfigAuthor_1.getGitConfigAuthor)(options),
32
- (0, git_1.createBackportBranch)({ options, targetBranch, backportBranch }),
38
+ (0, author_1.getGitConfigAuthor)(options),
39
+ (0, git_1.createBackportBranch)({
40
+ options,
41
+ sourceBranch,
42
+ targetBranch,
43
+ backportBranch,
44
+ }),
33
45
  ]);
34
46
  const commitsFlattened = (0, lodash_1.flatten)(await Promise.all(commits.map((c) => getMergeCommits(options, c))));
35
47
  await (0, sequentially_1.sequentially)(commitsFlattened, (commit) => waitForCherrypick(options, commit, targetBranch, gitConfigAuthor));
@@ -111,12 +123,18 @@ function getBackportBranchName(targetBranch, commits) {
111
123
  async function waitForCherrypick(options, commit, targetBranch, gitConfigAuthor) {
112
124
  const spinnerText = `Cherry-picking: ${chalk_1.default.greenBright((0, commitFormatters_1.getFirstLine)(commit.sourceCommit.message))}`;
113
125
  const cherrypickSpinner = (0, ora_1.ora)(options.interactive, spinnerText).start();
114
- await (0, git_1.fetchBranch)(options, commit.sourceBranch);
115
- await cherrypickAndHandleConflicts(options, commit, targetBranch, cherrypickSpinner, gitConfigAuthor);
126
+ const commitAuthor = (0, author_1.getCommitAuthor)({ options, commit, gitConfigAuthor });
127
+ await cherrypickAndHandleConflicts({
128
+ options,
129
+ commit,
130
+ commitAuthor,
131
+ targetBranch,
132
+ cherrypickSpinner,
133
+ });
116
134
  // Conflicts should be resolved and files staged at this point
117
135
  try {
118
- // Run `git commit`
119
- await (0, git_1.commitChanges)(commit, options);
136
+ // Run `git commit` in case conflicts were not manually committed
137
+ await (0, git_1.commitChanges)({ options, commit, commitAuthor });
120
138
  cherrypickSpinner.succeed();
121
139
  }
122
140
  catch (e) {
@@ -124,9 +142,8 @@ async function waitForCherrypick(options, commit, targetBranch, gitConfigAuthor)
124
142
  throw e;
125
143
  }
126
144
  }
127
- async function cherrypickAndHandleConflicts(options, commit, targetBranch, cherrypickSpinner, gitConfigAuthor) {
145
+ async function cherrypickAndHandleConflicts({ options, commit, commitAuthor, targetBranch, cherrypickSpinner, }) {
128
146
  const mergedTargetPullRequest = commit.expectedTargetPullRequests.find((pr) => pr.state === 'MERGED' && pr.branch === targetBranch);
129
- const commitAuthor = getCommitAuthor({ options, gitConfigAuthor, commit });
130
147
  let conflictingFiles;
131
148
  let unstagedFiles;
132
149
  let needsResolving;
@@ -238,15 +255,3 @@ async function listConflictingAndUnstagedFiles({ retries, options, conflictingFi
238
255
  unstagedFiles: _unstagedFiles,
239
256
  });
240
257
  }
241
- function getCommitAuthor({ options, gitConfigAuthor, commit, }) {
242
- if (options.resetAuthor) {
243
- return {
244
- name: options.authenticatedUsername,
245
- email: `<${options.authenticatedUsername}@users.noreply.github.com>`,
246
- };
247
- }
248
- return {
249
- name: options.gitAuthorName ?? gitConfigAuthor?.name ?? commit.author.name,
250
- email: options.gitAuthorEmail ?? gitConfigAuthor?.email ?? commit.author.email,
251
- };
252
- }
@@ -63,6 +63,8 @@ describe('cherrypickAndCreateTargetPullRequest', () => {
63
63
  const options = {
64
64
  assignees: [],
65
65
  authenticatedUsername: 'sqren_authenticated',
66
+ gitAuthorName: 'Soren L',
67
+ gitAuthorEmail: 'soren@louv.dk',
66
68
  author: 'sqren',
67
69
  fork: true,
68
70
  interactive: true,
@@ -12,7 +12,7 @@ export declare function spawnPromise(cmd: string, cmdArgs: string[], cwd: string
12
12
  stderr: string;
13
13
  stdout: string;
14
14
  }>;
15
- export declare const spawnOriginal: typeof childProcess.spawn;
15
+ export declare const spawnStream: (cmd: string, cmdArgs: ReadonlyArray<string>) => childProcess.ChildProcessWithoutNullStreams;
16
16
  export declare type SpawnErrorContext = {
17
17
  cmdArgs: string[];
18
18
  code: number;
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.SpawnError = exports.spawnOriginal = exports.spawnPromise = exports.exec = void 0;
6
+ exports.SpawnError = exports.spawnStream = exports.spawnPromise = exports.exec = void 0;
7
7
  const child_process_1 = __importDefault(require("child_process"));
8
8
  const util_1 = require("util");
9
9
  const logger_1 = require("./logger");
@@ -12,6 +12,8 @@ async function exec(cmd, options) {
12
12
  const res = await execPromisified(cmd, {
13
13
  maxBuffer: 100 * 1024 * 1024,
14
14
  ...options,
15
+ // ensure that git commands return english error messages
16
+ env: { ...process.env, LANG: 'en_US' },
15
17
  });
16
18
  return res;
17
19
  }
@@ -20,7 +22,11 @@ async function spawnPromise(cmd, cmdArgs, cwd) {
20
22
  const fullCmd = `${cmd} ${cmdArgs.join(' ')}`;
21
23
  logger_1.logger.info(`Running command: "${fullCmd}"`);
22
24
  return new Promise(function (resolve, reject) {
23
- const subprocess = child_process_1.default.spawn(cmd, cmdArgs, { cwd });
25
+ const subprocess = child_process_1.default.spawn(cmd, cmdArgs, {
26
+ cwd,
27
+ // ensure that git commands return english error messages
28
+ env: { ...process.env, LANG: 'en_US' },
29
+ });
24
30
  let stderr = '';
25
31
  let stdout = '';
26
32
  subprocess.stdout.on('data', (data) => {
@@ -45,7 +51,12 @@ async function spawnPromise(cmd, cmdArgs, cwd) {
45
51
  });
46
52
  }
47
53
  exports.spawnPromise = spawnPromise;
48
- exports.spawnOriginal = child_process_1.default.spawn;
54
+ const spawnStream = (cmd, cmdArgs) => {
55
+ return child_process_1.default.spawn(cmd, cmdArgs, {
56
+ env: { ...process.env, LANG: 'en_US' },
57
+ });
58
+ };
59
+ exports.spawnStream = spawnStream;
49
60
  class SpawnError extends Error {
50
61
  constructor(context) {
51
62
  const cmdArgs = context.cmdArgs.join(' ');
package/dist/lib/git.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { ValidConfigOptions } from '../options/options';
2
+ import { CommitAuthor } from './author';
2
3
  import { ExpectedTargetPullRequest } from './sourceCommit/getExpectedTargetPullRequests';
3
4
  import { Commit } from './sourceCommit/parseSourceCommit';
4
5
  export declare function getRemoteUrl({ repoName, accessToken, gitHostname }: ValidConfigOptions, repoOwner: string): string;
@@ -32,10 +33,7 @@ export declare function cherrypick({ options, sha, mergedTargetPullRequest, comm
32
33
  options: ValidConfigOptions;
33
34
  sha: string;
34
35
  mergedTargetPullRequest?: ExpectedTargetPullRequest;
35
- commitAuthor: {
36
- name: string;
37
- email: string;
38
- };
36
+ commitAuthor: CommitAuthor;
39
37
  }): Promise<{
40
38
  conflictingFiles: {
41
39
  absolute: string;
@@ -44,7 +42,11 @@ export declare function cherrypick({ options, sha, mergedTargetPullRequest, comm
44
42
  unstagedFiles: string[];
45
43
  needsResolving: boolean;
46
44
  }>;
47
- export declare function commitChanges(commit: Commit, options: ValidConfigOptions): Promise<void>;
45
+ export declare function commitChanges({ options, commit, commitAuthor, }: {
46
+ options: ValidConfigOptions;
47
+ commit: Commit;
48
+ commitAuthor: CommitAuthor;
49
+ }): Promise<void>;
48
50
  export declare type ConflictingFiles = Awaited<ReturnType<typeof getConflictingFiles>>;
49
51
  export declare function getConflictingFiles(options: ValidConfigOptions): Promise<{
50
52
  absolute: string;
@@ -55,10 +57,11 @@ export declare function getGitConfig({ dir, key, }: {
55
57
  dir: string;
56
58
  key: 'user.name' | 'user.email';
57
59
  }): Promise<string | undefined>;
58
- export declare function createBackportBranch({ options, targetBranch, backportBranch, }: {
60
+ export declare function createBackportBranch({ options, sourceBranch, backportBranch, targetBranch, }: {
59
61
  options: ValidConfigOptions;
60
- targetBranch: string;
62
+ sourceBranch: string;
61
63
  backportBranch: string;
64
+ targetBranch: string;
62
65
  }): Promise<void>;
63
66
  export declare function deleteBackportBranch({ options, backportBranch, }: {
64
67
  options: ValidConfigOptions;
package/dist/lib/git.js CHANGED
@@ -17,7 +17,7 @@ exports.getRemoteUrl = getRemoteUrl;
17
17
  async function cloneRepo({ sourcePath, targetPath }, onProgress) {
18
18
  logger_1.logger.info(`Cloning repo from ${sourcePath} to ${targetPath}`);
19
19
  return new Promise((resolve, reject) => {
20
- const subprocess = (0, child_process_promisified_1.spawnOriginal)('git', [
20
+ const subprocess = (0, child_process_promisified_1.spawnStream)('git', [
21
21
  'clone',
22
22
  sourcePath,
23
23
  targetPath,
@@ -198,9 +198,9 @@ async function getShasInMergeCommit(options, sha) {
198
198
  exports.getShasInMergeCommit = getShasInMergeCommit;
199
199
  async function cherrypick({ options, sha, mergedTargetPullRequest, commitAuthor, }) {
200
200
  const cmdArgs = [
201
- '-c',
201
+ `-c`,
202
202
  `user.name="${commitAuthor.name}"`,
203
- '-c',
203
+ `-c`,
204
204
  `user.email="${commitAuthor.email}"`,
205
205
  `cherry-pick`,
206
206
  ...(options.mainline != undefined
@@ -247,11 +247,15 @@ async function cherrypick({ options, sha, mergedTargetPullRequest, commitAuthor,
247
247
  }
248
248
  }
249
249
  exports.cherrypick = cherrypick;
250
- async function commitChanges(commit, options) {
250
+ async function commitChanges({ options, commit, commitAuthor, }) {
251
251
  const noVerifyFlag = options.noVerify ? ['--no-verify'] : [];
252
252
  const cwd = (0, env_1.getRepoPath)(options);
253
253
  try {
254
254
  await (0, child_process_promisified_1.spawnPromise)('git', [
255
+ `-c`,
256
+ `user.name="${commitAuthor.name}"`,
257
+ `-c`,
258
+ `user.email="${commitAuthor.email}"`,
255
259
  'commit',
256
260
  '--no-edit',
257
261
  ...noVerifyFlag, // bypass pre-commit and commit-msg hooks
@@ -268,6 +272,10 @@ async function commitChanges(commit, options) {
268
272
  // this can happen if the user runs `git reset HEAD` and thereby aborts the cherrypick process
269
273
  if (e.context.stderr.includes('Aborting commit due to empty commit message')) {
270
274
  await (0, child_process_promisified_1.spawnPromise)('git', [
275
+ `-c`,
276
+ `user.name="${commitAuthor.name}"`,
277
+ `-c`,
278
+ `user.email="${commitAuthor.email}"`,
271
279
  'commit',
272
280
  `--message=${commit.sourceCommit.message}`,
273
281
  ...noVerifyFlag, // bypass pre-commit and commit-msg hooks
@@ -338,13 +346,18 @@ exports.getGitConfig = getGitConfig;
338
346
  // How the commit flows:
339
347
  // ${sourceBranch} -> ${backportBranch} -> ${targetBranch}
340
348
  // master -> backport/7.x/pr-1234 -> 7.x
341
- async function createBackportBranch({ options, targetBranch, backportBranch, }) {
349
+ async function createBackportBranch({ options, sourceBranch, backportBranch, targetBranch, }) {
342
350
  const spinner = (0, ora_1.ora)(options.interactive, 'Pulling latest changes').start();
343
351
  try {
344
352
  const cwd = (0, env_1.getRepoPath)(options);
345
353
  await (0, child_process_promisified_1.spawnPromise)('git', ['reset', '--hard'], cwd);
346
354
  await (0, child_process_promisified_1.spawnPromise)('git', ['clean', '-d', '--force'], cwd);
347
- await (0, child_process_promisified_1.spawnPromise)('git', ['fetch', options.repoOwner, targetBranch], cwd);
355
+ // create tmp branch. This can be necessary when fetching to the currently selected branch
356
+ const tmpBranchName = '__backport_tool_tmp';
357
+ await (0, child_process_promisified_1.spawnPromise)('git', ['checkout', '-B', tmpBranchName], cwd);
358
+ // fetch target branch
359
+ await fetchBranch(options, targetBranch);
360
+ // checkout backport branch and point it to target branch
348
361
  await (0, child_process_promisified_1.spawnPromise)('git', [
349
362
  'checkout',
350
363
  '-B',
@@ -352,6 +365,15 @@ async function createBackportBranch({ options, targetBranch, backportBranch, })
352
365
  `${options.repoOwner}/${targetBranch}`,
353
366
  '--no-track',
354
367
  ], cwd);
368
+ // delete tmp branch (if it still exists)
369
+ try {
370
+ await (0, child_process_promisified_1.spawnPromise)('git', ['branch', '-D', tmpBranchName], cwd);
371
+ }
372
+ catch (e) {
373
+ //
374
+ }
375
+ // fetch commits for source branch
376
+ await fetchBranch(options, sourceBranch);
355
377
  spinner.succeed();
356
378
  }
357
379
  catch (e) {
@@ -39,7 +39,7 @@ jest.unmock('del');
39
39
  jest.unmock('make-dir');
40
40
  const commitAuthor = { name: 'Soren L', email: 'soren@mail.dk' };
41
41
  const accessToken = (0, getDevAccessToken_1.getDevAccessToken)();
42
- describe('git.integration', () => {
42
+ describe('git.private', () => {
43
43
  describe('getIsCommitInBranch', () => {
44
44
  let firstSha;
45
45
  let secondSha;
@@ -80,6 +80,23 @@ describe('git.integration', () => {
80
80
  expect(isSecondCommitInBranch).toEqual(false);
81
81
  });
82
82
  });
83
+ describe('deleteRemote', () => {
84
+ const cwd = (0, sandbox_1.getSandboxPath)({
85
+ filename: __filename,
86
+ specname: 'deleteRemote',
87
+ });
88
+ it('should handle when deleting a remote that does not exist', async () => {
89
+ const options = {
90
+ repoName: 'kibana',
91
+ repoOwner: 'elastic',
92
+ dir: cwd,
93
+ };
94
+ await (0, sandbox_1.resetSandbox)(cwd);
95
+ await gitInit(cwd);
96
+ const res = await (0, git_1.deleteRemote)(options, 'my-remote-foo');
97
+ expect(res).toBe(undefined);
98
+ });
99
+ });
83
100
  describe('getGitConfig', () => {
84
101
  const cwd = (0, sandbox_1.getSandboxPath)({
85
102
  filename: __filename,
@@ -121,6 +138,7 @@ describe('git.integration', () => {
121
138
  repoOwner: 'origin',
122
139
  dir: cwd,
123
140
  },
141
+ sourceBranch: 'main',
124
142
  targetBranch: '7.x',
125
143
  backportBranch: 'my-backport-branch',
126
144
  });
@@ -133,6 +151,7 @@ describe('git.integration', () => {
133
151
  repoOwner: 'origin',
134
152
  dir: cwd,
135
153
  },
154
+ sourceBranch: 'main',
136
155
  targetBranch: 'foo',
137
156
  backportBranch: 'my-backport-branch',
138
157
  });
@@ -152,6 +171,7 @@ describe('git.integration', () => {
152
171
  repoOwner: 'origin',
153
172
  dir: cwd,
154
173
  },
174
+ sourceBranch: 'main',
155
175
  targetBranch: '7.x',
156
176
  backportBranch: 'my-backport-branch',
157
177
  });
@@ -290,7 +310,7 @@ describe('git.integration', () => {
290
310
  cwd,
291
311
  });
292
312
  expect(async () => {
293
- return await (0, git_1.commitChanges)(commit, options);
313
+ return await (0, git_1.commitChanges)({ commit, commitAuthor, options });
294
314
  }).not.toThrowError();
295
315
  const message = await getMostRecentCommitMessage(cwd);
296
316
  expect(message).toBe('Update my-file-1.txt');
@@ -306,7 +326,7 @@ describe('git.integration', () => {
306
326
  filename: 'my-file-2.txt',
307
327
  cwd,
308
328
  });
309
- await (0, git_1.commitChanges)(commit, options);
329
+ await (0, git_1.commitChanges)({ commit, commitAuthor, options });
310
330
  const message = await getMostRecentCommitMessage(cwd);
311
331
  expect(message).toBe('my fallback commit message');
312
332
  });
@@ -326,7 +346,7 @@ describe('git.integration', () => {
326
346
  }
327
347
  // disregard conflicts and stage all files
328
348
  await childProcess.exec('git add -A', { cwd });
329
- await (0, git_1.commitChanges)(commit, options);
349
+ await (0, git_1.commitChanges)({ commit, commitAuthor, options });
330
350
  const message = await getMostRecentCommitMessage(cwd);
331
351
  expect(message).toMatchInlineSnapshot(`
332
352
  "Add 🇩🇰 (#12)
@@ -238,6 +238,7 @@ describe('createBackportBranch', () => {
238
238
  repoOwner: 'elastic',
239
239
  repoName: 'kibana',
240
240
  };
241
+ const sourceBranch = 'main';
241
242
  const targetBranch = '4.x';
242
243
  const backportBranch = 'backport/4.x/commit-72f94e76';
243
244
  it(`should handle "couldn't find remote ref" error`, async () => {
@@ -249,7 +250,12 @@ describe('createBackportBranch', () => {
249
250
  stderr: "fatal: couldn't find remote ref 4.x\n",
250
251
  });
251
252
  jest.spyOn(childProcess, 'spawnPromise').mockRejectedValueOnce(err);
252
- await expect((0, git_1.createBackportBranch)({ options, targetBranch, backportBranch })).rejects.toThrowErrorMatchingInlineSnapshot(`"The branch \\"4.x\\" is invalid or doesn't exist"`);
253
+ await expect((0, git_1.createBackportBranch)({
254
+ options,
255
+ sourceBranch,
256
+ targetBranch,
257
+ backportBranch,
258
+ })).rejects.toThrowErrorMatchingInlineSnapshot(`"The branch \\"4.x\\" is invalid or doesn't exist"`);
253
259
  });
254
260
  it('should throw "Invalid refspec" error', async () => {
255
261
  expect.assertions(1);
@@ -260,14 +266,24 @@ describe('createBackportBranch', () => {
260
266
  stderr: "fatal: Invalid refspec 'https://github.com/elastic/kibana.git'\n",
261
267
  });
262
268
  jest.spyOn(childProcess, 'spawnPromise').mockRejectedValueOnce(err);
263
- await expect((0, git_1.createBackportBranch)({ options, targetBranch, backportBranch })).rejects.toThrowErrorMatchingInlineSnapshot(`"The branch \\"4.x\\" is invalid or doesn't exist"`);
269
+ await expect((0, git_1.createBackportBranch)({
270
+ options,
271
+ sourceBranch,
272
+ targetBranch,
273
+ backportBranch,
274
+ })).rejects.toThrowErrorMatchingInlineSnapshot(`"The branch \\"4.x\\" is invalid or doesn't exist"`);
264
275
  });
265
276
  it('should rethrow normal error', async () => {
266
277
  expect.assertions(1);
267
278
  const err = new Error('just a normal error');
268
279
  jest.spyOn(childProcess, 'spawnPromise').mockRejectedValueOnce(err);
269
280
  expect.assertions(1);
270
- await expect((0, git_1.createBackportBranch)({ options, targetBranch, backportBranch })).rejects.toThrowErrorMatchingInlineSnapshot(`"just a normal error"`);
281
+ await expect((0, git_1.createBackportBranch)({
282
+ options,
283
+ sourceBranch,
284
+ targetBranch,
285
+ backportBranch,
286
+ })).rejects.toThrowErrorMatchingInlineSnapshot(`"just a normal error"`);
271
287
  });
272
288
  });
273
289
  describe('deleteRemote', () => {
@@ -473,7 +489,7 @@ describe('commitChanges', () => {
473
489
  jest
474
490
  .spyOn(childProcess, 'spawnPromise')
475
491
  .mockResolvedValueOnce({ stderr: '', stdout: '', code: 0, cmdArgs: [] });
476
- await expect(await (0, git_1.commitChanges)(commit, options)).toBe(undefined);
492
+ await expect(await (0, git_1.commitChanges)({ commit, commitAuthor, options })).toBe(undefined);
477
493
  });
478
494
  it('should swallow error if changes have already been committed manaully', async () => {
479
495
  const err = new childProcess.SpawnError({
@@ -483,7 +499,7 @@ describe('commitChanges', () => {
483
499
  stderr: '',
484
500
  });
485
501
  jest.spyOn(childProcess, 'spawnPromise').mockRejectedValueOnce(err);
486
- await expect(await (0, git_1.commitChanges)(commit, options)).toBe(undefined);
502
+ await expect(await (0, git_1.commitChanges)({ commit, commitAuthor, options })).toBe(undefined);
487
503
  });
488
504
  describe('when commit fails due to empty message', () => {
489
505
  let spy;
@@ -504,12 +520,34 @@ describe('commitChanges', () => {
504
520
  code: 0,
505
521
  cmdArgs: [],
506
522
  });
507
- res = await (0, git_1.commitChanges)(commit, options);
523
+ res = await (0, git_1.commitChanges)({ commit, commitAuthor, options });
508
524
  });
509
525
  it('should manually set the commit message', () => {
510
526
  expect(spy).toHaveBeenCalledTimes(2);
511
- expect(spy).toHaveBeenCalledWith('git', ['commit', '--no-edit'], expect.any(String));
512
- expect(spy).toHaveBeenCalledWith('git', ['commit', '--message=The original commit message'], expect.any(String));
527
+ expect(spy.mock.calls[0]).toEqual([
528
+ 'git',
529
+ [
530
+ '-c',
531
+ 'user.name="Soren L"',
532
+ '-c',
533
+ 'user.email="soren@mail.dk"',
534
+ 'commit',
535
+ '--no-edit',
536
+ ],
537
+ expect.any(String),
538
+ ]);
539
+ expect(spy.mock.calls[1]).toEqual([
540
+ 'git',
541
+ [
542
+ '-c',
543
+ 'user.name="Soren L"',
544
+ '-c',
545
+ 'user.email="soren@mail.dk"',
546
+ 'commit',
547
+ '--message=The original commit message',
548
+ ],
549
+ expect.any(String),
550
+ ]);
513
551
  });
514
552
  it('should handle the error and resolve successfully', async () => {
515
553
  await expect(res).toBe(undefined);
@@ -519,7 +557,7 @@ describe('commitChanges', () => {
519
557
  const err = new Error('another error');
520
558
  jest.spyOn(childProcess, 'spawnPromise').mockRejectedValueOnce(err);
521
559
  expect.assertions(1);
522
- await expect((0, git_1.commitChanges)(commit, options)).rejects.toThrowErrorMatchingInlineSnapshot(`"another error"`);
560
+ await expect((0, git_1.commitChanges)({ commit, commitAuthor, options })).rejects.toThrowErrorMatchingInlineSnapshot(`"another error"`);
523
561
  });
524
562
  });
525
563
  describe('addRemote', () => {
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.getQueryName = exports.GithubV4Exception = exports.apiRequestV4 = void 0;
7
7
  const axios_1 = __importDefault(require("axios"));
8
8
  const printer_1 = require("graphql/language/printer");
9
+ const lodash_1 = require("lodash");
9
10
  const BackportError_1 = require("../../BackportError");
10
11
  const logger_1 = require("../../logger");
11
12
  async function apiRequestV4({ githubApiBaseUrlV4 = 'https://api.github.com/graphql', accessToken, query, variables, }) {
@@ -28,7 +29,7 @@ async function apiRequestV4({ githubApiBaseUrlV4 = 'https://api.github.com/graph
28
29
  return response.data.data;
29
30
  }
30
31
  catch (e) {
31
- if (axios_1.default.isAxiosError(e) && e.response) {
32
+ if (isAxiosGithubError(e) && e.response) {
32
33
  addDebugLogs({
33
34
  githubApiBaseUrlV4,
34
35
  query,
@@ -42,13 +43,10 @@ async function apiRequestV4({ githubApiBaseUrlV4 = 'https://api.github.com/graph
42
43
  }
43
44
  }
44
45
  exports.apiRequestV4 = apiRequestV4;
45
- function addDebugLogs({ githubApiBaseUrlV4, query, variables, githubResponse, didThrow = false, }) {
46
- const gqlQueryName = getQueryName(query);
47
- logger_1.logger.info(`POST ${githubApiBaseUrlV4} (name:${gqlQueryName}, status: ${githubResponse.status}${didThrow ? ', EXCEPTION THROWN' : ''})`);
48
- logger_1.logger.verbose(`Query: ${(0, printer_1.print)(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);
46
+ function isAxiosGithubError(e) {
47
+ return (axios_1.default.isAxiosError(e) &&
48
+ e.response !== undefined &&
49
+ (0, lodash_1.isObject)(e.response.data));
52
50
  }
53
51
  class GithubV4Exception extends Error {
54
52
  constructor(githubResponse, errorMessage) {
@@ -69,3 +67,11 @@ function getQueryName(query) {
69
67
  return query.definitions[0].name?.value;
70
68
  }
71
69
  exports.getQueryName = getQueryName;
70
+ function addDebugLogs({ githubApiBaseUrlV4, query, variables, githubResponse, didThrow = false, }) {
71
+ const gqlQueryName = getQueryName(query);
72
+ logger_1.logger.info(`POST ${githubApiBaseUrlV4} (name:${gqlQueryName}, status: ${githubResponse.status}${didThrow ? ', EXCEPTION THROWN' : ''})`);
73
+ logger_1.logger.verbose(`Query: ${(0, printer_1.print)(query)}`);
74
+ logger_1.logger.verbose('Variables:', variables);
75
+ logger_1.logger.verbose('Response headers:', githubResponse.headers);
76
+ logger_1.logger.verbose('Response data:', githubResponse.data);
77
+ }
@@ -47,7 +47,7 @@ describe('setupRepo', () => {
47
47
  it('should delete repo', async () => {
48
48
  expect.assertions(2);
49
49
  jest
50
- .spyOn(childProcess, 'spawnOriginal')
50
+ .spyOn(childProcess, 'spawnStream')
51
51
  .mockImplementation((cmd, cmdArgs) => {
52
52
  if (cmdArgs.includes('clone')) {
53
53
  throw new Error('Simulated git clone failure');
@@ -74,7 +74,7 @@ describe('setupRepo', () => {
74
74
  .spyOn(gitModule, 'getLocalSourceRepoPath')
75
75
  .mockResolvedValue(undefined);
76
76
  jest
77
- .spyOn(childProcess, 'spawnOriginal')
77
+ .spyOn(childProcess, 'spawnStream')
78
78
  //@ts-expect-error
79
79
  .mockImplementation(() => {
80
80
  return {
@@ -194,7 +194,7 @@ describe('setupRepo', () => {
194
194
  });
195
195
  function mockGitClone() {
196
196
  jest
197
- .spyOn(childProcess, 'spawnOriginal')
197
+ .spyOn(childProcess, 'spawnStream')
198
198
  //@ts-expect-error
199
199
  .mockImplementation((cmd, cmdArgs) => {
200
200
  if (cmdArgs.includes('clone')) {
@@ -227,7 +227,7 @@ describe('setupRepo', () => {
227
227
  });
228
228
  it('should clone it from github.com', async () => {
229
229
  expect(spinnerSuccessSpy).toHaveBeenCalledWith('100% Cloning repository from github.com (one-time operation)');
230
- expect(childProcess.spawnOriginal).toHaveBeenCalledWith('git', [
230
+ expect(childProcess.spawnStream).toHaveBeenCalledWith('git', [
231
231
  'clone',
232
232
  'https://x-access-token:myAccessToken@github.com/elastic/kibana.git',
233
233
  '/myHomeDir/.backport/repositories/elastic/kibana',
@@ -256,7 +256,7 @@ describe('setupRepo', () => {
256
256
  });
257
257
  it('should clone it from local folder', async () => {
258
258
  expect(spinnerSuccessSpy).toHaveBeenCalledWith('100% Cloning repository from /path/to/source/repo (one-time operation)');
259
- expect(childProcess.spawnOriginal).toHaveBeenCalledWith('git', [
259
+ expect(childProcess.spawnStream).toHaveBeenCalledWith('git', [
260
260
  'clone',
261
261
  '/path/to/source/repo',
262
262
  '/myHomeDir/.backport/repositories/elastic/kibana',