backport 7.1.0 → 7.2.0-beta.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 (56) hide show
  1. package/dist/entrypoint.cli.js +0 -0
  2. package/dist/entrypoint.module.d.ts +4 -3
  3. package/dist/entrypoint.module.js +2 -7
  4. package/dist/options/ConfigOptions.d.ts +1 -1
  5. package/dist/options/cliArgs.d.ts +1 -0
  6. package/dist/options/cliArgs.js +4 -0
  7. package/dist/options/config/config.d.ts +1 -1
  8. package/dist/options/config/readConfigFile.d.ts +1 -1
  9. package/dist/options/options.d.ts +2 -1
  10. package/dist/runSequentially.js +1 -0
  11. package/dist/runSequentially.test.js +55 -29
  12. package/dist/services/git.d.ts +3 -3
  13. package/dist/services/git.integration.test.js +66 -13
  14. package/dist/services/git.js +47 -5
  15. package/dist/services/git.test.js +15 -1
  16. package/dist/services/github/v3/createStatusComment.js +1 -1
  17. package/dist/services/github/v4/apiRequestV4.d.ts +4 -3
  18. package/dist/services/github/v4/apiRequestV4.js +15 -14
  19. package/dist/services/github/v4/fetchCommits/fetchCommitByPullNumber.js +19 -12
  20. package/dist/services/github/v4/fetchCommits/fetchCommitBySha.js +19 -12
  21. package/dist/services/github/v4/fetchCommits/fetchCommitsByAuthor.js +15 -9
  22. package/dist/services/github/v4/fetchCommits/fetchPullRequestBySearchQuery.js +15 -8
  23. package/dist/services/github/v4/fetchRemoteProjectConfig.js +1 -1
  24. package/dist/services/github/v4/getOptionsFromGithub/getOptionsFromGithub.d.ts +1 -1
  25. package/dist/services/github/v4/getOptionsFromGithub/getOptionsFromGithub.js +2 -15
  26. package/dist/services/github/v4/getOptionsFromGithub/query.js +1 -1
  27. package/dist/services/github/v4/mocks/commitsByAuthorMock.js +2 -5
  28. package/dist/services/github/v4/throwOnInvalidAccessToken.js +6 -6
  29. package/dist/services/github/v4/throwOnInvalidAccessToken.test.js +5 -5
  30. package/dist/services/remoteConfig.d.ts +2 -0
  31. package/dist/services/remoteConfig.js +15 -2
  32. package/dist/services/sourceCommit/getExpectedTargetPullRequests.d.ts +4 -1
  33. package/dist/services/sourceCommit/getExpectedTargetPullRequests.js +5 -1
  34. package/dist/services/sourceCommit/getExpectedTargetPullRequests.test.js +73 -39
  35. package/dist/services/sourceCommit/getMockSourceCommit.js +19 -18
  36. package/dist/services/sourceCommit/parseSourceCommit.d.ts +2 -2
  37. package/dist/services/sourceCommit/parseSourceCommit.js +9 -15
  38. package/dist/{entrypoint.cli.e2e.private.test.d.ts → test/e2e/cli.e2e.private.test.d.ts} +0 -0
  39. package/dist/{entrypoint.cli.e2e.private.test.js → test/e2e/cli.e2e.private.test.js} +153 -39
  40. package/dist/{services/github/v3/index.d.ts → test/e2e/module.e2e.private.test.d.ts} +0 -0
  41. package/dist/test/e2e/module.e2e.private.test.js +363 -0
  42. package/dist/test/handleUnbackportedPullRequests.private.test.js +0 -2
  43. package/dist/ui/cherrypickAndCreateTargetPullRequest.js +12 -18
  44. package/dist/ui/cherrypickAndCreateTargetPullRequest.test.js +6 -2
  45. package/dist/ui/getCommits.js +6 -4
  46. package/dist/ui/maybeSetupRepo.js +13 -16
  47. package/dist/ui/maybeSetupRepo.test.js +50 -16
  48. package/dist/ui/ora.d.ts +1 -1
  49. package/dist/ui/ora.js +2 -2
  50. package/dist/utils/packageVersion.d.ts +1 -1
  51. package/dist/utils/packageVersion.js +1 -1
  52. package/package.json +10 -10
  53. package/yarn.lock +121 -114
  54. package/dist/services/github/v3/index.js +0 -61
  55. package/dist/test/backport-e2e.mutation.test.d.ts +0 -1
  56. package/dist/test/backport-e2e.mutation.test.js +0 -347
File without changes
@@ -1,8 +1,9 @@
1
1
  import { ConfigFileOptions } from './options/ConfigOptions';
2
2
  import { ValidConfigOptions } from './options/options';
3
+ import { Commit } from './services/sourceCommit/parseSourceCommit';
3
4
  export { BackportResponse } from './backportRun';
4
5
  export { ConfigFileOptions } from './options/ConfigOptions';
