backport 6.1.1 → 6.1.2

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.
package/README.md CHANGED
@@ -1,10 +1,16 @@
1
- # backport
1
+ <div align="center">
2
+ <img src="https://user-images.githubusercontent.com/209966/148229483-9f867a20-da7d-4cff-8c52-fcb27d482b89.png" height="200">
3
+ <p>
4
+ <b>A CLI tool that automates the process of backporting commits.</b>
5
+ </p>
6
+ <br>
7
+ </div>
2
8
 
3
- [![Build Status](https://travis-ci.com/sqren/backport.svg?branch=master)](https://app.travis-ci.com/github/sqren/backport)
4
- [![NPM version](https://img.shields.io/npm/v/backport.svg)](https://www.npmjs.com/package/backport)
5
- [![Coverage Status](https://coveralls.io/repos/github/sqren/backport/badge.svg?branch=master)](https://coveralls.io/github/sqren/backport?branch=master)
9
+ ## How it works
6
10
 
7
- A simple CLI tool that automates the process of backporting commits on a GitHub repo.
11
+ 1. Select a commit to backport
12
+ 2. Select a branch to backport to
13
+ 3. The commit will be cherrypicked, pushed and a pull request created.
8
14
 
9
15
  ![backport-demo](https://user-images.githubusercontent.com/209966/80993576-95766380-8e3b-11ea-9efd-b35eb2e6a9ec.gif)
10
16
 
@@ -34,7 +40,7 @@ Add a [project config](https://github.com/sqren/backport/blob/master/docs/config
34
40
  // the branches available to backport to
35
41
  "targetBranchChoices": ["main", "6.3", "6.2", "6.1", "6.0"],
36
42
 
37
- // Automatically detect which branches a pull request should be backported to based on the pull request labels.
43
+ // Optional: Automatically detect which branches a pull request should be backported to based on the pull request labels.
38
44
  "branchLabelMapping": {
39
45
  "^backport-to-(.+)$": "$1"
40
46
  }
@@ -100,37 +106,37 @@ See [configuration.md](https://github.com/sqren/backport/blob/master/docs/config
100
106
 
101
107
  The CLI options will override the [configuration options](https://github.com/sqren/backport/blob/master/docs/configuration.md).
102
108
 
103
- ### Node module
109
+ ## Backport Module API
104
110
 
105
- `backport` can be imported as a Node module and interacted with programatically.
111
+ `backport` can be imported as a Node module and interacted with programatically. This can be useful when creating automation around the Backport tool. See for example the [Backport Github Action](https://github.com/elastic/kibana-github-actions/blob/f5c58195840b8b0cf6036cfeba6e0b497306fb39/backport/index.ts)
106
112
 
107
- #### `backportRun`
113
+ ### `backportRun`
108
114
 
109
115
  Backport a commit programatically. Commits can be selected via `pullNumber` or `sha`.
110
116
 
111
- ##### Arguments:
117
+ #### Arguments:
112
118
 
113
119
  All of the options listed on [configuration.md](https://github.com/sqren/backport/blob/main/docs/configuration.md) are valid. The most common options are:
114
120
 
115
- `accessToken` _string_ **(Required)**
121
+ `accessToken` _string_ **(Required)**<br/>
116
122
  Github access token to authenticate the request
117
123
 
118
- `repoName` _string_ **(Required)**
124
+ `repoName` _string_ **(Required)**<br/>
119
125
  Name of repository
120
126
 
121
- `repoOwner` _string_ **(Required)**
127
+ `repoOwner` _string_ **(Required)**<br/>
122
128
  Owner of repository (organisation or username)
123
129
 
124
- `pullNumber` _number_
130
+ `pullNumber` _number_<br/>
125
131
  Filter commits by pull request number
126
132
 
127
- `sha` _string_
133
+ `sha` _string_<br/>
128
134
  Filter commits by commit sha
129
135
 
130
- `ci` _boolean_
136
+ `ci` _boolean_<br/>
131
137
  Enabling this will disable the interactive prompts
132
138
 
133
- ##### Example
139
+ #### Example
134
140
 
135
141
  ```ts
136
142
  import { backportRun } from 'backport';
@@ -149,34 +155,34 @@ const result = await backportRun({
149
155
  console.log(result);
150
156
  ```
151
157
 
152
- #### `getCommits`
158
+ ### `getCommits`
153
159
 
154
160
  Retrieve information about commits and whether they are backported
155
161
 
156
- ##### Arguments:
162
+ #### Arguments:
157
163
 
158
- `accessToken` _string_ **(Required)**
164
+ `accessToken` _string_ **(Required)**<br/>
159
165
  Github access token to authenticate the request
160
166
 
161
- `repoName` _string_ **(Required)**
167
+ `repoName` _string_ **(Required)**<br/>
162
168
  Name of repository
163
169
 
164
- `repoOwner` _string_ **(Required)**
170
+ `repoOwner` _string_ **(Required)**<br/>
165
171
  Owner of repository (organisation or username)
166
172
 
167
- `author` _string_
173
+ `author` _string_<br/>
168
174
  Filter commits by Github user
169
175
 
170
- `pullNumber` _number_
176
+ `pullNumber` _number_<br/>
171
177
  Filter commits by pull request number
172
178
 
173
- `sha` _string_
179
+ `sha` _string_<br/>
174
180
  Filter commits by commit sha
175
181
 
176
- `sourceBranch` _string_
182
+ `sourceBranch` _string_<br/>
177
183
  The branch to display commits from. Defaults to the default branch (normally "main" or "master")
178
184
 
179
- ##### Example
185
+ #### Example
180
186
 
181
187
  ```ts
182
188
  import { getCommits } from 'backport';
@@ -210,9 +216,9 @@ console.log(commits);
210
216
  */
211
217
  ```
212
218
 
213
- ## Github Action (beta)
219
+ ## The Backport Tool as a Github Action
214
220
 
215
- A [Github Action](https://github.com/elastic/kibana-github-actions/tree/main/backport) for automatically backporting pull requests.
221
+ A [Github Action](https://github.com/elastic/kibana-github-actions/tree/main/backport) around The Backport Tool for automatically creating backports when pull requests are merged.
216
222
 
217
223
  ## What is backporting?
218
224
 
@@ -224,20 +230,21 @@ Source: [https://en.wikipedia.org/wiki/Backporting](https://en.wikipedia.org/wik
224
230
 
225
231
  This tools is for anybody who is working on a codebase where they have to maintain multiple versions. If you manually cherry-pick commits from master and apply them to one or more branches, this tool might save you a lot of time.
226
232
 
227
- `backport` is a CLI tool that will let you backport commit(s) interactively and then cherry-pick and create pull requests automatically. `backport` will always perform the git operation in a temporary folder (`~/.backport/repositories/`) separate from your working directory, thereby never interfering with any unstages changes your might have.
233
+ `backport` is a CLI tool that will let you backport commit(s) interactively and then cherry-pick and create pull requests automatically. `backport` will perform all git operations in a temporary folder (`~/.backport/repositories/`) separate from your working directory, thereby never interfering with any unstages changes your might have.
228
234
 
229
235
  **Features:**
230
236
 
231
237
  - interactively backport one or more commits to one or more branches with an intuitive UI
232
- - will never run `git reset --hard` or other git commands in your working directory - all git operations are handled in a separate directory
238
+ - ability to see which commits have been backported and to which branches
239
+ - ability to customize the title, description and labels of the created backport PRs
240
+ - all git operations are handled in a separate directory to not interfere with unstaged files
241
+ - Conflicts are handled gracefully, and hints are provided to help the user understand the source of the conflict
233
242
  - backport a commit by specifying a PR: `backport --pr 1337`
234
243
  - list and backport commits by a particular user: `backport --author john`
235
244
  - list and backport commits by a particular path: `backport --path src/plugins/chatbot`
236
245
  - list PRs filtered by a query: `backport --pr-filter label:backport-v2` (will list commits from PRs with the label "backport-v2")
237
- - forward port commits: `backport --sourceBranch 7.x --branch master` (will forwardport from 7.x to master)
246
+ - forward port commits: `backport --source-branch 7.x --branch master` (will forwardport from 7.x to master)
238
247
  - backport merge commits: `backport --mainline`
239
- - ability to see which commits have been backported and to which branches
240
- - customize the title, description and labels of the created backport PRs
241
248
 
242
249
  ## Contributing
243
250
 
@@ -245,3 +252,7 @@ See [CONTRIBUTING.md](https://github.com/sqren/backport/blob/master/CONTRIBUTING
245
252
 
246
253
  [1]: https://git-scm.com/docs/git-cherry-pick#Documentation/git-cherry-pick.txt--x
247
254
  [2]: https://docs.github.com/en/search-github/getting-started-with-searching-on-github/understanding-the-search-syntax
255
+
256
+ [![Build Status](https://travis-ci.com/sqren/backport.svg?branch=master)](https://app.travis-ci.com/github/sqren/backport)
257
+ [![NPM version](https://img.shields.io/npm/v/backport.svg)](https://www.npmjs.com/package/backport)
258
+ [![Coverage Status](https://coveralls.io/repos/github/sqren/backport/badge.svg?branch=master)](https://coveralls.io/github/sqren/backport?branch=master)
@@ -18,6 +18,7 @@ declare type Options = Partial<{
18
18
  autoFixConflicts: AutoFixConflictsHandler;
19
19
  autoMerge: boolean;
20
20
  autoMergeMethod: string;
21
+ backportBinary: string;
21
22
  cherrypickRef: boolean;
22
23
  ci: boolean;
23
24
  commitPaths: string[];
@@ -20,8 +20,6 @@ describe('getOptionsFromCliArgs', () => {
20
20
  const argv = [
21
21
  '--access-token',
22
22
  'my access token',
23
- '--author',
24
- 'sqren',
25
23
  '--repo-owner',
26
24
  'elastic',
27
25
  '--repo-name',
@@ -32,11 +30,6 @@ describe('getOptionsFromCliArgs', () => {
32
30
  accessToken: 'my access token',
33
31
  repoOwner: 'elastic',
34
32
  repoName: 'kibana',
35
- author: 'sqren',
36
- mainline: 1,
37
- reviewers: [],
38
- assignees: [],
39
- commitPaths: [],
40
33
  });
41
34
  });
42
35
  });
@@ -19,6 +19,7 @@ export declare function getOptionsFromConfigFiles(optionsFromModule?: ConfigFile
19
19
  }) => boolean | Promise<boolean>) | undefined;
20
20
  autoMerge?: boolean | undefined;
21
21
  autoMergeMethod?: string | undefined;
22
+ backportBinary?: string | undefined;
22
23
  cherrypickRef?: boolean | undefined;
23
24
  ci?: boolean | undefined;
24
25
  commitPaths?: string[] | undefined;
@@ -21,6 +21,7 @@ export declare function withConfigMigrations({ upstream, labels, branches, ...co
21
21
  }) => boolean | Promise<boolean>) | undefined;
22
22
  autoMerge?: boolean | undefined;
23
23
  autoMergeMethod?: string | undefined;
24
+ backportBinary?: string | undefined;
24
25
  cherrypickRef?: boolean | undefined;
25
26
  ci?: boolean | undefined;
26
27
  commitPaths?: string[] | undefined;
@@ -5,6 +5,7 @@ export declare const defaultConfigOptions: {
5
5
  autoAssign: boolean;
6
6
  autoMerge: boolean;
7
7
  autoMergeMethod: string;
8
+ backportBinary: string;
8
9
  cherrypickRef: boolean;
9
10
  ci: boolean;
10
11
  commitPaths: string[];
@@ -75,6 +76,7 @@ export declare function getOptions(argv: string[], optionsFromModule?: ConfigFil
75
76
  };
76
77
  targetBranch: string;
77
78
  }) => boolean | Promise<boolean>) | undefined;
79
+ backportBinary: string;
78
80
  multiple?: boolean | undefined;
79
81
  branchLabelMapping?: Record<string, string> | undefined;
80
82
  upstream?: string | undefined;
@@ -15,6 +15,7 @@ exports.defaultConfigOptions = {
15
15
  autoAssign: false,
16
16
  autoMerge: false,
17
17
  autoMergeMethod: 'merge',
18
+ backportBinary: 'backport',
18
19
  cherrypickRef: true,
19
20
  ci: false,
20
21
  commitPaths: [],
@@ -28,45 +28,6 @@ const mockConfigFiles_1 = require("../test/mockConfigFiles");
28
28
  const nockHelpers_1 = require("../test/nockHelpers");
29
29
  const options_1 = require("./options");
30
30
  jest.unmock('../services/fs-promisified');
31
- function mockGithubConfigOptions({ viewerLogin = 'sqren', defaultBranchRef = 'DO_NOT_USE-default-branch-name', refName, historicalMappings = [], }) {
32
- return (0, nockHelpers_1.mockGqlRequest)({
33
- name: 'GithubConfigOptions',
34
- statusCode: 200,
35
- body: {
36
- data: {
37
- viewer: {
38
- login: viewerLogin,
39
- },
40
- repository: {
41
- isFork: false,
42
- parent: null,
43
- ref: refName ? { name: refName } : null,
44
- defaultBranchRef: {
45
- name: defaultBranchRef,
46
- target: {
47
- history: {
48
- edges: historicalMappings.map(({ committedDate, branchLabelMapping }) => {
49
- return {
50
- remoteConfig: {
51
- committedDate,
52
- file: {
53
- object: {
54
- text: JSON.stringify({
55
- branchLabelMapping,
56
- }),
57
- },
58
- },
59
- },
60
- };
61
- }),
62
- },
63
- },
64
- },
65
- },
66
- },
67
- },
68
- });
69
- }
70
31
  const defaultConfigs = {
71
32
  projectConfig: {
72
33
  // use localhost to avoid CORS issues with nock
@@ -103,72 +64,39 @@ describe('getOptions', () => {
103
64
  `);
104
65
  });
105
66
  it('when `targetBranches`, `targetBranchChoices` and `branchLabelMapping` are all empty', async () => {
106
- (0, mockConfigFiles_1.mockConfigFiles)({
107
- projectConfig: {
108
- ...defaultConfigs.projectConfig,
109
- targetBranchChoices: undefined,
110
- branchLabelMapping: undefined,
111
- },
112
- globalConfig: { accessToken: 'abc' },
67
+ mockProjectConfig({
68
+ targetBranches: undefined,
69
+ targetBranchChoices: undefined,
70
+ branchLabelMapping: undefined,
113
71
  });
114
72
  await expect(() => (0, options_1.getOptions)([])).rejects
115
73
  .toThrowErrorMatchingInlineSnapshot(`
116
- "Please specify a target branch: \\"--branch 6.1\\".
74
+ "Please specify a target branch: \\"--branch 6.1\\".
117
75
 
118
- Read more: https://github.com/sqren/backport/blob/main/docs/configuration.md#project-config-backportrcjson"
76
+ Read more: https://github.com/sqren/backport/blob/main/docs/configuration.md#project-config-backportrcjson"
119
77
  `);
120
78
  });
121
79
  it('when repoName is missing', async () => {
122
- (0, mockConfigFiles_1.mockConfigFiles)({
123
- projectConfig: {
124
- ...defaultConfigs.projectConfig,
125
- repoName: '',
126
- },
127
- globalConfig: { accessToken: 'abc' },
128
- });
80
+ mockProjectConfig({ repoName: '' });
129
81
  await expect(() => (0, options_1.getOptions)([])).rejects
130
82
  .toThrowErrorMatchingInlineSnapshot(`
131
- "Please specify a repo name: \\"--repo-name kibana\\".
83
+ "Please specify a repo name: \\"--repo-name kibana\\".
132
84
 
133
85
  Read more: https://github.com/sqren/backport/blob/main/docs/configuration.md#project-config-backportrcjson"
134
86
  `);
135
87
  });
136
88
  it('when repoOwner is missing', async () => {
137
- (0, mockConfigFiles_1.mockConfigFiles)({
138
- projectConfig: {
139
- ...defaultConfigs.projectConfig,
140
- repoOwner: '',
141
- },
142
- globalConfig: { accessToken: 'abc' },
143
- });
89
+ mockProjectConfig({ repoOwner: '' });
144
90
  await expect(() => (0, options_1.getOptions)([])).rejects
145
91
  .toThrowErrorMatchingInlineSnapshot(`
146
- "Please specify a repo owner: \\"--repo-owner elastic\\".
92
+ "Please specify a repo owner: \\"--repo-owner elastic\\".
147
93
 
148
94
  Read more: https://github.com/sqren/backport/blob/main/docs/configuration.md#project-config-backportrcjson"
149
95
  `);
150
96
  });
151
97
  });
152
- describe('sourceBranch', () => {
153
- beforeEach(() => {
154
- mockGithubConfigOptions({ defaultBranchRef: 'some-default-branch' });
155
- });
156
- it('uses the `defaultBranchRef` as default', async () => {
157
- const options = await (0, options_1.getOptions)([]);
158
- expect(options.sourceBranch).toBe('some-default-branch');
159
- });
160
- it('uses the sourceBranch given via cli instead of `defaultBranchRef`', async () => {
161
- const options = await (0, options_1.getOptions)([
162
- '--source-branch',
163
- 'cli-source-branch',
164
- ]);
165
- expect(options.sourceBranch).toBe('cli-source-branch');
166
- });
167
- });
168
98
  it('should ensure that "backport" branch does not exist', async () => {
169
- mockGithubConfigOptions({
170
- refName: 'backport',
171
- });
99
+ mockGithubConfigOptions({ refName: 'backport' });
172
100
  await expect((0, options_1.getOptions)([])).rejects.toThrowError('You must delete the branch "backport" to continue. See https://github.com/sqren/backport/issues/155 for details');
173
101
  });
174
102
  it('should merge config options and module options', async () => {
@@ -184,6 +112,7 @@ describe('getOptions', () => {
184
112
  });
185
113
  it('should return options', async () => {
186
114
  mockGithubConfigOptions({
115
+ viewerLogin: 'john.diller',
187
116
  defaultBranchRef: 'default-branch-from-github',
188
117
  historicalMappings: [
189
118
  {
@@ -199,7 +128,7 @@ describe('getOptions', () => {
199
128
  autoAssign: false,
200
129
  autoMerge: false,
201
130
  autoMergeMethod: 'merge',
202
- authenticatedUsername: 'sqren',
131
+ authenticatedUsername: 'john.diller',
203
132
  branchLabelMapping: {
204
133
  foo: 'bar',
205
134
  },
@@ -216,7 +145,6 @@ describe('getOptions', () => {
216
145
  committedDate: '2022-01-02T20:52:45.173Z',
217
146
  },
218
147
  ],
219
- mainline: 1,
220
148
  maxNumber: 10,
221
149
  multipleBranches: true,
222
150
  multipleCommits: false,
@@ -230,13 +158,29 @@ describe('getOptions', () => {
230
158
  targetBranchChoices: ['7.9', '8.0'],
231
159
  targetBranches: [],
232
160
  targetPRLabels: [],
233
- author: 'sqren',
161
+ author: 'john.diller',
234
162
  verbose: false,
235
163
  });
236
164
  });
165
+ describe('sourceBranch', () => {
166
+ beforeEach(() => {
167
+ mockGithubConfigOptions({ defaultBranchRef: 'some-default-branch' });
168
+ });
169
+ it('uses the `defaultBranchRef` as default', async () => {
170
+ const options = await (0, options_1.getOptions)([]);
171
+ expect(options.sourceBranch).toBe('some-default-branch');
172
+ });
173
+ it('uses the sourceBranch given via cli instead of `defaultBranchRef`', async () => {
174
+ const options = await (0, options_1.getOptions)([
175
+ '--source-branch',
176
+ 'cli-source-branch',
177
+ ]);
178
+ expect(options.sourceBranch).toBe('cli-source-branch');
179
+ });
180
+ });
237
181
  describe('fork', () => {
238
182
  beforeEach(() => {
239
- mockGithubConfigOptions({ viewerLogin: 'billy.bob' });
183
+ mockGithubConfigOptions({});
240
184
  });
241
185
  it('is enabled by default', async () => {
242
186
  const { fork } = await (0, options_1.getOptions)([]);
@@ -247,37 +191,42 @@ describe('getOptions', () => {
247
191
  expect(fork).toBe(false);
248
192
  });
249
193
  it('can be disabled via config file', async () => {
250
- (0, mockConfigFiles_1.mockConfigFiles)({
251
- globalConfig: { accessToken: 'abc' },
252
- projectConfig: {
253
- ...defaultConfigs.projectConfig,
254
- fork: false,
255
- },
256
- });
194
+ mockProjectConfig({ fork: false });
257
195
  const { fork } = await (0, options_1.getOptions)([]);
258
196
  expect(fork).toBe(false);
259
197
  });
260
198
  });
261
199
  describe('reviewers', () => {
262
200
  beforeEach(() => {
263
- mockGithubConfigOptions({ viewerLogin: 'billy.bob' });
201
+ mockGithubConfigOptions({});
264
202
  });
265
203
  it('can be set via `--reviewer` flag', async () => {
266
204
  const { reviewers } = await (0, options_1.getOptions)(['--reviewer', 'peter']);
267
205
  expect(reviewers).toEqual(['peter']);
268
206
  });
269
207
  it('can be set via config file', async () => {
270
- (0, mockConfigFiles_1.mockConfigFiles)({
271
- globalConfig: { accessToken: 'abc' },
272
- projectConfig: {
273
- ...defaultConfigs.projectConfig,
274
- reviewers: ['john'],
275
- },
276
- });
208
+ mockProjectConfig({ reviewers: ['john'] });
277
209
  const { reviewers } = await (0, options_1.getOptions)([]);
278
210
  expect(reviewers).toEqual(['john']);
279
211
  });
280
212
  });
213
+ describe('mainline', () => {
214
+ beforeEach(() => {
215
+ mockGithubConfigOptions({});
216
+ });
217
+ it('is not enabled by default', async () => {
218
+ const { mainline } = await (0, options_1.getOptions)([]);
219
+ expect(mainline).toBe(undefined);
220
+ });
221
+ it('can be set via `--mainline` flag', async () => {
222
+ const { mainline } = await (0, options_1.getOptions)(['--mainline']);
223
+ expect(mainline).toBe(1);
224
+ });
225
+ it('accepts numeric values', async () => {
226
+ const { mainline } = await (0, options_1.getOptions)(['--mainline', '2']);
227
+ expect(mainline).toBe(2);
228
+ });
229
+ });
281
230
  describe('author', () => {
282
231
  beforeEach(() => {
283
232
  mockGithubConfigOptions({ viewerLogin: 'billy.bob' });
@@ -295,24 +244,12 @@ describe('getOptions', () => {
295
244
  expect(author).toBe(null);
296
245
  });
297
246
  it('can be reset via config file (similar to `--all` flag)', async () => {
298
- (0, mockConfigFiles_1.mockConfigFiles)({
299
- globalConfig: { accessToken: 'abc' },
300
- projectConfig: {
301
- ...defaultConfigs.projectConfig,
302
- author: null,
303
- },
304
- });
247
+ mockProjectConfig({ author: null });
305
248
  const { author } = await (0, options_1.getOptions)([]);
306
249
  expect(author).toBe(null);
307
250
  });
308
251
  it('can be overridden via config file', async () => {
309
- (0, mockConfigFiles_1.mockConfigFiles)({
310
- globalConfig: { accessToken: 'abc' },
311
- projectConfig: {
312
- ...defaultConfigs.projectConfig,
313
- author: 'jane.doe',
314
- },
315
- });
252
+ mockProjectConfig({ author: 'jane.doe' });
316
253
  const { author } = await (0, options_1.getOptions)([]);
317
254
  expect(author).toBe('jane.doe');
318
255
  });
@@ -330,16 +267,66 @@ describe('getOptions', () => {
330
267
  expect(cherrypickRef).toBe(false);
331
268
  });
332
269
  it('should be settable via config file', async () => {
333
- const { cherrypickRef } = await (0, options_1.getOptions)([], {
334
- cherrypickRef: false,
335
- });
270
+ mockProjectConfig({ cherrypickRef: false });
271
+ const { cherrypickRef } = await (0, options_1.getOptions)([]);
336
272
  expect(cherrypickRef).toBe(false);
337
273
  });
338
274
  it('cli args overwrites config', async () => {
339
- const { cherrypickRef } = await (0, options_1.getOptions)(['--cherrypick-ref'], {
340
- cherrypickRef: false,
341
- });
275
+ mockProjectConfig({ cherrypickRef: false });
276
+ const { cherrypickRef } = await (0, options_1.getOptions)(['--cherrypick-ref']);
342
277
  expect(cherrypickRef).toBe(true);
343
278
  });
344
279
  });
345
280
  });
281
+ function mockProjectConfig(projectConfig) {
282
+ return (0, mockConfigFiles_1.mockConfigFiles)({
283
+ globalConfig: { accessToken: 'abc' },
284
+ projectConfig: {
285
+ // use localhost to avoid CORS issues with nock
286
+ githubApiBaseUrlV4: 'http://localhost/graphql',
287
+ repoOwner: 'elastic',
288
+ repoName: 'kibana',
289
+ targetBranchChoices: ['7.9', '8.0'],
290
+ ...projectConfig,
291
+ },
292
+ });
293
+ }
294
+ function mockGithubConfigOptions({ viewerLogin = 'DO_NOT_USE-sqren', defaultBranchRef = 'DO_NOT_USE-default-branch-name', refName, historicalMappings = [], }) {
295
+ return (0, nockHelpers_1.mockGqlRequest)({
296
+ name: 'GithubConfigOptions',
297
+ statusCode: 200,
298
+ body: {
299
+ data: {
300
+ viewer: {
301
+ login: viewerLogin,
302
+ },
303
+ repository: {
304
+ isFork: false,
305
+ parent: null,
306
+ ref: refName ? { name: refName } : null,
307
+ defaultBranchRef: {
308
+ name: defaultBranchRef,
309
+ target: {
310
+ history: {
311
+ edges: historicalMappings.map(({ committedDate, branchLabelMapping }) => {
312
+ return {
313
+ remoteConfig: {
314
+ committedDate,
315
+ file: {
316
+ object: {
317
+ text: JSON.stringify({
318
+ branchLabelMapping,
319
+ }),
320
+ },
321
+ },
322
+ },
323
+ };
324
+ }),
325
+ },
326
+ },
327
+ },
328
+ },
329
+ },
330
+ },
331
+ });
332
+ }
@@ -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;
@@ -28,6 +28,7 @@ export declare function getOptionsFromGithub(options: {
28
28
  }) => boolean | Promise<boolean>) | undefined;
29
29
  autoMerge?: boolean | undefined;
30
30
  autoMergeMethod?: string | undefined;
31
+ backportBinary?: string | undefined;
31
32
  cherrypickRef?: boolean | undefined;
32
33
  ci?: boolean | undefined;
33
34
  commitPaths?: string[] | undefined;
@@ -38,7 +38,7 @@ describe('inquirer cli', () => {
38
38
  ]);
39
39
  expect(res).toMatchInlineSnapshot(`
40
40
  "Please specify a target branch: \\"--branch 6.1\\".
41
- Read more: https://github.com/sqren/backport/blob/main/docs/configuration.md#project-config-backportrcjson"
41
+ Read more: https://github.com/sqren/backport/blob/main/docs/configuration.md#project-config-backportrcjson"
42
42
  `);
43
43
  });
44
44
  it('should list commits based on .git/config when `repoOwner`/`repoName` is missing', async () => {
@@ -49,20 +49,9 @@ describe('inquirer cli', () => {
49
49
  '--accessToken',
50
50
  devAccessToken,
51
51
  ]);
52
- expect(res).toMatchInlineSnapshot(`
53
- "? Select commit (Use arrow keys)
54
- ❯ 1. v6.0.0
55
- 2. Bump dependencies
56
- 3. Add support for historical branch label mappings (#282)
57
- 4. Add status comment (#281)
58
- 5. Add \`--reviewer\` option (#280)
59
- 6. By default append \\"(cherry picked from commit...)\\" to commit message. Disab
60
- le with \`--no-cherrypick-ref\` (#279)
61
- 7. Improve git unit tests (#278)
62
- 8. Add tests for \`getCommitsWithoutBackports\`
63
- 9. Add Details View and \`--details\` flag (#277)
64
- 10.Feature: Show hint about missing backports (#276)"
65
- `);
52
+ const lineCount = res.split('\n').length;
53
+ expect(lineCount).toBe(12);
54
+ expect(res.includes('Select commit (Use arrow keys)')).toBe(true);
66
55
  });
67
56
  it('should return error when access token is invalid', async () => {
68
57
  const res = await runBackportAsync([
@@ -9,13 +9,4 @@ export declare function cherrypickAndCreateTargetPullRequest({ options, commits,
9
9
  number: number;
10
10
  didUpdate: boolean;
11
11
  }>;
12
- export declare function getCommitsWithoutBackports({ options, commit, targetBranch, conflictingFiles, }: {
13
- options: ValidConfigOptions;
14
- commit: Commit;
15
- targetBranch: string;
16
- conflictingFiles: string[];
17
- }): Promise<{
18
- formatted: string;
19
- commit: Commit;
20
- }[]>;
21
12
  export declare function getBackportBranchName(targetBranch: string, commits: Commit[]): string;
@@ -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.getBackportBranchName = exports.getCommitsWithoutBackports = exports.cherrypickAndCreateTargetPullRequest = void 0;
6
+ exports.getBackportBranchName = exports.cherrypickAndCreateTargetPullRequest = void 0;
7
7
  const chalk_1 = __importDefault(require("chalk"));
8
8
  const lodash_1 = require("lodash");
9
9
  const ora = require("ora");
@@ -17,10 +17,10 @@ const addLabelsToPullRequest_1 = require("../services/github/v3/addLabelsToPullR
17
17
  const addReviewersToPullRequest_1 = require("../services/github/v3/addReviewersToPullRequest");
18
18
  const createPullRequest_1 = require("../services/github/v3/createPullRequest");
19
19
  const enablePullRequestAutoMerge_1 = require("../services/github/v4/enablePullRequestAutoMerge");
20
- const fetchCommitsByAuthor_1 = require("../services/github/v4/fetchCommits/fetchCommitsByAuthor");
21
20
  const logger_1 = require("../services/logger");
22
21
  const prompts_1 = require("../services/prompts");
23
22
  const sequentially_1 = require("../services/sequentially");
23
+ const getCommitsWithoutBackports_1 = require("./getCommitsWithoutBackports");
24
24
  async function cherrypickAndCreateTargetPullRequest({ options, commits, targetBranch, }) {
25
25
  const backportBranch = getBackportBranchName(targetBranch, commits);
26
26
  const repoForkOwner = (0, git_1.getRepoForkOwner)(options);
@@ -83,44 +83,6 @@ async function backportViaFilesystem({ options, prPayload, commits, targetBranch
83
83
  await (0, git_1.deleteBackportBranch)({ options, backportBranch });
84
84
  return (0, createPullRequest_1.createPullRequest)({ options, prPayload });
85
85
  }
86
- // when the user is facing a git conflict we should help them understand
87
- // why the conflict occurs. In many cases it's because one or more commits haven't been backported yet
88
- async function getCommitsWithoutBackports({ options, commit, targetBranch, conflictingFiles, }) {
89
- const commitsInConflictingPaths = await (0, fetchCommitsByAuthor_1.fetchCommitsByAuthor)({
90
- ...options,
91
- author: null,
92
- commitPaths: conflictingFiles,
93
- });
94
- return (await Promise.all(commitsInConflictingPaths
95
- .filter((c) => {
96
- // exclude the commit we are currently trying to backport
97
- if (c.sha === commit.sha) {
98
- return false;
99
- }
100
- // exclude commits that are newer than the commit we are trying to backport
101
- if (c.committedDate > commit.committedDate) {
102
- return false;
103
- }
104
- const alreadyBackported = c.expectedTargetPullRequests.some((pr) => pr.branch === targetBranch && pr.state === 'MERGED');
105
- if (alreadyBackported) {
106
- return false;
107
- }
108
- return true;
109
- })
110
- .slice(0, 10) // limit to max 10 commits
111
- .map(async (c) => {
112
- const isCommitInBranch = await (0, git_1.getIsCommitInBranch)(options, c.sha);
113
- return { c, isCommitInBranch };
114
- })))
115
- .filter(({ isCommitInBranch }) => !isCommitInBranch)
116
- .map(({ c }) => {
117
- // get pull request for the target branch (if it exists)
118
- const unmergedPr = c.expectedTargetPullRequests.find((pr) => pr.branch === targetBranch);
119
- const formatted = ` - ${(0, commitFormatters_1.getFirstLine)(c.originalMessage)}${unmergedPr?.state === 'OPEN' ? chalk_1.default.gray(' (backport pending)') : ''}${c.pullUrl ? `\n ${c.pullUrl}` : ''}`;
120
- return { formatted, commit: c };
121
- });
122
- }
123
- exports.getCommitsWithoutBackports = getCommitsWithoutBackports;
124
86
  /*
125
87
  * Returns the name of the backport branch without remote name
126
88
  *
@@ -177,23 +139,23 @@ async function waitForCherrypick(options, commit, targetBranch) {
177
139
  }
178
140
  autoResolveSpinner.fail();
179
141
  }
180
- const commitsWithoutBackports = await getCommitsWithoutBackports({
142
+ const commitsWithoutBackports = await (0, getCommitsWithoutBackports_1.getCommitsWithoutBackports)({
181
143
  options,
182
144
  commit,
183
145
  targetBranch,
184
146
  conflictingFiles: conflictingFiles.map((f) => f.relative).slice(0, 50),
185
147
  });
186
- (0, logger_1.consoleLog)(chalk_1.default.bold('\nThe commit could not be backported due to conflicts\n'));
187
- if (commitsWithoutBackports.length > 0) {
188
- (0, logger_1.consoleLog)(chalk_1.default.italic(`Hint: Before fixing the conflicts manually you should consider backporting the following commits to "${targetBranch}":`));
189
- (0, logger_1.consoleLog)(`${commitsWithoutBackports.map((c) => c.formatted).join('\n')}\n\n`);
190
- }
191
148
  if (options.ci) {
192
149
  throw new HandledError_1.HandledError(`Commit could not be cherrypicked due to conflicts`, {
193
150
  type: 'commitsWithoutBackports',
194
151
  commitsWithoutBackports,
195
152
  });
196
153
  }
154
+ (0, logger_1.consoleLog)(chalk_1.default.bold('\nThe commit could not be backported due to conflicts\n'));
155
+ if (commitsWithoutBackports.length > 0) {
156
+ (0, logger_1.consoleLog)(chalk_1.default.italic(`Hint: Before fixing the conflicts manually you should consider backporting the following commits to "${targetBranch}":`));
157
+ (0, logger_1.consoleLog)(`${commitsWithoutBackports.map((c) => c.formatted).join('\n')}\n\n`);
158
+ }
197
159
  /*
198
160
  * Commit could not be cleanly cherrypicked: Initiating conflict resolution
199
161
  */
@@ -0,0 +1,11 @@
1
+ import { Commit } from '../entrypoint.module';
2
+ import { ValidConfigOptions } from '../options/options';
3
+ export declare function getCommitsWithoutBackports({ options, commit, targetBranch, conflictingFiles, }: {
4
+ options: ValidConfigOptions;
5
+ commit: Commit;
6
+ targetBranch: string;
7
+ conflictingFiles: string[];
8
+ }): Promise<{
9
+ formatted: string;
10
+ commit: Commit;
11
+ }[]>;
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getCommitsWithoutBackports = void 0;
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ const commitFormatters_1 = require("../services/github/commitFormatters");
9
+ const fetchCommitsByAuthor_1 = require("../services/github/v4/fetchCommits/fetchCommitsByAuthor");
10
+ // when the user is facing a git conflict we should help them understand
11
+ // why the conflict occurs. In many cases it's because one or more commits haven't been backported yet
12
+ async function getCommitsWithoutBackports({ options,
13
+ // commit that is being backported
14
+ commit,
15
+ // branch the commit is being backported to
16
+ targetBranch,
17
+ // the files with conflicts on the target branch
18
+ conflictingFiles, }) {
19
+ // commits on the source branch that also touched the conflicting files
20
+ const commitsInConflictingPaths = await (0, fetchCommitsByAuthor_1.fetchCommitsByAuthor)({
21
+ ...options,
22
+ author: null,
23
+ commitPaths: conflictingFiles,
24
+ });
25
+ return commitsInConflictingPaths
26
+ .filter((c) => {
27
+ // exclude the commit we are currently trying to backport
28
+ if (c.sha === commit.sha) {
29
+ return false;
30
+ }
31
+ // exclude commits that are newer than the commit we are trying to backport
32
+ if (c.committedDate > commit.committedDate) {
33
+ return false;
34
+ }
35
+ // only consider commits that have an associated pull request
36
+ if (!c.pullUrl) {
37
+ return false;
38
+ }
39
+ // only include commit if it has an unmerged PR for the given target branch
40
+ const hasUnmergedPr = c.expectedTargetPullRequests.some((pr) => pr.branch === targetBranch && pr.state !== 'MERGED');
41
+ return hasUnmergedPr;
42
+ })
43
+ .slice(0, 10) // limit to max 10 commits
44
+ .map((c) => {
45
+ // get pull request for the target branch (if it exists)
46
+ const pendingBackportPr = c.expectedTargetPullRequests.find((pr) => pr.branch === targetBranch && pr.state === 'OPEN');
47
+ const formatted = pendingBackportPr
48
+ ? ` - ${(0, commitFormatters_1.getFirstLine)(c.originalMessage)} ${chalk_1.default.gray('(backport pending)')}\n ${pendingBackportPr.url}`
49
+ : ` - ${(0, commitFormatters_1.getFirstLine)(c.originalMessage)} ${chalk_1.default.red('(backport missing)')}\n ${c.pullUrl}`;
50
+ return { formatted, commit: c };
51
+ });
52
+ }
53
+ exports.getCommitsWithoutBackports = getCommitsWithoutBackports;
package/package.json CHANGED
@@ -14,7 +14,7 @@
14
14
  "branches",
15
15
  "branching"
16
16
  ],
17
- "version": "6.1.1",
17
+ "version": "6.1.2",
18
18
  "main": "./dist/entrypoint.module.js",
19
19
  "types": "dist/entrypoint.module.d.ts",
20
20
  "bin": {