backport 6.0.0 → 6.1.3

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 (106) hide show
  1. package/README.md +179 -52
  2. package/dist/entrypoint.cli.js +2 -0
  3. package/dist/entrypoint.module.d.ts +16 -4
  4. package/dist/entrypoint.module.js +41 -13
  5. package/dist/entrypoint.module.private.test.d.ts +1 -0
  6. package/dist/entrypoint.module.private.test.js +34 -0
  7. package/dist/main.js +1 -2
  8. package/dist/options/ConfigOptions.d.ts +16 -6
  9. package/dist/options/cliArgs.d.ts +36 -37
  10. package/dist/options/cliArgs.js +25 -24
  11. package/dist/options/cliArgs.test.js +6 -10
  12. package/dist/options/config/config.d.ts +28 -52
  13. package/dist/options/config/config.js +2 -36
  14. package/dist/options/config/config.test.js +10 -27
  15. package/dist/options/config/getOptionsFromGit.d.ts +3 -2
  16. package/dist/options/config/getOptionsFromGit.js +1 -3
  17. package/dist/options/config/globalConfig.js +2 -5
  18. package/dist/options/config/globalConfig.test.js +0 -2
  19. package/dist/options/config/projectConfig.test.js +51 -14
  20. package/dist/options/config/readConfigFile.d.ts +52 -0
  21. package/dist/options/config/readConfigFile.js +28 -2
  22. package/dist/options/options.d.ts +55 -32
  23. package/dist/options/options.js +101 -7
  24. package/dist/options/options.test.js +248 -97
  25. package/dist/options/parseRequiredOptions.d.ts +3 -3
  26. package/dist/options/parseRequiredOptions.js +2 -4
  27. package/dist/options/parseRequiredOptions.test.js +6 -11
  28. package/dist/runSequentially.test.js +40 -78
  29. package/dist/services/git.d.ts +5 -2
  30. package/dist/services/git.js +11 -10
  31. package/dist/services/git.test.js +12 -9
  32. package/dist/services/github/v3/addAssigneesToPullRequest.d.ts +1 -1
  33. package/dist/services/github/v3/addAssigneesToPullRequest.js +2 -3
  34. package/dist/services/github/v3/addAssigneesToPullRequest.test.js +4 -5
  35. package/dist/services/github/v3/createPullRequest.js +10 -13
  36. package/dist/services/github/v3/createPullRequest.test.d.ts +1 -0
  37. package/dist/services/github/v3/createPullRequest.test.js +110 -0
  38. package/dist/services/github/v3/createStatusComment.js +12 -14
  39. package/dist/services/github/v3/createStatusComment.test.js +58 -29
  40. package/dist/services/github/v4/apiRequestV4.d.ts +1 -1
  41. package/dist/services/github/v4/apiRequestV4.js +1 -1
  42. package/dist/services/github/v4/enablePullRequestAutoMerge.js +1 -1
  43. package/dist/services/github/v4/enablePullRequestAutoMerge.private.test.js +0 -1
  44. package/dist/services/github/v4/fetchAuthorId.d.ts +5 -2
  45. package/dist/services/github/v4/fetchAuthorId.js +5 -6
  46. package/dist/services/github/v4/fetchAuthorId.private.test.js +3 -6
  47. package/dist/services/github/v4/fetchCommits/fetchCommitByPullNumber.d.ts +8 -1
  48. package/dist/services/github/v4/fetchCommits/fetchCommitByPullNumber.js +1 -1
  49. package/dist/services/github/v4/fetchCommits/fetchCommitByPullNumber.private.test.js +6 -3
  50. package/dist/services/github/v4/fetchCommits/fetchCommitBySha.d.ts +8 -1
  51. package/dist/services/github/v4/fetchCommits/fetchCommitBySha.js +1 -1
  52. package/dist/services/github/v4/fetchCommits/fetchCommitBySha.private.test.js +3 -3
  53. package/dist/services/github/v4/fetchCommits/fetchCommitsByAuthor.d.ts +12 -1
  54. package/dist/services/github/v4/fetchCommits/fetchCommitsByAuthor.js +6 -8
  55. package/dist/services/github/v4/fetchCommits/fetchCommitsByAuthor.private.test.js +10 -12
  56. package/dist/services/github/v4/fetchCommits/fetchCommitsByAuthor.test.js +5 -7
  57. package/dist/services/github/v4/fetchCommits/fetchProjectConfig.d.ts +3 -0
  58. package/dist/services/github/v4/fetchCommits/fetchProjectConfig.js +55 -0
  59. package/dist/services/github/v4/fetchCommits/fetchPullRequestBySearchQuery.js +5 -5
  60. package/dist/services/github/v4/fetchCommits/fetchPullRequestBySearchQuery.private.test.js +2 -6
  61. package/dist/services/github/v4/fetchExistingPullRequest.private.test.js +0 -2
  62. package/dist/services/github/v4/fetchProjectConfig.d.ts +8 -0
  63. package/dist/services/github/v4/fetchProjectConfig.js +56 -0
  64. package/dist/services/github/v4/fetchProjectConfig.private.test.d.ts +1 -0
  65. package/dist/services/github/v4/fetchProjectConfig.private.test.js +52 -0
  66. package/dist/services/github/v4/fetchProjectConfig.test.d.ts +1 -0
  67. package/dist/services/github/v4/fetchProjectConfig.test.js +37 -0
  68. package/dist/services/github/v4/getOptionsFromGithub/getOptionsFromGithub.d.ts +67 -0
  69. package/dist/services/github/v4/getOptionsFromGithub/getOptionsFromGithub.js +130 -0
  70. package/dist/services/github/v4/getOptionsFromGithub/getOptionsFromGithub.private.test.d.ts +1 -0
  71. package/dist/services/github/v4/getOptionsFromGithub/getOptionsFromGithub.private.test.js +130 -0
  72. package/dist/services/github/v4/getOptionsFromGithub/index.d.ts +3 -1
  73. package/dist/services/github/v4/getOptionsFromGithub/index.private.test.js +22 -1
  74. package/dist/services/github/v4/getOptionsFromGithub/query.d.ts +4 -1
  75. package/dist/services/github/v4/getOptionsFromGithub/query.js +3 -0
  76. package/dist/services/sourceCommit/getExpectedTargetPullRequests.test.js +32 -15
  77. package/dist/services/sourceCommit/parseSourceCommit.d.ts +5 -1
  78. package/dist/services/sourceCommit/parseSourceCommit.js +2 -2
  79. package/dist/services/sourceCommit/parseSourceCommit.test.js +120 -5
  80. package/dist/test/inquirer.private.test.js +33 -36
  81. package/dist/test/integration/integration.private.test.js +114 -95
  82. package/dist/test/mockConfigFiles.d.ts +5 -0
  83. package/dist/test/mockConfigFiles.js +37 -0
  84. package/dist/test/nockHelpers.d.ts +1 -1
  85. package/dist/test/nockHelpers.js +4 -4
  86. package/dist/test/private/getDevAccessToken.js +1 -1
  87. package/dist/test/setupFiles/automatic-mocks.js +1 -29
  88. package/dist/ui/cherrypickAndCreatePullRequest.test.js +80 -28
  89. package/dist/ui/cherrypickAndCreateTargetPullRequest.d.ts +0 -9
  90. package/dist/ui/cherrypickAndCreateTargetPullRequest.js +13 -48
  91. package/dist/ui/cherrypickAndCreateTargetPullRequest.test.js +222 -260
  92. package/dist/ui/getCommits.d.ts +1 -1
  93. package/dist/ui/getCommitsWithoutBackports.d.ts +11 -0
  94. package/dist/ui/getCommitsWithoutBackports.js +53 -0
  95. package/dist/ui/getCommitsWithoutBackports.test.d.ts +1 -0
  96. package/dist/ui/getCommitsWithoutBackports.test.js +259 -0
  97. package/dist/ui/getTargetBranches.d.ts +2 -1
  98. package/dist/ui/getTargetBranches.js +17 -1
  99. package/dist/ui/maybeSetupRepo.js +4 -3
  100. package/dist/ui/maybeSetupRepo.test.js +49 -3
  101. package/dist/utils/excludeUndefined.d.ts +6 -0
  102. package/dist/utils/excludeUndefined.js +7 -0
  103. package/dist/utils/excludeUndefined.test.d.ts +1 -0
  104. package/dist/utils/excludeUndefined.test.js +24 -0
  105. package/package.json +9 -8
  106. package/yarn.lock +98 -77