5
- export { Commit } from './services/sourceCommit/parseSourceCommit';
6
+ export { Commit };
6
7
  export { fetchRemoteProjectConfig as getRemoteProjectConfig } from './services/github/v4/fetchRemoteProjectConfig';
7
8
  export { getGlobalConfig as getLocalGlobalConfig } from './options/config/globalConfig';
8
9
  export declare function backportRun(options: ConfigFileOptions, processArgs?: string[]): Promise<import("./backportRun").BackportResponse>;
@@ -14,9 +15,9 @@ export declare function getCommits(options: {
14
15
  branchLabelMapping?: ValidConfigOptions['branchLabelMapping'];
15
16
  githubApiBaseUrlV4?: string;
16
17
  pullNumber?: number;
17
- sha?: string;
18
+ sha?: string | string[];
18
19
  skipRemoteConfig?: boolean;
19
20
  sourceBranch?: string;
20
21
  dateUntil?: string;
21
22
  dateSince?: string;
22
- }): Promise<import("./services/sourceCommit/parseSourceCommit").Commit[]>;
23
+ }): Promise<Commit[]>;
@@ -37,13 +37,8 @@ async function getCommits(options) {
37
37
  ];
38
38
  }
39
39
  if (options.sha) {
40
- return [
41
- await (0, fetchCommitBySha_1.fetchCommitBySha)({
42
- ...optionsFromGithub,
43
- ...options,
44
- sha: options.sha,
45
- }),
46
- ];
40
+ const shas = Array.isArray(options.sha) ? options.sha : [options.sha];
41
+ return Promise.all(shas.map((sha) => (0, fetchCommitBySha_1.fetchCommitBySha)({ ...optionsFromGithub, ...options, sha })));
47
42
  }