@@ -54,16 +54,14 @@ function getTargetBranchChoicesAsObject(targetBranchChoices) {
54
54
  return choice;
55
55
  });
56
56
  }
57
- function getRequiredOptions({ accessToken, username, upstream, }) {
57
+ function getRequiredOptions({ accessToken, username, repoName, repoOwner, }) {
58
58
  // accessToken and username must be supplied in config or via cli args
59
59
  if (!accessToken || !username) {
60
60
  const globalConfigPath = (0, env_1.getGlobalConfigPath)();
61
61
  throw new HandledError_1.HandledError(`Please update your config file: ${globalConfigPath}.\nIt must contain a valid "username" and "accessToken".\n\nRead more: ${GLOBAL_CONFIG_DOCS_LINK}`);
62
62
  }
63
- // upstream must be specified via config or cli args
64
- const [repoOwner, repoName] = (upstream ?? '').split('/');
65
63
  if (!repoOwner || !repoName) {
66
- throw new HandledError_1.HandledError(`You must specify a valid Github repository\n\nYou can specify it via either:\n - Config file (recommended): ".backportrc.json". Read more: ${PROJECT_CONFIG_DOCS_LINK}\n - CLI: "--upstream elastic/kibana"`);
64
+ throw new HandledError_1.HandledError(`You must specify a valid Github repository\n\nYou can specify it via either:\n - Config file (recommended): ".backportrc.json". Read more: ${PROJECT_CONFIG_DOCS_LINK}\n - CLI: "--repo-owner elastic --repo-name kibana"`);
67
65
  }
68
66
  return { accessToken, username, repoOwner, repoName };
69
67
  }
@@ -14,7 +14,8 @@ describe('parseRequiredOptions', () => {
14
14
  ...config_1.defaultConfigOptions,
15
15
  accessToken: 'myAccessToken',
16
16
  username: 'sqren',
17
- upstream: 'elastic/kibana',
17
+ repoOwner: 'elastic',
18
+ repoName: 'kibana',
18
19
  targetBranches: ['branchA', 'branchB'],
19
20
  };
20
21
  const optionsFromCliArgs = {};
@@ -93,22 +94,16 @@ describe('parseRequiredOptions', () => {
93
94
  branchLabelMapping: {},
94
95
  }, optionsFromCliArgs, optionsFromGithub)).toThrowErrorMatchingSnapshot();
95
96
  });
96
- it('when upstream is missing', () => {
97
+ it('when repoName is missing', () => {
97
98
  expect(() => (0, parseRequiredOptions_1.parseRequiredOptions)({
98
99
  ...optionsFromConfigFiles,
99
- upstream: undefined,
100
+ repoName: undefined,
100
101
  }, optionsFromCliArgs, optionsFromGithub)).toThrowErrorMatchingSnapshot();
101
102
  });
102
- it('when upstream is empty', () => {
103
+ it('when repoOwner is missing', () => {
103
104
  expect(() => (0, parseRequiredOptions_1.parseRequiredOptions)({
104
105
  ...optionsFromConfigFiles,
105
- upstream: '',
106
- }, optionsFromCliArgs, optionsFromGithub)).toThrowErrorMatchingSnapshot();
107
- });
108
- it('when upstream is invalid', () => {
109
- expect(() => (0, parseRequiredOptions_1.parseRequiredOptions)({
110
- ...optionsFromConfigFiles,
111
- upstream: 'foobar',
106
+ repoOwner: undefined,
112
107
  }, optionsFromCliArgs, optionsFromGithub)).toThrowErrorMatchingSnapshot();
113
108
  });
114
109
  it('when username is missing', () => {
@@ -56,13 +56,13 @@ describe('runSequentially', () => {
56
56
  jest.spyOn(os_1.default, 'homedir').mockReturnValue('/myHomeDir');
57
57
  const options = {
58
58
  accessToken: 'myAccessToken',
59
- all: false,
59
+ authenticatedUsername: 'sqren_authenticated',
60
60
  assignees: [],
61
- author: 'sqren',
62
61
  autoAssign: false,
63
62
  autoFixConflicts: undefined,
64
63
  autoMerge: false,
65
64
  autoMergeMethod: 'merge',
65
+ backportBinary: 'node scripts/backport',
66
66
  branchLabelMapping: undefined,
67
67
  historicalBranchLabelMappings: [],
68
68
  cherrypickRef: true,
@@ -70,7 +70,7 @@ describe('runSequentially', () => {
70
70
  commitPaths: [],
71
71
  details: false,
72
72
  editor: 'code',
73
- forceLocalConfig: undefined,
73
+ skipRemoteConfig: undefined,
74
74
  fork: true,
75
75
  gitHostname: 'github.com',
76
76
  githubApiBaseUrlV3: 'https://api.github.com',
@@ -92,7 +92,6 @@ describe('runSequentially', () => {
92
92
  sourceBranch: 'my-source-branch-from-options',
93
93
  sourcePRLabels: [],
94
94
  targetBranches: [],
95
- upstream: 'elastic/kibana',
96
95
  targetBranchChoices: [
97
96
  { name: '6.x' },
98
97
  { name: '6.0' },
@@ -101,7 +100,7 @@ describe('runSequentially', () => {
101
100
  { name: '5.4' },
102
101
  ],
103
102
  targetPRLabels: [],
104
- username: 'sqren',
103
+ author: 'sqren',
105
104
  verbose: false,
106
105
  };
107
106
  rpcExecMock = jest
@@ -114,7 +113,7 @@ describe('runSequentially', () => {
114
113
  number: 1337,
115
114
  html_url: 'myHtmlUrl',
116
115
  });
117
- createPullRequestCalls = (0, nockHelpers_1.getNockCallsForScope)(scope);
116
+ createPullRequestCalls = (0, nockHelpers_1.listenForCallsToNockScope)(scope);
118
117
  const commits = [
119
118
  {
120
119
  sha: 'abcd',
@@ -141,82 +140,45 @@ describe('runSequentially', () => {
141
140
  ]);
142
141
  });
143
142
  it('creates pull request', () => {
144
- expect(createPullRequestCalls).toEqual([
145
- {
146
- base: '7.x',
147
- body: 'Backports the following commits to 7.x:\n - #55\n\nmyPrDescription',
148
- head: 'sqren:backport/7.x/pr-55',
149
- title: 'myPrTitle 7.x My commit message',
150
- },
151
- ]);
152
- });
153
- it('exec should be called with correct args', () => {
154
- expect(rpcExecMock).toHaveBeenCalledTimes(10);
155
- expect(rpcExecMock.mock.calls).toMatchInlineSnapshot(`
143
+ expect(createPullRequestCalls).toMatchInlineSnapshot(`
156
144
  Array [
157
- Array [
158
- "git remote rm origin",
159
- Object {
160
- "cwd": "/myHomeDir/.backport/repositories/elastic/kibana",
161
- },
162
- ],
163
- Array [
164
- "git remote rm sqren",
165
- Object {
166
- "cwd": "/myHomeDir/.backport/repositories/elastic/kibana",
167
- },
168
- ],
169
- Array [
170
- "git remote add sqren https://x-access-token:myAccessToken@github.com/sqren/kibana.git",
171
- Object {
172
- "cwd": "/myHomeDir/.backport/repositories/elastic/kibana",
173
- },
174
- ],
175
- Array [
176
- "git remote rm elastic",
177
- Object {
178
- "cwd": "/myHomeDir/.backport/repositories/elastic/kibana",
179
- },
180
- ],
181
- Array [
182
- "git remote add elastic https://x-access-token:myAccessToken@github.com/elastic/kibana.git",
183
- Object {
184
- "cwd": "/myHomeDir/.backport/repositories/elastic/kibana",
185
- },
186
- ],
187
- Array [
188
- "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",
189
- Object {
190
- "cwd": "/myHomeDir/.backport/repositories/elastic/kibana",
191
- },
192
- ],
193
- Array [
194
- "git fetch elastic master:master --force",
195
- Object {
196
- "cwd": "/myHomeDir/.backport/repositories/elastic/kibana",
197
- },
198
- ],
199
- Array [
200
- "git cherry-pick -x abcd",
201
- Object {
202
- "cwd": "/myHomeDir/.backport/repositories/elastic/kibana",
203
- },
204
- ],
205
- Array [
206
- "git push sqren backport/7.x/pr-55:backport/7.x/pr-55 --force",
207
- Object {
208
- "cwd": "/myHomeDir/.backport/repositories/elastic/kibana",
209
- },
210
- ],
211
- Array [
212
- "git reset --hard && git checkout my-source-branch-from-options && git branch -D backport/7.x/pr-55",
213
- Object {
214
- "cwd": "/myHomeDir/.backport/repositories/elastic/kibana",
215
- },
216
- ],
145
+ Object {
146
+ "base": "7.x",
147
+ "body": "# Backport
148
+
149
+ This is an automatic backport to 7.x of:
150
+ - #55
151
+
152
+ ### Questions ?
153
+ Please refer to the [Backport tool documentation](https://github.com/sqren/backport)
154
+
155
+ myPrDescription",
156
+ "head": "sqren_authenticated:backport/7.x/pr-55",
157
+ "title": "myPrTitle 7.x My commit message",
158
+ },
217
159
  ]
218
160
  `);
219
161
  });
162
+ it('should run all commands in the correct directory', () => {
163
+ expect(rpcExecMock.mock.calls.every(
164
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
165
+ ([cmd, opts]) => opts.cwd === '/myHomeDir/.backport/repositories/elastic/kibana')).toBe(true);
166
+ });
167
+ it('exec should be called with correct args', () => {
168
+ expect(rpcExecMock).toHaveBeenCalledTimes(10);
169
+ expect(rpcExecMock.mock.calls.map(([cmd]) => cmd)).toEqual([
170
+ 'git remote rm origin',
171
+ 'git remote rm sqren_authenticated',
172
+ 'git remote add sqren_authenticated https://x-access-token:myAccessToken@github.com/sqren_authenticated/kibana.git',
173
+ 'git remote rm elastic',
174
+ 'git remote add elastic https://x-access-token:myAccessToken@github.com/elastic/kibana.git',
175
+ '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',
176
+ 'git fetch elastic master:master --force',
177
+ 'git cherry-pick -x abcd',
178
+ 'git push sqren_authenticated backport/7.x/pr-55:backport/7.x/pr-55 --force',
179
+ 'git reset --hard && git checkout my-source-branch-from-options && git branch -D backport/7.x/pr-55',
180
+ ]);
181
+ });
220
182
  it('git clone should be called with correct args', () => {
221
183
  expect(rpcExecOriginalMock).toHaveBeenCalledTimes(1);
222
184
  expect(rpcExecOriginalMock.mock.calls).toMatchInlineSnapshot(`
@@ -7,7 +7,10 @@ export declare function cloneRepo(options: ValidConfigOptions, callback: (progre
7
7
  export declare function getLocalConfigFileCommitDate(): Promise<number | undefined>;
8
8
  export declare function isLocalConfigFileUntracked(): Promise<boolean | undefined>;
9
9
  export declare function isLocalConfigFileModified(): Promise<boolean | undefined>;
10
- export declare function getUpstreamFromGitRemote(): Promise<string | undefined>;
10
+ export declare function getRepoOwnerAndNameFromGitRemote(): Promise<{
11
+ repoOwner: string;
12
+ repoName: string;
13
+ } | undefined>;
11
14
  export declare function getIsCommitInBranch(options: ValidConfigOptions, commitSha: string): Promise<boolean>;
12
15
  export declare function deleteRemote(options: ValidConfigOptions, remoteName: string): Promise<void>;
13
16
  export declare function addRemote(options: ValidConfigOptions, remoteName: string): Promise<void>;
@@ -27,7 +30,7 @@ export declare function getConflictingFiles(options: ValidConfigOptions): Promis
27
30
  relative: string;
28
31
  }[]>;
29
32
  export declare function getUnstagedFiles(options: ValidConfigOptions): Promise<string[]>;
30
- export declare function setCommitAuthor(options: ValidConfigOptions, username: string): Promise<{
33
+ export declare function setCommitAuthor(options: ValidConfigOptions, author: string): Promise<{
31
34
  stdout: string;
32
35
  stderr: string;
33
36
  }>;
@@ -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.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.getUpstreamFromGitRemote = exports.isLocalConfigFileModified = exports.isLocalConfigFileUntracked = exports.getLocalConfigFileCommitDate = exports.cloneRepo = exports.getRemoteUrl = exports.deleteRepo = exports.repoExists = void 0;
6
+ 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.getRepoOwnerAndNameFromGitRemote = exports.isLocalConfigFileModified = exports.isLocalConfigFileUntracked = exports.getLocalConfigFileCommitDate = exports.cloneRepo = exports.getRemoteUrl = exports.deleteRepo = exports.repoExists = void 0;
7
7
  const path_1 = require("path");
8
8
  const del_1 = __importDefault(require("del"));
9
9
  const lodash_1 = require("lodash");
@@ -35,7 +35,7 @@ function deleteRepo(options) {
35
35
  return (0, del_1.default)(repoPath);
36
36
  }
37
37
  exports.deleteRepo = deleteRepo;
38
- function getRemoteUrl({ repoName, accessToken, gitHostname }, repoOwner) {
38
+ function getRemoteUrl({ repoName, accessToken, gitHostname = 'github.com' }, repoOwner) {
39
39
  return `https://x-access-token:${accessToken}@${gitHostname}/${repoOwner}/${repoName}.git`;
40
40
  }
41
41
  exports.getRemoteUrl = getRemoteUrl;
@@ -97,19 +97,20 @@ async function isLocalConfigFileModified() {
97
97
  }
98
98
  }
99
99
  exports.isLocalConfigFileModified = isLocalConfigFileModified;
100
- async function getUpstreamFromGitRemote() {
100
+ async function getRepoOwnerAndNameFromGitRemote() {
101
101
  try {
102
102
  const { stdout } = await (0, child_process_promisified_1.exec)('git remote --verbose', {});
103
103
  const matches = stdout.match(/github.com[:/]{1}(.*).git/);
104
104
  if (matches !== null) {
105
- return matches[1];
105
+ const [repoOwner, repoName] = matches[1].split('/');
106
+ return { repoOwner, repoName };
106
107
  }
107
108
  }
108
109
  catch (e) {
109
110
  return;
110
111
  }
111
112
  }
112
- exports.getUpstreamFromGitRemote = getUpstreamFromGitRemote;
113
+ exports.getRepoOwnerAndNameFromGitRemote = getRepoOwnerAndNameFromGitRemote;
113
114
  async function getIsCommitInBranch(options, commitSha) {
114
115
  try {
115
116
  const cwd = (0, env_1.getRepoPath)(options);
@@ -159,7 +160,7 @@ async function fetchBranch(options, branch) {
159
160
  exports.fetchBranch = fetchBranch;
160
161
  async function cherrypick(options, sha) {
161
162
  const mainlinArg = options.mainline != undefined ? ` --mainline ${options.mainline}` : '';
162
- const cherrypickRefArg = options.cherrypickRef ? ' -x' : '';
163
+ const cherrypickRefArg = options.cherrypickRef === false ? '' : ' -x';
163
164
  const cmd = `git cherry-pick${cherrypickRefArg}${mainlinArg} ${sha}`;
164
165
  try {
165
166
  await (0, child_process_promisified_1.exec)(cmd, { cwd: (0, env_1.getRepoPath)(options) });
@@ -264,10 +265,10 @@ async function getUnstagedFiles(options) {
264
265
  return (0, lodash_1.uniq)(files);
265
266
  }
266
267
  exports.getUnstagedFiles = getUnstagedFiles;
267
- async function setCommitAuthor(options, username) {
268
- const spinner = (0, ora_1.default)(`Changing author to "${username}"`).start();
268
+ async function setCommitAuthor(options, author) {
269
+ const spinner = (0, ora_1.default)(`Changing author to "${author}"`).start();
269
270
  try {
270
- const res = await (0, child_process_promisified_1.exec)(`git commit --amend --no-edit --author "${username} <${username}@users.noreply.github.com>"`, { cwd: (0, env_1.getRepoPath)(options) });
271
+ const res = await (0, child_process_promisified_1.exec)(`git commit --amend --no-edit --author "${author} <${author}@users.noreply.github.com>"`, { cwd: (0, env_1.getRepoPath)(options) });
271
272
  spinner.succeed();
272
273
  return res;
273
274
  }
@@ -308,7 +309,7 @@ exports.deleteBackportBranch = deleteBackportBranch;
308
309
  * Returns the repo owner of the forked repo or the source repo
309
310
  */
310
311
  function getRepoForkOwner(options) {
311
- return options.fork ? options.username : options.repoOwner;
312
+ return options.fork ? options.authenticatedUsername : options.repoOwner;
312
313
  }
313
314
  exports.getRepoForkOwner = getRepoForkOwner;
314
315
  async function pushBackportBranch({ options, backportBranch, }) {
@@ -139,19 +139,22 @@ describe('isLocalConfigFileModified', () => {
139
139
  expect(await (0, git_1.isLocalConfigFileModified)()).toEqual(undefined);
140
140
  });
141
141
  });
142
- describe('getUpstreamFromGitRemote', () => {
143
- it('returns first upstream matching pattern', async () => {
142
+ describe('getRepoOwnerAndNameFromGitRemote', () => {
143
+ it('returns first matching pattern', async () => {
144
144
  const res = {
145
145
  stdout: 'origin\tgit@github.com:elastic/kibana.git (fetch)\norigin\tgit@github.com:elastic/kibana.git (push)\nsqren\tgit@github.com:sqren/kibana.git (fetch)\nsqren\tgit@github.com:sqren/kibana.git (push)\n',
146
146
  stderr: '',
147
147
  };
148
148
  jest.spyOn(childProcess, 'exec').mockResolvedValue(res);
149
- expect(await (0, git_1.getUpstreamFromGitRemote)()).toEqual('elastic/kibana');
149
+ expect(await (0, git_1.getRepoOwnerAndNameFromGitRemote)()).toEqual({
150
+ repoOwner: 'elastic',
151
+ repoName: 'kibana',
152
+ });
150
153
  });
151
154
  it('returns undefined when no remotes exist', async () => {
152
155
  const res = { stdout: '', stderr: '' };
153
156
  jest.spyOn(childProcess, 'exec').mockResolvedValue(res);
154
- expect(await (0, git_1.getUpstreamFromGitRemote)()).toEqual(undefined);
157
+ expect(await (0, git_1.getRepoOwnerAndNameFromGitRemote)()).toEqual(undefined);
155
158
  });
156
159
  it('handles errors', async () => {
157
160
  const err = {
@@ -163,7 +166,7 @@ describe('getUpstreamFromGitRemote', () => {
163
166
  stderr: 'fatal: not a git repository (or any of the parent directories): .git\n',
164
167
  };
165
168
  jest.spyOn(childProcess, 'exec').mockRejectedValueOnce(err);
166
- expect(await (0, git_1.getUpstreamFromGitRemote)()).toEqual(undefined);
169
+ expect(await (0, git_1.getRepoOwnerAndNameFromGitRemote)()).toEqual(undefined);
167
170
  });
168
171
  });
169
172
  describe('getConflictingFiles', () => {
@@ -277,7 +280,7 @@ describe('cherrypick', () => {
277
280
  // mock cherry pick command
278
281
  .mockResolvedValueOnce({ stderr: '', stdout: '' });
279
282
  await (0, git_1.cherrypick)({ ...options, mainline: 1 }, 'abcd');
280
- expect(execSpy.mock.calls[0][0]).toBe('git cherry-pick --mainline 1 abcd');
283
+ expect(execSpy.mock.calls[0][0]).toBe('git cherry-pick -x --mainline 1 abcd');
281
284
  });
282
285
  it('should return `needsResolving: true` upon cherrypick error', async () => {
283
286
  jest
@@ -286,7 +289,7 @@ describe('cherrypick', () => {
286
289
  .mockRejectedValueOnce(new ExecError_1.ExecError({
287
290
  killed: false,
288
291
  code: 128,
289
- cmd: 'git cherry-pick abcd',
292
+ cmd: 'git cherry-pick -x abcd',
290
293
  stdout: '',
291
294
  stderr: '',
292
295
  }))
@@ -480,8 +483,8 @@ describe('addRemote', () => {
480
483
  });
481
484
  describe('pushBackportBranch', () => {
482
485
  const options = {
486
+ authenticatedUsername: 'sqren_authenticated',
483
487
  fork: true,
484
- username: 'sqren',
485
488
  repoOwner: 'elastic',
486
489
  repoName: 'kibana',
487
490
  };
@@ -495,6 +498,6 @@ describe('pushBackportBranch', () => {
495
498
  stdout: '',
496
499
  stderr: "remote: Repository not found.\nfatal: repository 'https://github.com/sqren/kibana.git/' not found\n",
497
500
  });
498
- await expect((0, git_1.pushBackportBranch)({ options, backportBranch })).rejects.toThrowErrorMatchingInlineSnapshot(`"Error pushing to https://github.com/sqren/kibana. Repository does not exist. Either fork the source repository (https://github.com/elastic/kibana) or disable fork mode \\"--no-fork\\". Read more about \\"fork mode\\" in the docs: https://github.com/sqren/backport/blob/3a182b17e0e7237c12915895aea9d71f49eb2886/docs/configuration.md#fork"`);
501
+ await expect((0, git_1.pushBackportBranch)({ options, backportBranch })).rejects.toThrowErrorMatchingInlineSnapshot(`"Error pushing to https://github.com/sqren_authenticated/kibana. Repository does not exist. Either fork the source repository (https://github.com/elastic/kibana) or disable fork mode \\"--no-fork\\". Read more about \\"fork mode\\" in the docs: https://github.com/sqren/backport/blob/3a182b17e0e7237c12915895aea9d71f49eb2886/docs/configuration.md#fork"`);
499
502
  });
500
503
  });
@@ -1,2 +1,2 @@
1
1
  import { ValidConfigOptions } from '../../../options/options';
2
- export declare function addAssigneesToPullRequest({ githubApiBaseUrlV3, repoName, repoOwner, accessToken, username, }: ValidConfigOptions, pullNumber: number, assignees: string[]): Promise<void>;
2
+ export declare function addAssigneesToPullRequest({ githubApiBaseUrlV3, repoName, repoOwner, accessToken, autoAssign, }: ValidConfigOptions, pullNumber: number, assignees: string[]): Promise<void>;
@@ -7,9 +7,8 @@ exports.addAssigneesToPullRequest = void 0;
7
7
  const rest_1 = require("@octokit/rest");
8
8
  const ora_1 = __importDefault(require("ora"));
9
9
  const logger_1 = require("../../logger");
10
- async function addAssigneesToPullRequest({ githubApiBaseUrlV3, repoName, repoOwner, accessToken, username, }, pullNumber, assignees) {
11
- const isSelfAssigning = assignees.length === 1 && assignees[0] === username;
12
- const text = isSelfAssigning
10
+ async function addAssigneesToPullRequest({ githubApiBaseUrlV3, repoName, repoOwner, accessToken, autoAssign, }, pullNumber, assignees) {
11
+ const text = autoAssign
13
12
  ? `Self-assigning to #${pullNumber}`
14
13
  : `Adding assignees to #${pullNumber}: ${assignees.join(', ')}`;
15
14
  logger_1.logger.info(text);
@@ -10,16 +10,15 @@ describe('addAssigneesToPullRequest', () => {
10
10
  const pullNumber = 216;
11
11
  const assignees = ['sqren'];
12
12
  const scope = (0, nock_1.default)('https://api.github.com')
13
- .post('/repos/backport-org/backport-demo/issues/216/assignees', {
13
+ .post('/repos/elastic/kibana/issues/216/assignees', {
14
14
  assignees: ['sqren'],
15
15
  })
16
16
  .reply(200, 'some response');
17
17
  const res = await (0, addAssigneesToPullRequest_1.addAssigneesToPullRequest)({
18
- githubApiBaseUrlV3: 'https://api.github.com',
19
- repoName: 'backport-demo',
20
- repoOwner: 'backport-org',
18
+ author: 'sqren',
19
+ repoName: 'kibana',
20
+ repoOwner: 'elastic',
21
21
  accessToken: 'my-token',
22
- username: 'sqren',
23
22
  }, pullNumber, assignees);
24
23
  expect(res).toBe(undefined);
25
24
  scope.done();
@@ -55,17 +55,7 @@ async function createPullRequest({ options, prPayload, }) {
55
55
  }
56
56
  exports.createPullRequest = createPullRequest;
57
57
  function getPullRequestBody({ options, commits, targetBranch, }) {
58
- const bodySuffix = options.prDescription
59
- ? `\n\n${options.prDescription}`
60
- : '';
61
- const backportDocsNote = `\n\nPlease refer to the [Backport tool documentation](https://github.com/sqren/backport) for additional information`;
62
- if (commits.length === 1) {
63
- const c = commits[0];
64
- const ref = c.pullNumber
65
- ? `pull request #${c.pullNumber}`
66
- : `commit ${c.sha}`;
67
- return `This is an automatic backport of ${ref} to ${targetBranch}.${backportDocsNote}${bodySuffix}`;
68
- }
58
+ const bodySuffix = options.prDescription ? `\n${options.prDescription}` : '';
69
59
  const commitMessages = commits
70
60
  .map((c) => {
71
61
  const message = c.pullNumber
@@ -74,14 +64,21 @@ function getPullRequestBody({ options, commits, targetBranch, }) {
74
64
  return ` - ${message}`;
75
65
  })
76
66
  .join('\n');
77
- return `This is an automatic backport of the following commits to ${targetBranch}:\n${commitMessages}${backportDocsNote}${bodySuffix}`;
67
+ return `# Backport
68
+
69
+ This is an automatic backport to \`${targetBranch}\` of:
70
+ ${commitMessages}
71
+
72
+ ### Questions ?
73
+ Please refer to the [Backport tool documentation](https://github.com/sqren/backport)
74
+ ${bodySuffix}`;
78
75
  }
79
76
  exports.getPullRequestBody = getPullRequestBody;
80
77
  function getTitle({ options, commits, targetBranch, }) {
81
78
  const commitMessages = commits
82
79
  .map((commit) => (0, commitFormatters_1.getFirstLine)(commit.originalMessage))
83
80
  .join(' | ');
84
- return options.prTitle
81
+ return (options.prTitle ?? '[{targetBranch}] {commitMessages}')
85
82
  .replace('{targetBranch}', targetBranch)
86
83
  .replace('{commitMessages}', commitMessages)
87
84
  .slice(0, 240);
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const createPullRequest_1 = require("./createPullRequest");
4
+ describe('getPullRequestBody', () => {
5
+ it('when single pull request is backported', () => {
6
+ expect((0, createPullRequest_1.getPullRequestBody)({
7
+ options: {},
8
+ commits: [
9
+ {
10
+ pullNumber: 55,
11
+ sha: 'abcdefghi',
12
+ originalMessage: 'My commit message',
13
+ },
14
+ ],
15
+ targetBranch: '7.x',
16
+ })).toMatchInlineSnapshot(`
17
+ "# Backport
18
+
19
+ This is an automatic backport to 7.x of:
20
+ - #55
21
+
22
+ ### Questions ?
23
+ Please refer to the [Backport tool documentation](https://github.com/sqren/backport)
24
+ "
25
+ `);
26
+ });
27
+ it('when a single commit (non pull request) is backported', () => {
28
+ expect((0, createPullRequest_1.getPullRequestBody)({
29
+ options: {},
30
+ commits: [
31
+ {
32
+ sha: 'abcdefghijklmw',
33
+ originalMessage: 'My commit message',
34
+ },
35
+ ],
36
+ targetBranch: '7.x',
37
+ })).toMatchInlineSnapshot(`
38
+ "# Backport
39
+
40
+ This is an automatic backport to 7.x of:
41
+ - My commit message (abcdefgh)
42
+
43
+ ### Questions ?
44
+ Please refer to the [Backport tool documentation](https://github.com/sqren/backport)
45
+ "
46
+ `);
47
+ });
48
+ it('when multiple commits are backported', () => {
49
+ expect((0, createPullRequest_1.getPullRequestBody)({
50
+ options: {},
51
+ commits: [
52
+ {
53
+ pullNumber: 55,
54
+ sha: 'abcdefghijklm',
55
+ originalMessage: 'My commit message',
56
+ },
57
+ {
58
+ sha: 'qwertyuiop',
59
+ originalMessage: 'Another commit message',
60
+ },
61
+ ],
62
+ targetBranch: '7.x',
63
+ })).toMatchInlineSnapshot(`
64
+ "# Backport
65
+
66
+ This is an automatic backport to 7.x of:
67
+ - #55
68
+ - Another commit message (qwertyui)
69
+
70
+ ### Questions ?
71
+ Please refer to the [Backport tool documentation](https://github.com/sqren/backport)
72
+ "
73
+ `);
74
+ });
75
+ });
76
+ describe('getTitle', () => {
77
+ it('when the default title is used', () => {
78
+ expect((0, createPullRequest_1.getTitle)({
79
+ options: {},
80
+ commits: [
81
+ {
82
+ pullNumber: 55,
83
+ sha: 'abcdefghi',
84
+ originalMessage: 'My commit message',
85
+ },
86
+ {
87
+ pullNumber: 56,
88
+ sha: 'jklmnopqr',
89
+ originalMessage: 'Another commit message',
90
+ },
91
+ ],
92
+ targetBranch: '7.x',
93
+ })).toEqual('[7.x] My commit message | Another commit message');
94
+ });
95
+ it('when a custom PR title is used', () => {
96
+ expect((0, createPullRequest_1.getTitle)({
97
+ options: {
98
+ prTitle: 'Branch: "{targetBranch}". Messages: {commitMessages}',
99
+ },
100
+ commits: [
101
+ {
102
+ pullNumber: 55,
103
+ sha: 'abcdefghi',
104
+ originalMessage: 'My commit message',
105
+ },
106
+ ],
107
+ targetBranch: '7.x',
108
+ })).toEqual('Branch: "7.x". Messages: My commit message');
109
+ });
110
+ });
@@ -43,14 +43,13 @@ async function createStatusComment({ options, backportResponse, }) {
43
43
  exports.createStatusComment = createStatusComment;
44
44
  function getCommentBody({ options, pullNumber, backportResponse, }) {
45
45
  const { repoName, repoOwner, autoMerge } = options;
46
- const backportPRCommand = `To backport manually run: \`node scripts/backport --pr ${pullNumber}\`.\nFor more info read the [Backport documentation](https://github.com/sqren/backport#backport)`;
46
+ const backportPRCommand = `\n### How to fix\nRe-run the backport manually:\n\`\`\`\n${options.backportBinary} --pr ${pullNumber}\n\`\`\``;
47
+ const supportSection = '\n\n### Questions ?\nPlease refer to the [Backport tool documentation](https://github.com/sqren/backport)';
47
48
  if (backportResponse.status === 'failure') {
48
49
  return `## 💔 Backport failed
49
50
  The pull request could not be backported due to the following error:
50
51
  \`${backportResponse.errorMessage}\`
51
-
52
- ${backportPRCommand}
53
- `;
52
+ ${backportPRCommand}${supportSection}`;
54
53
  }
55
54
  const tableBody = backportResponse.results
56
55
  .map((result) => {
@@ -62,16 +61,14 @@ ${backportPRCommand}
62
61
  ];
63
62
  }
64
63
  if (result.error.meta?.type === 'commitsWithoutBackports') {
65
- const conflictMessage = result.error.meta.commitsWithoutBackports.map((c) => {
66
- if (c.commit.pullNumber) {
67
- return ` - [#${c.commit.pullNumber}](${c.commit.pullUrl})`;
68
- }
69
- return ` - ${(0, commitFormatters_1.getFirstLine)(c.commit.originalMessage)} (${(0, commitFormatters_1.getShortSha)(c.commit.sha)})`;
64
+ const conflictingPullRequests = result.error.meta.commitsWithoutBackports.map((c) => {
65
+ return ` - [${(0, commitFormatters_1.getFirstLine)(c.commit.originalMessage)}](${c.commit.pullUrl})`;
70
66
  });
67
+ const conflictSection = `<br><br>You might need to backport the following PRs to ${result.targetBranch}:<br>${conflictingPullRequests.join('<br>')}`;
71
68
  return [
72
69
  '❌',
73
70
  result.targetBranch,
74
- `Could not backport due to conflicts, possibly caused by the following unbackported commits:<br>${conflictMessage.join('<br>')}`,
71
+ `**Backport failed because of merge conflicts**${conflictingPullRequests.length > 0 ? conflictSection : ''}`,
75
72
  ];
76
73
  }
77
74
  return ['❌', result.targetBranch, result.errorMessage];
@@ -79,7 +76,7 @@ ${backportPRCommand}
79
76
  .map((line) => line.join('|'))
80
77
  .join('|\n|');
81
78
  const table = backportResponse.results.length
82
- ? `| Status | Branch | Result |\n|:------:|:------:|:------:|\n|${tableBody}|`
79
+ ? `| Status | Branch | Result |\n|:------:|:------:|:------|\n|${tableBody}|`
83
80
  : '';
84
81
  const didAllBackportsSucceed = backportResponse.results.every((r) => r.status === 'success');
85
82
  const didAnyBackportsSucceed = backportResponse.results.some((r) => r.status === 'success');
@@ -87,11 +84,12 @@ ${backportPRCommand}
87
84
  ? '## 💚 All backports created successfully'
88
85
  : '## 💔 Some backports could not be created';
89
86
  const autoMergeMessage = autoMerge && didAnyBackportsSucceed
90
- ? 'Note: Successful backport PRs will be merged automatically after passing CI.\n'
87
+ ? '\nNote: Successful backport PRs will be merged automatically after passing CI.'
91
88
  : '';
92
89
  const backportPRCommandMessage = !didAllBackportsSucceed
93
- ? `${backportPRCommand}\n\n`
90
+ ? `${backportPRCommand}`
94
91
  : '';
95
- return (0, logger_1.redactAccessToken)(`${header}\n\n${table}\n\n${backportPRCommandMessage}${autoMergeMessage}`);
92
+ return (0, logger_1.redactAccessToken)(`${header}\n\n${table}
93
+ ${backportPRCommandMessage}${autoMergeMessage}${supportSection}`);
96
94
  }
97
95
  exports.getCommentBody = getCommentBody;