48
43
  return (0, fetchCommitsByAuthor_1.fetchCommitsByAuthor)({
49
44
  ...optionsFromGithub,
@@ -45,7 +45,7 @@ declare type Options = Partial<{
45
45
  repoOwner: string;
46
46
  resetAuthor: boolean;
47
47
  reviewers: string[];
48
- sha: string;
48
+ sha: string | string[];
49
49
  skipRemoteConfig: boolean;
50
50
  sourceBranch: string;
51
51
  sourcePRLabels: string[];
@@ -16,6 +16,7 @@ export declare function getOptionsFromCliArgs(processArgs: readonly string[], {
16
16
  cherrypickRef?: boolean | undefined;
17
17
  configFile?: string | undefined;
18
18
  details?: boolean | undefined;
19
+ dryRun?: boolean | undefined;
19
20
  editor?: string | undefined;
20
21
  skipRemoteConfig?: boolean | undefined;
21
22
  gitHostname?: string | undefined;
@@ -83,6 +83,10 @@ function getOptionsFromCliArgs(processArgs, { exitOnError = true } = {}) {
83
83
  .option('details', {
84
84
  description: 'Show details about each commit',
85
85
  type: 'boolean',
86
+ })
87
+ .option('dryRun', {
88
+ description: 'Run backport locally without pushing to Github',
89
+ type: 'boolean',
86
90
  })
87
91
  .option('editor', {
88
92
  description: 'Editor to be opened during conflict resolution',
@@ -45,7 +45,7 @@ export declare function getOptionsFromConfigFiles({ optionsFromCliArgs, optionsF
45
45
  repoOwner?: string | undefined;
46
46
  resetAuthor?: boolean | undefined;
47
47
  reviewers?: string[] | undefined;
48
- sha?: string | undefined;
48
+ sha?: string | string[] | undefined;
49
49
  skipRemoteConfig?: boolean | undefined;
50
50
  sourceBranch?: string | undefined;
51
51
  sourcePRLabels?: string[] | undefined;
@@ -30,7 +30,7 @@ export declare function withConfigMigrations({ upstream, labels, branches, ...co
30
30
  prTitle?: string | undefined;
31
31
  prFilter?: string | undefined;
32
32
  pullNumber?: number | undefined;
33
- sha?: string | undefined;
33
+ sha?: string | string[] | undefined;
34
34
  resetAuthor?: boolean | undefined;
35
35
  repoOwner?: string | undefined;
36
36
  repoName?: string | undefined;
@@ -17,6 +17,7 @@ export declare function getOptions(processArgs: string[], optionsFromModule: Con
17
17
  cherrypickRef: boolean;
18
18
  configFile?: string | undefined;
19
19
  details: boolean;
20
+ dryRun?: boolean | undefined;
20
21
  editor?: string | undefined;
21
22
  skipRemoteConfig?: boolean | undefined;
22
23
  gitHostname: string;
@@ -31,7 +32,7 @@ export declare function getOptions(processArgs: string[], optionsFromModule: Con
31
32
  prTitle?: string | undefined;
32
33
  prFilter?: string | undefined;
33
34
  pullNumber?: number | undefined;
34
- sha?: string | undefined;
35
+ sha?: string | string[] | undefined;
35
36
  resetAuthor: boolean;
36
37
  sourceBranch: string;
37
38
  username?: string | undefined;
@@ -26,6 +26,7 @@ async function runSequentially({ options, commits, targetBranches, }) {
26
26
  });
27
27
  }
28
28
  catch (e) {
29
+ process.exitCode = 1;
29
30
  results.push({
30
31
  targetBranch,
31
32
  status: 'failure',
@@ -106,7 +106,7 @@ describe('runSequentially', () => {
106
106
  };
107
107
  rpcExecMock = jest
108
108
  .spyOn(childProcess, 'exec')
109
- .mockResolvedValue({ stdout: 'success', stderr: '' });
109
+ .mockResolvedValue({ stdout: '', stderr: '' });
110
110
  rpcExecOriginalMock = jest.spyOn(childProcess, 'execAsCallback');
111
111
  const scope = (0, nock_1.default)('https://api.github.com')
112
112
  .post('/repos/elastic/kibana/pulls')
@@ -169,35 +169,61 @@ describe('runSequentially', () => {
169
169
  ]
170
170
  `);
171
171
  });
172
- it('should run all exec commands in the either source or backport directory', () => {
172
+ it('should run commands in correct folders', () => {
173
173
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
174
- expect(rpcExecMock.mock.calls.map(([cmd, opts]) => opts.cwd)).toEqual([
175
- '/path/to/source/repo',
176
- '/myHomeDir/.backport/repositories/elastic/kibana',
177
- '/myHomeDir/.backport/repositories/elastic/kibana',
178
- '/myHomeDir/.backport/repositories/elastic/kibana',
179
- '/myHomeDir/.backport/repositories/elastic/kibana',
180
- '/myHomeDir/.backport/repositories/elastic/kibana',
181
- '/myHomeDir/.backport/repositories/elastic/kibana',
182
- '/myHomeDir/.backport/repositories/elastic/kibana',
183
- '/myHomeDir/.backport/repositories/elastic/kibana',
184
- '/myHomeDir/.backport/repositories/elastic/kibana',
185
- '/myHomeDir/.backport/repositories/elastic/kibana',
186
- ]);
187
- });
188
- it('exec commands should be called with correct args', () => {
189
- expect(rpcExecMock.mock.calls.map(([cmd]) => cmd)).toEqual([
190
- 'git remote --verbose',
191
- 'git remote rm origin',
192
- 'git remote rm sqren_authenticated',
193
- 'git remote add sqren_authenticated https://x-access-token:myAccessToken@github.com/sqren_authenticated/kibana.git',
194
- 'git remote rm elastic',
195
- 'git remote add elastic https://x-access-token:myAccessToken@github.com/elastic/kibana.git',
196
- 'git reset --hard && git clean -d --force && git fetch elastic 7.x && git checkout -B backport/7.x/pr-55 elastic/7.x --no-track',
197
- 'git fetch elastic master:master --force',
198
- 'git cherry-pick -x abcd',
199
- 'git push sqren_authenticated backport/7.x/pr-55:backport/7.x/pr-55 --force',
200
- 'git reset --hard && git checkout my-source-branch-from-options && git branch -D backport/7.x/pr-55',
174
+ expect(rpcExecMock.mock.calls.map(([cmd, { cwd }]) => ({ cmd, cwd }))).toEqual([
175
+ {
176
+ cmd: 'git rev-parse --show-toplevel',
177
+ cwd: '/myHomeDir/.backport/repositories/elastic/kibana',
178
+ },
179
+ {
180
+ cmd: 'git remote --verbose',
181
+ cwd: '/path/to/source/repo',
182
+ },
183
+ {
184
+ cmd: 'git remote rm origin',
185
+ cwd: '/myHomeDir/.backport/repositories/elastic/kibana',
186
+ },
187
+ {
188
+ cmd: 'git remote rm sqren_authenticated',
189
+ cwd: '/myHomeDir/.backport/repositories/elastic/kibana',
190
+ },
191
+ {
192
+ cmd: 'git remote add sqren_authenticated https://x-access-token:myAccessToken@github.com/sqren_authenticated/kibana.git',
193
+ cwd: '/myHomeDir/.backport/repositories/elastic/kibana',
194
+ },
195
+ {
196
+ cmd: 'git remote rm elastic',
197
+ cwd: '/myHomeDir/.backport/repositories/elastic/kibana',
198
+ },
199
+ {
200
+ cmd: 'git remote add elastic https://x-access-token:myAccessToken@github.com/elastic/kibana.git',
201
+ cwd: '/myHomeDir/.backport/repositories/elastic/kibana',
202
+ },
203
+ {
204
+ cmd: 'git reset --hard && git clean -d --force && git fetch elastic 7.x && git checkout -B backport/7.x/pr-55 elastic/7.x --no-track',
205
+ cwd: '/myHomeDir/.backport/repositories/elastic/kibana',
206
+ },
207
+ {
208
+ cmd: 'git fetch elastic master:master --force',
209
+ cwd: '/myHomeDir/.backport/repositories/elastic/kibana',
210
+ },
211
+ {
212
+ cmd: 'git rev-list -1 --merges abcd~1..abcd',
213
+ cwd: '/myHomeDir/.backport/repositories/elastic/kibana',
214
+ },
215
+ {
216
+ cmd: 'git cherry-pick -x abcd',
217
+ cwd: '/myHomeDir/.backport/repositories/elastic/kibana',
218
+ },
219
+ {
220
+ cmd: 'git push sqren_authenticated backport/7.x/pr-55:backport/7.x/pr-55 --force',
221
+ cwd: '/myHomeDir/.backport/repositories/elastic/kibana',
222
+ },
223
+ {
224
+ cmd: 'git reset --hard && git checkout my-source-branch-from-options && git branch -D backport/7.x/pr-55',
225
+ cwd: '/myHomeDir/.backport/repositories/elastic/kibana',
226
+ },
201
227
  ]);
202
228
  });
203
229
  it('git clone should be called with correct args', () => {
@@ -21,13 +21,13 @@ export declare function getRepoInfoFromGitRemotes({ cwd }: {
21
21
  repoOwner: string;
22
22
  repoName: string;
23
23
  }[]>;
24
- export declare function getGitProjectRoot({ cwd }: {
25
- cwd: string;
26
- }): Promise<string | undefined>;
24
+ export declare function getGitProjectRoot(dir: string): Promise<string | undefined>;
27
25
  export declare function getIsCommitInBranch(options: ValidConfigOptions, commitSha: string): Promise<boolean>;
28
26
  export declare function deleteRemote(options: ValidConfigOptions, remoteName: string): Promise<void>;
29
27
  export declare function addRemote(options: ValidConfigOptions, remoteName: string): Promise<void>;
30
28
  export declare function fetchBranch(options: ValidConfigOptions, branch: string): Promise<void>;
29
+ export declare function getIsMergeCommit(options: ValidConfigOptions, sha: string): Promise<boolean>;
30
+ export declare function getCommitsInMergeCommit(options: ValidConfigOptions, sha: string): Promise<string[]>;
31
31
  export declare function cherrypick(options: ValidConfigOptions, sha: string, mergedTargetPullRequest?: ExpectedTargetPullRequest): Promise<{
32
32
  conflictingFiles: {
33
33
  absolute: string;
@@ -31,19 +31,6 @@ const git_1 = require("./git");
31
31
  const commitFormatters_1 = require("./github/commitFormatters");
32
32
  jest.unmock('del');
33
33
  jest.unmock('make-dir');
34
- async function createAndCommitFile({ filename, content, execOpts, }) {
35
- await childProcess.exec(`echo "${content}" > "${filename}"`, execOpts);
36
- await childProcess.exec(`git add -A && git commit -m 'Update ${filename}'`, execOpts);
37
- return getCurrentSha(execOpts);
38
- }
39
- async function getCurrentSha(execOpts) {
40
- const { stdout } = await childProcess.exec('git rev-parse HEAD', execOpts);
41
- return stdout.trim();
42
- }
43
- async function getCurrentMessage(execOpts) {
44
- const { stdout } = await childProcess.exec('git --no-pager log -1 --pretty=%B', execOpts);
45
- return stdout.trim();
46
- }
47
34
  describe('git.integration', () => {
48
35
  describe('getIsCommitInBranch', () => {
49
36
  let firstSha;
@@ -239,7 +226,73 @@ describe('git.integration', () => {
239
226
  expect(await (0, git_1.getSourceRepoPath)(options)).toBe('https://x-access-token:verysecret@github.com/not-a-match/kibana.git');
240
227
  });
241
228
  });
229
+ describe('when cloning "backport-org/different-merge-strategies"', () => {
230
+ const MERGE_COMMIT_HASH_1 = 'bdc5a17f81e5f32129e27b05c742e055c650bc54';
231
+ const MERGE_COMMIT_HASH_2 = '0db7f1ac1233461563d8708511d1c14adbab46da';
232
+ const SQUASH_COMMIT_HASH = '74a76fa64b34e3ffe8f2a3f73840e1b42fd07299';
233
+ const REBASE_COMMIT_HASH = '9059ae0ca31caa2eebc035f2542842d6c2fde83b';
234
+ let sandboxPath;
235
+ beforeAll(async () => {
236
+ sandboxPath = (0, sandbox_1.getSandboxPath)({
237
+ filename: __filename,
238
+ specname: 'different-merge-strategies',
239
+ });
240
+ await (0, sandbox_1.resetSandbox)(sandboxPath);
241
+ await childProcess.exec('git clone https://github.com/backport-org/different-merge-strategies.git ./', { cwd: sandboxPath });
242
+ });
243
+ describe('getIsMergeCommit', () => {
244
+ it('returns true for first merge commit', async () => {
245
+ const res = await (0, git_1.getIsMergeCommit)({ dir: sandboxPath }, MERGE_COMMIT_HASH_1);
246
+ expect(res).toBe(true);
247
+ });
248
+ it('returns true for second merge commit', async () => {
249
+ const res = await (0, git_1.getIsMergeCommit)({ dir: sandboxPath }, MERGE_COMMIT_HASH_2);
250
+ expect(res).toBe(true);
251
+ });
252
+ it('returns false for rebased commits', async () => {
253
+ const res = await (0, git_1.getIsMergeCommit)({ dir: sandboxPath }, REBASE_COMMIT_HASH);
254
+ expect(res).toBe(false);
255
+ });
256
+ it('returns false for squashed commits', async () => {
257
+ const res = await (0, git_1.getIsMergeCommit)({ dir: sandboxPath }, SQUASH_COMMIT_HASH);
258
+ expect(res).toBe(false);
259
+ });
260
+ });
261
+ describe('getCommitsInMergeCommit', () => {
262
+ it('returns a list of commit hashes - excluding the merge hash itself', async () => {
263
+ const res = await (0, git_1.getCommitsInMergeCommit)({ dir: sandboxPath }, MERGE_COMMIT_HASH_1);
264
+ expect(res).not.toContain(MERGE_COMMIT_HASH_1);
265
+ expect(res).toEqual([
266
+ 'f9a760e0d9eb3ebcc64f8cb75ce885714b836496',
267
+ '7b92e29e88266004485ce0fae0260605b01df887',
268
+ 'a1facf8c006fb815d6a6ecd1b2907e6e64f29576',
269
+ 'b8d4bcfb0fd875be4ab0230f6db40ddf72f45378',
270
+ '6f224054db5f7772b04f23f17659070216bae84c',
271
+ '7fed54cbd1ba9cb973462670ff82ac80bf8a79f8',
272
+ '78c24d0058859e7d511d10ce91ebf279c7b58ac2',
273
+ '709ccf707d443dd8c001b3c3ae40fdf037bb43f5',
274
+ ]);
275
+ });
276
+ it('returns empty for squash commits', async () => {
277
+ const res = await (0, git_1.getCommitsInMergeCommit)({ dir: sandboxPath }, SQUASH_COMMIT_HASH);
278
+ expect(res).toEqual([]);
279
+ });
280
+ });
281
+ });
242
282
  });
283
+ async function createAndCommitFile({ filename, content, execOpts, }) {
284
+ await childProcess.exec(`echo "${content}" > "${filename}"`, execOpts);
285
+ await childProcess.exec(`git add -A && git commit -m 'Update ${filename}'`, execOpts);
286
+ return getCurrentSha(execOpts);
287
+ }
288
+ async function getCurrentSha(execOpts) {
289
+ const { stdout } = await childProcess.exec('git rev-parse HEAD', execOpts);
290
+ return stdout.trim();
291
+ }
292
+ async function getCurrentMessage(execOpts) {
293
+ const { stdout } = await childProcess.exec('git --no-pager log -1 --pretty=%B', execOpts);
294
+ return stdout.trim();
295
+ }
243
296
  function mockRepoOwnerAndName({ repoName, parentRepoOwner, childRepoOwner, }) {
244
297
  return (0, nockHelpers_1.mockGqlRequest)({
245
298
  name: 'RepoOwnerAndName',
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getSourceRepoPath = exports.pushBackportBranch = exports.getRepoForkOwner = exports.deleteBackportBranch = exports.createBackportBranch = exports.setCommitAuthor = exports.getUnstagedFiles = exports.getConflictingFiles = exports.commitChanges = exports.cherrypick = exports.fetchBranch = exports.addRemote = exports.deleteRemote = exports.getIsCommitInBranch = exports.getGitProjectRoot = exports.getRepoInfoFromGitRemotes = exports.isLocalConfigFileModified = exports.isLocalConfigFileUntracked = exports.getLocalConfigFileCommitDate = exports.cloneRepo = exports.getRemoteUrl = void 0;
3
+ exports.getSourceRepoPath = exports.pushBackportBranch = exports.getRepoForkOwner = exports.deleteBackportBranch = exports.createBackportBranch = exports.setCommitAuthor = exports.getUnstagedFiles = exports.getConflictingFiles = exports.commitChanges = exports.cherrypick = exports.getCommitsInMergeCommit = exports.getIsMergeCommit = exports.fetchBranch = exports.addRemote = exports.deleteRemote = exports.getIsCommitInBranch = exports.getGitProjectRoot = exports.getRepoInfoFromGitRemotes = exports.isLocalConfigFileModified = exports.isLocalConfigFileUntracked = exports.getLocalConfigFileCommitDate = exports.cloneRepo = exports.getRemoteUrl = void 0;
4
4
  const path_1 = require("path");
5
5
  const lodash_1 = require("lodash");
6
6
  const ora_1 = require("../ui/ora");
@@ -99,9 +99,11 @@ async function getRepoInfoFromGitRemotes({ cwd }) {
99
99
  }
100
100
  }
101
101
  exports.getRepoInfoFromGitRemotes = getRepoInfoFromGitRemotes;
102
- async function getGitProjectRoot({ cwd }) {
102
+ async function getGitProjectRoot(dir) {
103
103
  try {
104
- const { stdout } = await (0, child_process_promisified_1.exec)('git rev-parse --show-toplevel', { cwd });
104
+ const { stdout } = await (0, child_process_promisified_1.exec)('git rev-parse --show-toplevel', {
105
+ cwd: dir,
106
+ });
105
107
  return stdout.trim();
106
108
  }
107
109
  catch (e) {
@@ -156,10 +158,50 @@ async function fetchBranch(options, branch) {
156
158
  });
157
159
  }
158
160
  exports.fetchBranch = fetchBranch;
161
+ async function getIsMergeCommit(options, sha) {
162
+ const res = await (0, child_process_promisified_1.exec)(`git rev-list -1 --merges ${sha}~1..${sha}`, {
163
+ cwd: (0, env_1.getRepoPath)(options),
164
+ });
165
+ return res.stdout !== '';
166
+ }
167
+ exports.getIsMergeCommit = getIsMergeCommit;
168
+ async function getCommitsInMergeCommit(options, sha) {
169
+ try {
170
+ const res = await (0, child_process_promisified_1.exec)(`git --no-pager log ${sha}^1..${sha}^2 --pretty=format:"%H"`, {
171
+ cwd: (0, env_1.getRepoPath)(options),
172
+ });
173
+ return res.stdout.split('\n');
174
+ }
175
+ catch (e) {
176
+ // swallow error
177
+ if (e.code === 128) {
178
+ return [];
179
+ }
180
+ throw e;
181
+ }
182
+ }
183
+ exports.getCommitsInMergeCommit = getCommitsInMergeCommit;
159
184
  async function cherrypick(options, sha, mergedTargetPullRequest) {
160
185
  const mainlinArg = options.mainline != undefined ? ` --mainline ${options.mainline}` : '';
161
186
  const cherrypickRefArg = options.cherrypickRef === false ? '' : ' -x';
162
- const cmd = `git cherry-pick${cherrypickRefArg}${mainlinArg} ${sha}`;
187
+ let shaOrRange = sha;
188
+ if (!options.mainline) {
189
+ try {
190
+ const isMergeCommit = await getIsMergeCommit(options, sha);
191
+ if (isMergeCommit) {
192
+ const shas = await getCommitsInMergeCommit(options, sha);
193
+ shaOrRange = `${(0, lodash_1.last)(shas)}^..${(0, lodash_1.first)(shas)}`;
194
+ }
195
+ }
196
+ catch (e) {
197
+ // swallow error if it's a known error
198
+ // exit 128 will happen for many things, among others when the cherrypicked commit is empty
199
+ if (e.code !== 128) {
200
+ throw e;
201
+ }
202
+ }
203
+ }
204
+ const cmd = `git cherry-pick${cherrypickRefArg}${mainlinArg} ${shaOrRange}`;
163
205
  try {
164
206
  await (0, child_process_promisified_1.exec)(cmd, { cwd: (0, env_1.getRepoPath)(options) });
165
207
  return { conflictingFiles: [], unstagedFiles: [], needsResolving: false };
@@ -335,7 +377,7 @@ async function getSourceRepoPath(options) {
335
377
  const remoteUrl = getRemoteUrl(options, options.repoOwner);
336
378
  const sourcePath = options.repoName === gitRemote.repoName &&
337
379
  options.repoOwner === gitRemote.repoOwner
338
- ? (await getGitProjectRoot(options)) ?? remoteUrl
380
+ ? (await getGitProjectRoot(options.cwd)) ?? remoteUrl
339
381
  : remoteUrl;
340
382
  return sourcePath;
341
383
  }
@@ -275,7 +275,9 @@ describe('cherrypick', () => {
275
275
  it('should return `needsResolving: false` when no errors are encountered', async () => {
276
276
  jest
277
277
  .spyOn(childProcess, 'exec')
278
- // mock cherry pick command
278
+ // mock getIsMergeCommit(...)
279
+ .mockResolvedValueOnce({ stderr: '', stdout: '' })
280
+ // mock cherrypick(...)
279
281
  .mockResolvedValueOnce({ stderr: '', stdout: '' });
280
282
  expect(await (0, git_1.cherrypick)(options, 'abcd')).toEqual({
281
283
  conflictingFiles: [],
@@ -286,6 +288,8 @@ describe('cherrypick', () => {
286
288
  it('should use mainline option when specified', async () => {
287
289
  const execSpy = jest
288
290
  .spyOn(childProcess, 'exec')
291
+ // mock getIsMergeCommit(...)
292
+ .mockResolvedValueOnce({ stderr: '', stdout: '' })
289
293
  // mock cherry pick command
290
294
  .mockResolvedValueOnce({ stderr: '', stdout: '' });
291
295
  await (0, git_1.cherrypick)({ ...options, mainline: 1 }, 'abcd');
@@ -294,6 +298,8 @@ describe('cherrypick', () => {
294
298
  it('should return `needsResolving: true` upon cherrypick error', async () => {
295
299
  jest
296
300
  .spyOn(childProcess, 'exec')
301
+ // mock getIsMergeCommit(...)
302
+ .mockResolvedValueOnce({ stderr: '', stdout: '' })
297
303
  // mock cherry pick command
298
304
  .mockRejectedValueOnce(new ExecError_1.ExecError({
299
305
  killed: false,
@@ -325,6 +331,8 @@ describe('cherrypick', () => {
325
331
  it('should let the user know about the "--mainline" argument when cherry-picking a merge commit without specifying it', async () => {
326
332
  jest
327
333
  .spyOn(childProcess, 'exec')
334
+ // mock getIsMergeCommit(...)
335
+ .mockResolvedValueOnce({ stderr: '', stdout: '' })
328
336
  // mock cherry pick command
329
337
  .mockRejectedValueOnce(new ExecError_1.ExecError({
330
338
  killed: false,
@@ -348,6 +356,8 @@ Or refer to the git documentation for more information: https://git-scm.com/docs
348
356
  it('should gracefully handle empty commits', async () => {
349
357
  jest
350
358
  .spyOn(childProcess, 'exec')
359
+ // mock getIsMergeCommit(...)
360
+ .mockResolvedValueOnce({ stderr: '', stdout: '' })
351
361
  // mock cherry pick command
352
362
  .mockRejectedValueOnce(new ExecError_1.ExecError({
353
363
  killed: false,
@@ -362,6 +372,8 @@ Or refer to the git documentation for more information: https://git-scm.com/docs
362
372
  it('gracefully handles missing git info', async () => {
363
373
  jest
364
374
  .spyOn(childProcess, 'exec')
375
+ // mock getIsMergeCommit(...)
376
+ .mockResolvedValueOnce({ stderr: '', stdout: '' })
365
377
  // mock cherry pick command
366
378
  .mockRejectedValueOnce(new ExecError_1.ExecError({
367
379
  killed: false,
@@ -392,6 +404,8 @@ Or refer to the git documentation for more information: https://git-scm.com/docs
392
404
  it('should re-throw non-cherrypick errors', async () => {
393
405
  jest
394
406
  .spyOn(childProcess, 'exec')
407
+ // mock getIsMergeCommit(...)
408
+ .mockResolvedValueOnce({ stderr: '', stdout: '' })
395
409
  // mock cherry pick command
396
410
  .mockRejectedValueOnce(new Error('non-cherrypick error'))
397
411
  // getConflictingFiles
@@ -9,7 +9,7 @@ const logger_1 = require("../../logger");
9
9
  const commitFormatters_1 = require("../commitFormatters");
10
10
  async function createStatusComment({ options, backportResponse, }) {
11
11
  const { githubApiBaseUrlV3, repoName, repoOwner, accessToken, publishStatusComment, } = options;
12
- if (!publishStatusComment) {
12
+ if (!publishStatusComment || options.dryRun) {
13
13
  return;
14
14
  }
15
15
  try {
@@ -22,9 +22,10 @@ export declare function apiRequestV4<DataResponse>({ githubApiBaseUrlV4, accessT
22
22
  }): Promise<DataResponse>;
23
23
  declare type AxiosGithubResponse<DataResponse> = AxiosResponse<GithubV4Response<DataResponse | null>, any>;
24
24
  export declare class GithubV4Exception<DataResponse> extends Error {
25
- message: string;
26
- axiosResponse: AxiosGithubResponse<DataResponse>;
27
- constructor(message: string, axiosResponse: AxiosGithubResponse<DataResponse>);
25
+ githubResponse: AxiosGithubResponse<DataResponse> & {
26
+ request: undefined;
27
+ };
28
+ constructor(githubResponse: AxiosGithubResponse<DataResponse>, errorMessage?: string);
28
29
  }
29
30
  export declare function getQueryName(query: DocumentNode): string;
30
31
  export {};
@@ -17,16 +17,13 @@ async function apiRequestV4({ githubApiBaseUrlV4 = 'https://api.github.com/graph
17
17
  },
18
18
  });
19
19
  if (response.data.errors) {
20
- const message = `${response.data.errors
21
- .map((error) => error.message)
22
- .join(',')} (Github API v4)`;
23
- throw new GithubV4Exception(message, response);
20
+ throw new GithubV4Exception(response);
24
21
  }
25
22
  addDebugLogs({
26
23
  githubApiBaseUrlV4,
27
24
  query,
28
25
  variables,
29
- axiosResponse: response,
26
+ githubResponse: response,
30
27
  didSucceed: false,
31
28
  });
32
29
  return response.data.data;
@@ -37,32 +34,36 @@ async function apiRequestV4({ githubApiBaseUrlV4 = 'https://api.github.com/graph
37
34
  githubApiBaseUrlV4,
38
35
  query,
39
36
  variables,
40
- axiosResponse: e.response,
37
+ githubResponse: e.response,
41
38
  didSucceed: false,
42
39
  });
43
- throw new GithubV4Exception(`${e.message} (Unhandled Github API v4)`, e.response);
40
+ throw new GithubV4Exception(e.response, e.message);
44
41
  }
45
42
  throw e;
46
43
  }
47
44
  }
48
45
  exports.apiRequestV4 = apiRequestV4;
49
- function addDebugLogs({ githubApiBaseUrlV4, query, variables, axiosResponse, didSucceed, }) {
46
+ function addDebugLogs({ githubApiBaseUrlV4, query, variables, githubResponse, didSucceed, }) {
50
47
  const gqlQueryName = getQueryName(query);
51
- logger_1.logger.info(`POST ${githubApiBaseUrlV4} (name:${gqlQueryName}, status: ${axiosResponse.status})`);
48
+ logger_1.logger.info(`POST ${githubApiBaseUrlV4} (name:${gqlQueryName}, status: ${githubResponse.status})`);
52
49
  const logMethod = didSucceed ? logger_1.logger.verbose : logger_1.logger.info;
53
50
  logMethod(`Query name ${gqlQueryName}`);
54
51
  logMethod(`Query: ${query}`);
55
52
  logMethod('Variables:', variables);
56
- logMethod('Response headers:', axiosResponse.headers);
57
- logMethod('Response data:', axiosResponse.data);
53
+ logMethod('Response headers:', githubResponse.headers);
54
+ logMethod('Response data:', githubResponse.data);
58
55
  }
59
56
  class GithubV4Exception extends Error {
60
- constructor(message, axiosResponse) {
57
+ constructor(githubResponse, errorMessage) {
58
+ const githubMessage = githubResponse.data.errors
59
+ ?.map((error) => error.message)
60
+ .join(',');
61
+ const message = `${errorMessage ?? githubMessage ?? 'Unknown error'} (Github API v4)`;
61
62
  super(message);
62
- this.message = message;
63
- this.axiosResponse = axiosResponse;
64
63
  Error.captureStackTrace(this, HandledError_1.HandledError);
65
64
  this.name = 'GithubV4Exception';
65
+ this.message = message;
66
+ this.githubResponse = { ...githubResponse, request: undefined };
66
67
  }
67
68
  }
68
69
  exports.GithubV4Exception = GithubV4Exception;
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.fetchCommitByPullNumber = void 0;
7
7
  const graphql_tag_1 = __importDefault(require("graphql-tag"));
8
8
  const HandledError_1 = require("../../../HandledError");
9
+ const remoteConfig_1 = require("../../../remoteConfig");
9
10
  const parseSourceCommit_1 = require("../../../sourceCommit/parseSourceCommit");
10
11
  const apiRequestV4_1 = require("../apiRequestV4");
11
12
  async function fetchCommitByPullNumber(options) {
@@ -19,24 +20,30 @@ async function fetchCommitByPullNumber(options) {
19
20
  repository(owner: $repoOwner, name: $repoName) {
20
21
  pullRequest(number: $pullNumber) {
21
22
  mergeCommit {
22
- ...SourceCommitWithTargetPullRequest
23
+ ...SourceCommitWithTargetPullRequestFragment
23
24
  }
24
25
  }
25
26
  }
26
27
  }
27
28
 
28
- ${parseSourceCommit_1.sourceCommitWithTargetPullRequestFragment}
29
+ ${parseSourceCommit_1.SourceCommitWithTargetPullRequestFragment}
29
30
  `;
30
- const res = await (0, apiRequestV4_1.apiRequestV4)({
31
- githubApiBaseUrlV4,
32
- accessToken,
33
- query,
34
- variables: {
35
- repoOwner,
36
- repoName,
37
- pullNumber,
38
- },
39
- });
31
+ let res;
32
+ try {
33
+ res = await (0, apiRequestV4_1.apiRequestV4)({
34
+ githubApiBaseUrlV4,
35
+ accessToken,
36
+ query,
37
+ variables: {
38
+ repoOwner,
39
+ repoName,
40
+ pullNumber,
41
+ },
42
+ });
43
+ }
44
+ catch (e) {
45
+ res = (0, remoteConfig_1.swallowMissingConfigFileException)(e);
46
+ }
40
47
  const pullRequestNode = res.repository.pullRequest;
41
48
  if (!pullRequestNode) {
42
49
  throw new HandledError_1.HandledError(`The PR #${pullNumber} does not exist`);