backport 8.4.0 → 8.4.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 (38) hide show
  1. package/README.md +11 -178
  2. package/dist/lib/author.d.ts +13 -0
  3. package/dist/lib/author.js +28 -0
  4. package/dist/lib/cherrypickAndCreateTargetPullRequest.js +50 -35
  5. package/dist/lib/cherrypickAndCreateTargetPullRequest.test.js +2 -0
  6. package/dist/lib/git.d.ts +11 -8
  7. package/dist/lib/git.js +32 -32
  8. package/dist/lib/git.private.test.js +13 -10
  9. package/dist/lib/git.test.js +52 -24
  10. package/dist/lib/github/v4/apiRequestV4.js +14 -8
  11. package/dist/lib/github/v4/fetchCommits/allFetchers.private.test.js +1 -0
  12. package/dist/lib/ora.d.ts +1 -0
  13. package/dist/options/options.js +2 -2
  14. package/dist/options/options.test.js +4 -4
  15. package/dist/test/e2e/cli/date-filters.private.test.js +1 -0
  16. package/dist/test/e2e/cli/different-merge-strategies.private.test.js +122 -6
  17. package/dist/test/e2e/cli/error-handling-interactive-mode.private.test.js +27 -13
  18. package/dist/test/e2e/cli/error-handling-non-interactive-mode.private.test.js +3 -2
  19. package/dist/test/e2e/cli/gracefully-handles-corrupt-repo.private.test.d.ts +1 -0
  20. package/dist/test/e2e/cli/gracefully-handles-corrupt-repo.private.test.js +52 -0
  21. package/dist/test/e2e/cli/repo-with-backportrc-removed.private.test.js +2 -2
  22. package/dist/test/e2e/cli/repo-with-programatically-added-commits.mutation.test.d.ts +1 -0
  23. package/dist/test/e2e/cli/repo-with-programatically-added-commits.mutation.test.js +114 -0
  24. package/dist/test/e2e/cli/runBackportViaCli.d.ts +8 -2
  25. package/dist/test/e2e/cli/runBackportViaCli.js +48 -18
  26. package/dist/test/e2e/cli/test-that-repo-can-be-cloned.private.test.js +7 -1
  27. package/dist/test/e2e/module/entrypoint.module.mutation.test.js +1 -1
  28. package/dist/test/handleUnbackportedPullRequests.private.test.js +1 -1
  29. package/dist/test/replaceStringAndLinebreaks.d.ts +5 -0
  30. package/dist/test/replaceStringAndLinebreaks.js +8 -0
  31. package/dist/test/sandbox.d.ts +1 -0
  32. package/dist/test/sandbox.js +8 -3
  33. package/dist/utils/packageVersion.d.ts +1 -1
  34. package/dist/utils/packageVersion.js +1 -1
  35. package/package.json +24 -24
  36. package/yarn.lock +886 -992
  37. package/dist/lib/getGitConfigAuthor.d.ts +0 -6
  38. package/dist/lib/getGitConfigAuthor.js +0 -15
package/README.md CHANGED
@@ -6,7 +6,7 @@
6
6
  <br>
7
7
  </div>
8
8
 
9
- ## 🎉 New! The Backport Tool as a Github Action 🎉
9
+ ## 🎉 New: The Backport Tool as a Github Action 🎉
10
10
 
11
11
  A [Github Action](https://github.com/sqren/backport-github-action) around The Backport Tool now exists. It makes it a breeze to get automatic backports when pull requests are merged.
12
12
 
@@ -33,7 +33,7 @@ The remaining documentation focuses on the Backport CLI tool (not the Github Act
33
33
  npm install -g backport
34
34
  ```
35
35
 
36
- After installation you should add an access token to the [global config](https://github.com/sqren/backport/blob/main/docs/configuration.md#global-config-backportconfigjson) in `~/.backport/config.json`. See the [documentation](https://github.com/sqren/backport/blob/main/docs/configuration.md#accesstoken-required) for how the access token is generated.
36
+ After installation you should add an access token to the [global config](/docs/config-file-options.md#global-config-backportconfigjson) in `~/.backport/config.json`. See the [documentation](/docs/config-file-options.md#accesstoken-required) for how the access token is generated.
37
37
 
38
38
  ## Quick start
39
39
 
@@ -41,7 +41,7 @@ After installation you should add an access token to the [global config](https:/
41
41
  npm install backport
42
42
  ```
43
43
 
44
- Add a [project config](https://github.com/sqren/backport/blob/main/docs/configuration.md#project-config-backportrcjson) to the root of your repository:
44
+ Add a [project config](/docs/config-file-options.md#project-config-backportrcjson) to the root of your repository:
45
45
 
46
46
  ```js
47
47
  // .backportrc.json
@@ -60,7 +60,7 @@ Add a [project config](https://github.com/sqren/backport/blob/main/docs/configur
60
60
  }
61
61
  ```
62
62
 
63
- Add personal access token to [global config](https://github.com/sqren/backport/blob/main/docs/configuration.md#global-config-backportconfigjson):
63
+ Add personal access token to [global config](/docs/config-file-options.md#global-config-backportconfigjson):
64
64
 
65
65
  ```js
66
66
  // ~/.backport/config.json
@@ -77,185 +77,24 @@ npx backport
77
77
 
78
78
  _This will start an interactive prompt. You can use your keyboards arrow keys to choose options, `<space>` to select checkboxes and `<enter>` to proceed._
79
79
 
80
- ### Config options
81
-
82
- See [configuration.md](https://github.com/sqren/backport/blob/main/docs/configuration.md)
83
-
84
- ### CLI options
85
-
86
- | Option | Shorthand notation | Description | Default |
87
- | ------------------- | ------------------ | -------------------------------------------------------------------------- | ------------------------- |
88
- | --access-token | | Github access token | |
89
- | --all | -a | Show commits from any author. Opposite of `--author` | false |
90
- | --assignee | --assign | Assign users to the target PR | |
91
- | --author | | Filter commits by Github username. Opposite of `--all` | _Current user_ |
92
- | --auto-assign | | Assign current user to the target PR | false |
93
- | --branch | -b | Target branch to backport to | |
94
- | --config-file | | Custom path to project config file (.backportrc.json) | |
95
- | --dir | | Clone repository into custom directory | ~/.backport/repositories/ |
96
- | --dry-run | | Perform backport without pushing to Github | false |
97
- | --editor | | Editor (eg. `code`) to open and resolve conflicts | nano |
98
- | --fork | | Create backports in fork repo | true |
99
- | --git-hostname | | Hostname for Git | github.com |
100
- | --interactive | | Enable interactive prompts | true |
101
- | --mainline | | Parent id of merge commit | 1 |
102
- | --max-number | --number, -n | Number of commits to choose from | 10 |
103
- | --multiple | | Multi-select for commits and branches | false |
104
- | --multiple-branches | | Multi-select for branches | true |
105
- | --multiple-commits | | Multi-select for commits | false |
106
- | --no-cherrypick-ref | | Do not append "(cherry picked from commit...)". [Git Docs][1] | false |
107
- | --no-status-comment | | Do not publish a status comment to Github with the results of the backport | false |
108
- | --no-verify | | Bypass the pre-commit and commit-msg hooks | false |
109
- | --path | -p | Filter commits by path | |
110
- | --pr-description | --description | Description for pull request | |
111
- | --pr-filter | | Find PRs using [Github's search syntax][2] | |
112
- | --pr-title | --title | Title of pull request | |
113
- | --pull-number | --pr | Backport pull request by number | |
114
- | --repo-fork-owner | | The owner of the fork where the backport branch is pushed. | _Current user_ |
115
- | --repo-name | | Name of repository | |
116
- | --repo-owner | | Owner of repository | |
117
- | --reset-author | | Set yourself as commit author | |
118
- | --reviewer | | Add reviewer to the target PR | |
119
- | --sha | | Sha of commit to backport | |
120
- | --source-branch | | Specify a non-default branch to backport from | |
121
- | --source-pr-label | | Labels added to the source PR | |
122
- | --target-branch | -b | Target branch(es) to backport to | |
123
- | --target-pr-label | --label, -l | Labels added to the target PR | |
124
- | --help | | Show help | |
125
- | -v, --version | | Show version number | |
126
-
127
- The CLI options will override the [configuration options](https://github.com/sqren/backport/blob/main/docs/configuration.md).
128
-
129
- ## Backport Module API
130
-
131
- `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/sqren/backport-github-action)
132
-
133
- ### `backportRun`
134
-
135
- Backport a commit programatically. Commits can be selected via `pullNumber` or `sha`.
136
-
137
- #### Arguments:
138
-
139
- 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:
140
-
141
- `accessToken` _string_ **(Required)**<br/>
142
- Github access token to authenticate the request
143
-
144
- `repoName` _string_ **(Required)**<br/>
145
- Name of repository
146
-
147
- `repoOwner` _string_ **(Required)**<br/>
148
- Owner of repository (organisation or username)
149
-
150
- `pullNumber` _number_<br/>
151
- Filter commits by pull request number
152
-
153
- `sha` _string_<br/>
154
- Filter commits by commit sha
155
-
156
- `interactive` _boolean_<br/>
157
- Enable interactive prompts
158
-
159
- #### Example
160
-
161
- ```ts
162
- import { backportRun } from 'backport';
163
-
164
- const result = await backportRun({
165
- options: {
166
- accessToken: 'very secret',
167
- repoName: 'kibana',
168
- repoOwner: 'elastic',
169
- pullNumber: 121633,
170
- interactive: false,
171
- },
172
- });
173
-
174
- console.log(result);
175
- ```
176
-
177
- ### `getCommits`
178
-
179
- Retrieve information about commits and whether they are backported
180
-
181
- #### Arguments:
182
-
183
- `accessToken` _string_ **(Required)**<br/>
184
- Github access token to authenticate the request
185
-
186
- `repoName` _string_ **(Required)**<br/>
187
- Name of repository
188
-
189
- `repoOwner` _string_ **(Required)**<br/>
190
- Owner of repository (organisation or username)
191
-
192
- `author` _string_<br/>
193
- Filter commits by Github user
194
-
195
- `pullNumber` _number_<br/>
196
- Filter commits by pull request number
197
-
198
- `sha` _string_<br/>
199
- Filter commits by commit sha
200
-
201
- `sourceBranch` _string_<br/>
202
- The branch to display commits from. Defaults to the default branch (normally "main" or "master")
203
-
204
- #### Example
205
-
206
- ```ts
207
- import { getCommits } from 'backport';
208
-
209
- const commits = await getCommits({
210
- accessToken: 'abc',
211
- repoName: 'kibana',
212
- repoOwner: 'elastic',
213
- pullNumber: 121633,
214
- });
215
-
216
- console.log(commits);
217
-
218
- /*
219
- [{
220
- soureCommit: {
221
- committedDate: '2021-12-20T14:20:16Z',
222
- sha: 'd421ddcf6157150596581c7885afa3690cec6339',
223
- message: '[APM] Add note about synthtrace to APM docs (#121633)',
224
- },
225
- sourcePullRequest: {
226
- number: 121633,
227
- url: 'https://github.com/elastic/kibana/pull/121633'
228
- mergeCommit: {
229
- sha: 'd421ddcf6157150596581c7885afa3690cec6339',
230
- message: '[APM] Add note about synthtrace to APM docs (#121633)',
231
- }
232
- },
233
- sourceBranch: 'main',
234
- expectedTargetPullRequests: [
235
- {
236
- url: 'https://github.com/elastic/kibana/pull/121643',
237
- number: 121643,
238
- branch: '8.0',
239
- state: 'MERGED'
240
- }
241
- ]
242
- }]
243
- */
244
- ```
80
+ ## Documentation
81
+ - [Config file options](/docs/config-file-options.md)
82
+ - [CLI options](/docs/cli-options.md)
83
+ - [Module API](/docs/api.md)
245
84
 
246
- ## What is backporting?
85
+ ### What is backporting?
247
86
 
248
87
  > Backporting is the action of taking parts from a newer version of a software system [..] and porting them to an older version of the same software. It forms part of the maintenance step in a software development process, and it is commonly used for fixing security issues in older versions of the software and also for providing new features to older versions.
249
88
 
250
89
  Source: [https://en.wikipedia.org/wiki/Backporting](https://en.wikipedia.org/wiki/Backporting)
251
90
 
252
- ## Who is this tool for?
91
+ ### Who is this tool for?
253
92
 
254
93
  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.
255
94
 
256
95
  `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.
257
96
 
258
- **Features:**
97
+ ### Features:
259
98
 
260
99
  - interactively backport one or more commits to one or more branches with an intuitive UI
261
100
  - ability to see which commits have been backported and to which branches
@@ -272,9 +111,3 @@ This tools is for anybody who is working on a codebase where they have to mainta
272
111
  ## Contributing
273
112
 
274
113
  See [CONTRIBUTING.md](https://github.com/sqren/backport/blob/master/CONTRIBUTING.md)
275
-
276
- [1]: https://git-scm.com/docs/git-cherry-pick#Documentation/git-cherry-pick.txt--x
277
- [2]: https://docs.github.com/en/search-github/getting-started-with-searching-on-github/understanding-the-search-syntax
278
-
279
- [![NPM version](https://img.shields.io/npm/v/backport.svg)](https://www.npmjs.com/package/backport)
280
- [![Coverage Status](https://coveralls.io/repos/github/sqren/backport/badge.svg?branch=master)](https://coveralls.io/github/sqren/backport?branch=master)
@@ -0,0 +1,13 @@
1
+ import { Commit } from '../entrypoint.module';
2
+ import { ValidConfigOptions } from '../options/options';
3
+ export declare type GitConfigAuthor = {
4
+ name?: string;
5
+ email?: string;
6
+ };
7
+ export declare function getGitConfigAuthor(options: ValidConfigOptions): Promise<GitConfigAuthor | undefined>;
8
+ export declare type CommitAuthor = Required<GitConfigAuthor>;
9
+ export declare function getCommitAuthor({ options, commit, gitConfigAuthor, }: {
10
+ options: ValidConfigOptions;
11
+ commit: Commit;
12
+ gitConfigAuthor?: GitConfigAuthor;
13
+ }): CommitAuthor;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getCommitAuthor = exports.getGitConfigAuthor = void 0;
4
+ const git_1 = require("./git");
5
+ async function getGitConfigAuthor(options) {
6
+ const localRepoPath = await (0, git_1.getLocalSourceRepoPath)(options);
7
+ if (!localRepoPath) {
8
+ return;
9
+ }
10
+ return {
11
+ name: await (0, git_1.getGitConfig)({ dir: localRepoPath, key: 'user.name' }),
12
+ email: await (0, git_1.getGitConfig)({ dir: localRepoPath, key: 'user.email' }),
13
+ };
14
+ }
15
+ exports.getGitConfigAuthor = getGitConfigAuthor;
16
+ function getCommitAuthor({ options, commit, gitConfigAuthor, }) {
17
+ if (options.resetAuthor) {
18
+ return {
19
+ name: options.authenticatedUsername,
20
+ email: `<${options.authenticatedUsername}@users.noreply.github.com>`,
21
+ };
22
+ }
23
+ return {
24
+ name: options.gitAuthorName ?? gitConfigAuthor?.name ?? commit.author.name,
25
+ email: options.gitAuthorEmail ?? gitConfigAuthor?.email ?? commit.author.email,
26
+ };
27
+ }
28
+ exports.getCommitAuthor = getCommitAuthor;
@@ -7,10 +7,10 @@ exports.cherrypickAndCreateTargetPullRequest = void 0;
7
7
  const chalk_1 = __importDefault(require("chalk"));
8
8
  const lodash_1 = require("lodash");
9
9
  const BackportError_1 = require("./BackportError");
10
+ const author_1 = require("./author");
10
11
  const child_process_promisified_1 = require("./child-process-promisified");
11
12
  const env_1 = require("./env");
12
13
  const getCommitsWithoutBackports_1 = require("./getCommitsWithoutBackports");
13
- const getGitConfigAuthor_1 = require("./getGitConfigAuthor");
14
14
  const git_1 = require("./git");
15
15
  const commitFormatters_1 = require("./github/commitFormatters");
16
16
  const addAssigneesToPullRequest_1 = require("./github/v3/addAssigneesToPullRequest");
@@ -18,19 +18,33 @@ const addLabelsToPullRequest_1 = require("./github/v3/addLabelsToPullRequest");
18
18
  const addReviewersToPullRequest_1 = require("./github/v3/addReviewersToPullRequest");
19
19
  const createPullRequest_1 = require("./github/v3/createPullRequest");
20
20
  const enablePullRequestAutoMerge_1 = require("./github/v4/enablePullRequestAutoMerge");
21
+ const fetchCommitBySha_1 = require("./github/v4/fetchCommits/fetchCommitBySha");
21
22
  const logger_1 = require("./logger");
22
23
  const ora_1 = require("./ora");
23
24
  const prompts_1 = require("./prompts");
24
25
  const sequentially_1 = require("./sequentially");
26
+ function getSourceBranchFromCommits(commits) {
27
+ // sourceBranch should be the same for all commits, so picking `sourceBranch` from the first commit should be fine 🤞
28
+ // this is specifically needed when backporting a PR like `backport --pr 123` and the source PR was merged to a non-default (aka non-master) branch.
29
+ const { sourceBranch } = commits[0];
30
+ return sourceBranch;
31
+ }
25
32
  async function cherrypickAndCreateTargetPullRequest({ options, commits, targetBranch, }) {
26
33
  const backportBranch = getBackportBranchName(targetBranch, commits);
27
34
  const repoForkOwner = (0, git_1.getRepoForkOwner)(options);
28
35
  (0, logger_1.consoleLog)(`\n${chalk_1.default.bold(`Backporting to ${targetBranch}:`)}`);
36
+ const sourceBranch = getSourceBranchFromCommits(commits);
29
37
  const [gitConfigAuthor] = await Promise.all([
30
- (0, getGitConfigAuthor_1.getGitConfigAuthor)(options),
31
- (0, git_1.createBackportBranch)({ options, targetBranch, backportBranch }),
38
+ (0, author_1.getGitConfigAuthor)(options),
39
+ (0, git_1.createBackportBranch)({
40
+ options,
41
+ sourceBranch,
42
+ targetBranch,
43
+ backportBranch,
44
+ }),
32
45
  ]);
33
- await (0, sequentially_1.sequentially)(commits, (commit) => waitForCherrypick(options, commit, targetBranch, gitConfigAuthor));
46
+ const commitsFlattened = (0, lodash_1.flatten)(await Promise.all(commits.map((c) => getMergeCommits(options, c))));
47
+ await (0, sequentially_1.sequentially)(commitsFlattened, (commit) => waitForCherrypick(options, commit, targetBranch, gitConfigAuthor));
34
48
  if (options.dryRun) {
35
49
  (0, ora_1.ora)(options.interactive).succeed('Dry run complete');
36
50
  return { url: 'https://localhost/dry-run', didUpdate: false, number: 1337 };
@@ -78,6 +92,17 @@ async function cherrypickAndCreateTargetPullRequest({ options, commits, targetBr
78
92
  return targetPullRequest;
79
93
  }
80
94
  exports.cherrypickAndCreateTargetPullRequest = cherrypickAndCreateTargetPullRequest;
95
+ async function getMergeCommits(options, commit) {
96
+ const { sha } = commit.sourceCommit;
97
+ if (!options.mainline) {
98
+ const isMergeCommit = await (0, git_1.getIsMergeCommit)(options, sha);
99
+ if (isMergeCommit) {
100
+ const shas = await (0, git_1.getShasInMergeCommit)(options, sha);
101
+ return Promise.all(shas.reverse().map((sha) => (0, fetchCommitBySha_1.fetchCommitBySha)({ ...options, sha })));
102
+ }
103
+ }
104
+ return [commit];
105
+ }
81
106
  /*
82
107
  * Returns the name of the backport branch without remote name
83
108
  *
@@ -97,18 +122,32 @@ function getBackportBranchName(targetBranch, commits) {
97
122
  }
98
123
  async function waitForCherrypick(options, commit, targetBranch, gitConfigAuthor) {
99
124
  const spinnerText = `Cherry-picking: ${chalk_1.default.greenBright((0, commitFormatters_1.getFirstLine)(commit.sourceCommit.message))}`;
100
- const mergedTargetPullRequest = commit.expectedTargetPullRequests.find((pr) => pr.state === 'MERGED' && pr.branch === targetBranch);
101
125
  const cherrypickSpinner = (0, ora_1.ora)(options.interactive, spinnerText).start();
102
- let conflictingFiles;
103
- let unstagedFiles;
104
- let needsResolving;
105
- const commitAuthor = getCommitAuthor({
126
+ const commitAuthor = (0, author_1.getCommitAuthor)({ options, commit, gitConfigAuthor });
127
+ await cherrypickAndHandleConflicts({
106
128
  options,
107
- gitConfigAuthor,
108
129
  commit,
130
+ commitAuthor,
131
+ targetBranch,
132
+ cherrypickSpinner,
109
133
  });
134
+ // Conflicts should be resolved and files staged at this point
135
+ try {
136
+ // Run `git commit` in case conflicts were not manually committed
137
+ await (0, git_1.commitChanges)({ options, commit, commitAuthor });
138
+ cherrypickSpinner.succeed();
139
+ }
140
+ catch (e) {
141
+ cherrypickSpinner.fail();
142
+ throw e;
143
+ }
144
+ }
145
+ async function cherrypickAndHandleConflicts({ options, commit, commitAuthor, targetBranch, cherrypickSpinner, }) {
146
+ const mergedTargetPullRequest = commit.expectedTargetPullRequests.find((pr) => pr.state === 'MERGED' && pr.branch === targetBranch);
147
+ let conflictingFiles;
148
+ let unstagedFiles;
149
+ let needsResolving;
110
150
  try {
111
- await (0, git_1.fetchBranch)(options, commit.sourceBranch);
112
151
  ({ conflictingFiles, unstagedFiles, needsResolving } = await (0, git_1.cherrypick)({
113
152
  options,
114
153
  sha: commit.sourceCommit.sha,
@@ -117,7 +156,6 @@ async function waitForCherrypick(options, commit, targetBranch, gitConfigAuthor)
117
156
  }));
118
157
  // no conflicts encountered
119
158
  if (!needsResolving) {
120
- cherrypickSpinner.succeed();
121
159
  return;
122
160
  }
123
161
  // cherrypick failed due to conflicts
@@ -179,17 +217,6 @@ async function waitForCherrypick(options, commit, targetBranch, gitConfigAuthor)
179
217
  conflictingFiles: conflictingFiles.map((f) => f.absolute),
180
218
  unstagedFiles,
181
219
  });
182
- // Conflicts should be resolved and files staged at this point
183
- const stagingSpinner = (0, ora_1.ora)(options.interactive, `Finalizing cherrypick`).start();
184
- try {
185
- // Run `git commit`
186
- await (0, git_1.commitChanges)(commit, options);
187
- stagingSpinner.succeed();
188
- }
189
- catch (e) {
190
- stagingSpinner.fail();
191
- throw e;
192
- }
193
220
  }
194
221
  async function listConflictingAndUnstagedFiles({ retries, options, conflictingFiles, unstagedFiles, }) {
195
222
  const hasUnstagedFiles = !(0, lodash_1.isEmpty)((0, lodash_1.difference)(unstagedFiles, conflictingFiles));
@@ -228,15 +255,3 @@ async function listConflictingAndUnstagedFiles({ retries, options, conflictingFi
228
255
  unstagedFiles: _unstagedFiles,
229
256
  });
230
257
  }
231
- function getCommitAuthor({ options, gitConfigAuthor, commit, }) {
232
- if (options.resetAuthor) {
233
- return {
234
- name: options.authenticatedUsername,
235
- email: `<${options.authenticatedUsername}@users.noreply.github.com>`,
236
- };
237
- }
238
- return {
239
- name: options.gitAuthorName ?? gitConfigAuthor?.name ?? commit.author.name,
240
- email: options.gitAuthorEmail ?? gitConfigAuthor?.email ?? commit.author.email,
241
- };
242
- }
@@ -63,6 +63,8 @@ describe('cherrypickAndCreateTargetPullRequest', () => {
63
63
  const options = {
64
64
  assignees: [],
65
65
  authenticatedUsername: 'sqren_authenticated',
66
+ gitAuthorName: 'Soren L',
67
+ gitAuthorEmail: 'soren@louv.dk',
66
68
  author: 'sqren',
67
69
  fork: true,
68
70
  interactive: true,
package/dist/lib/git.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { ValidConfigOptions } from '../options/options';
2
+ import { CommitAuthor } from './author';
2
3
  import { ExpectedTargetPullRequest } from './sourceCommit/getExpectedTargetPullRequests';
3
4
  import { Commit } from './sourceCommit/parseSourceCommit';
4
5
  export declare function getRemoteUrl({ repoName, accessToken, gitHostname }: ValidConfigOptions, repoOwner: string): string;
@@ -27,15 +28,12 @@ export declare function deleteRemote(options: ValidConfigOptions, remoteName: st
27
28
  export declare function addRemote(options: ValidConfigOptions, remoteName: string): Promise<void>;
28
29
  export declare function fetchBranch(options: ValidConfigOptions, branch: string): Promise<void>;
29
30
  export declare function getIsMergeCommit(options: ValidConfigOptions, sha: string): Promise<boolean>;
30
- export declare function getCommitsInMergeCommit(options: ValidConfigOptions, sha: string): Promise<string[]>;
31
+ export declare function getShasInMergeCommit(options: ValidConfigOptions, sha: string): Promise<string[]>;
31
32
  export declare function cherrypick({ options, sha, mergedTargetPullRequest, commitAuthor, }: {
32
33
  options: ValidConfigOptions;
33
34
  sha: string;
34
35
  mergedTargetPullRequest?: ExpectedTargetPullRequest;
35
- commitAuthor: {
36
- name: string;
37
- email: string;
38
- };
36
+ commitAuthor: CommitAuthor;
39
37
  }): Promise<{
40
38
  conflictingFiles: {
41
39
  absolute: string;
@@ -44,7 +42,11 @@ export declare function cherrypick({ options, sha, mergedTargetPullRequest, comm
44
42
  unstagedFiles: string[];
45
43
  needsResolving: boolean;
46
44
  }>;
47
- export declare function commitChanges(commit: Commit, options: ValidConfigOptions): Promise<void>;
45
+ export declare function commitChanges({ options, commit, commitAuthor, }: {
46
+ options: ValidConfigOptions;
47
+ commit: Commit;
48
+ commitAuthor: CommitAuthor;
49
+ }): Promise<void>;
48
50
  export declare type ConflictingFiles = Awaited<ReturnType<typeof getConflictingFiles>>;
49
51
  export declare function getConflictingFiles(options: ValidConfigOptions): Promise<{
50
52
  absolute: string;
@@ -55,10 +57,11 @@ export declare function getGitConfig({ dir, key, }: {
55
57
  dir: string;
56
58
  key: 'user.name' | 'user.email';
57
59
  }): Promise<string | undefined>;
58
- export declare function createBackportBranch({ options, targetBranch, backportBranch, }: {
60
+ export declare function createBackportBranch({ options, sourceBranch, backportBranch, targetBranch, }: {
59
61
  options: ValidConfigOptions;
60
- targetBranch: string;
62
+ sourceBranch: string;
61
63
  backportBranch: string;
64
+ targetBranch: string;
62
65
  }): Promise<void>;
63
66
  export declare function deleteBackportBranch({ options, backportBranch, }: {
64
67
  options: ValidConfigOptions;
package/dist/lib/git.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getLocalSourceRepoPath = exports.pushBackportBranch = exports.getRepoForkOwner = exports.deleteBackportBranch = exports.createBackportBranch = exports.getGitConfig = exports.getUnstagedFiles = exports.getConflictingFiles = exports.commitChanges = exports.cherrypick = exports.getCommitsInMergeCommit = exports.getIsMergeCommit = exports.fetchBranch = exports.addRemote = exports.deleteRemote = exports.getIsCommitInBranch = exports.getGitProjectRootPath = exports.getRepoInfoFromGitRemotes = exports.isLocalConfigFileModified = exports.isLocalConfigFileUntracked = exports.getLocalConfigFileCommitDate = exports.cloneRepo = exports.getRemoteUrl = void 0;
3
+ exports.getLocalSourceRepoPath = exports.pushBackportBranch = exports.getRepoForkOwner = exports.deleteBackportBranch = exports.createBackportBranch = exports.getGitConfig = exports.getUnstagedFiles = exports.getConflictingFiles = exports.commitChanges = exports.cherrypick = exports.getShasInMergeCommit = exports.getIsMergeCommit = exports.fetchBranch = exports.addRemote = exports.deleteRemote = exports.getIsCommitInBranch = exports.getGitProjectRootPath = 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("../lib/ora");
@@ -180,7 +180,7 @@ async function getIsMergeCommit(options, sha) {
180
180
  return res.stdout !== '';
181
181
  }
182
182
  exports.getIsMergeCommit = getIsMergeCommit;
183
- async function getCommitsInMergeCommit(options, sha) {
183
+ async function getShasInMergeCommit(options, sha) {
184
184
  try {
185
185
  const cwd = (0, env_1.getRepoPath)(options);
186
186
  const res = await (0, child_process_promisified_1.spawnPromise)('git', ['--no-pager', 'log', `${sha}^1..${sha}^2`, '--pretty=format:%H'], cwd);
@@ -195,34 +195,12 @@ async function getCommitsInMergeCommit(options, sha) {
195
195
  throw e;
196
196
  }
197
197
  }
198
- exports.getCommitsInMergeCommit = getCommitsInMergeCommit;
199
- async function getShaOrRange(options, sha) {
200
- if (!options.mainline) {
201
- try {
202
- const isMergeCommit = await getIsMergeCommit(options, sha);
203
- if (isMergeCommit) {
204
- const shas = await getCommitsInMergeCommit(options, sha);
205
- return `${(0, lodash_1.last)(shas)}^..${(0, lodash_1.first)(shas)}`;
206
- }
207
- }
208
- catch (e) {
209
- const isSpawnError = e instanceof child_process_promisified_1.SpawnError;
210
- // swallow error if it's a 128 exit code
211
- // exit 128 happens when the cherrypicked commit is empty which is handled below
212
- // (128 also applies to many other types of errors)
213
- if (!isSpawnError || e.context.code !== 128) {
214
- throw e;
215
- }
216
- }
217
- }
218
- return sha;
219
- }
198
+ exports.getShasInMergeCommit = getShasInMergeCommit;
220
199
  async function cherrypick({ options, sha, mergedTargetPullRequest, commitAuthor, }) {
221
- const shaOrRange = await getShaOrRange(options, sha);
222
200
  const cmdArgs = [
223
- '-c',
201
+ `-c`,
224
202
  `user.name="${commitAuthor.name}"`,
225
- '-c',
203
+ `-c`,
226
204
  `user.email="${commitAuthor.email}"`,
227
205
  `cherry-pick`,
228
206
  ...(options.mainline != undefined
@@ -230,7 +208,7 @@ async function cherrypick({ options, sha, mergedTargetPullRequest, commitAuthor,
230
208
  : []),
231
209
  ...(options.cherrypickRef === false ? [] : ['-x']),
232
210
  ...(options.signoff ? ['--signoff'] : []),
233
- shaOrRange,
211
+ sha,
234
212
  ];
235
213
  try {
236
214
  const cwd = (0, env_1.getRepoPath)(options);
@@ -269,11 +247,15 @@ async function cherrypick({ options, sha, mergedTargetPullRequest, commitAuthor,
269
247
  }
270
248
  }
271
249
  exports.cherrypick = cherrypick;
272
- async function commitChanges(commit, options) {
250
+ async function commitChanges({ options, commit, commitAuthor, }) {
273
251
  const noVerifyFlag = options.noVerify ? ['--no-verify'] : [];
274
252
  const cwd = (0, env_1.getRepoPath)(options);
275
253
  try {
276
254
  await (0, child_process_promisified_1.spawnPromise)('git', [
255
+ `-c`,
256
+ `user.name="${commitAuthor.name}"`,
257
+ `-c`,
258
+ `user.email="${commitAuthor.email}"`,
277
259
  'commit',
278
260
  '--no-edit',
279
261
  ...noVerifyFlag, // bypass pre-commit and commit-msg hooks
@@ -290,6 +272,10 @@ async function commitChanges(commit, options) {
290
272
  // this can happen if the user runs `git reset HEAD` and thereby aborts the cherrypick process
291
273
  if (e.context.stderr.includes('Aborting commit due to empty commit message')) {
292
274
  await (0, child_process_promisified_1.spawnPromise)('git', [
275
+ `-c`,
276
+ `user.name="${commitAuthor.name}"`,
277
+ `-c`,
278
+ `user.email="${commitAuthor.email}"`,
293
279
  'commit',
294
280
  `--message=${commit.sourceCommit.message}`,
295
281
  ...noVerifyFlag, // bypass pre-commit and commit-msg hooks
@@ -360,13 +346,18 @@ exports.getGitConfig = getGitConfig;
360
346
  // How the commit flows:
361
347
  // ${sourceBranch} -> ${backportBranch} -> ${targetBranch}
362
348
  // master -> backport/7.x/pr-1234 -> 7.x
363
- async function createBackportBranch({ options, targetBranch, backportBranch, }) {
349
+ async function createBackportBranch({ options, sourceBranch, backportBranch, targetBranch, }) {
364
350
  const spinner = (0, ora_1.ora)(options.interactive, 'Pulling latest changes').start();
365
351
  try {
366
352
  const cwd = (0, env_1.getRepoPath)(options);
367
353
  await (0, child_process_promisified_1.spawnPromise)('git', ['reset', '--hard'], cwd);
368
354
  await (0, child_process_promisified_1.spawnPromise)('git', ['clean', '-d', '--force'], cwd);
369
- await (0, child_process_promisified_1.spawnPromise)('git', ['fetch', options.repoOwner, targetBranch], cwd);
355
+ // create tmp branch. This can be necessary when fetching to the currently selected branch
356
+ const tmpBranchName = '__backport_tool_tmp';
357
+ await (0, child_process_promisified_1.spawnPromise)('git', ['checkout', '-B', tmpBranchName], cwd);
358
+ // fetch target branch
359
+ await fetchBranch(options, targetBranch);
360
+ // checkout backport branch and point it to target branch
370
361
  await (0, child_process_promisified_1.spawnPromise)('git', [
371
362
  'checkout',
372
363
  '-B',
@@ -374,6 +365,15 @@ async function createBackportBranch({ options, targetBranch, backportBranch, })
374
365
  `${options.repoOwner}/${targetBranch}`,
375
366
  '--no-track',
376
367
  ], cwd);
368
+ // delete tmp branch (if it still exists)
369
+ try {
370
+ await (0, child_process_promisified_1.spawnPromise)('git', ['branch', '-D', tmpBranchName], cwd);
371
+ }
372
+ catch (e) {
373
+ //
374
+ }
375
+ // fetch commits for source branch
376
+ await fetchBranch(options, sourceBranch);
377
377
  spinner.succeed();
378
378
  }
379
379
  catch (e) {
@@ -421,7 +421,7 @@ async function pushBackportBranch({ options, backportBranch, }) {
421
421
  spinner.fail();
422
422
  if (e instanceof child_process_promisified_1.SpawnError &&
423
423
  e.context.stderr.toLowerCase().includes(`repository not found`)) {
424
- throw new BackportError_1.BackportError(`Error pushing to https://github.com/${repoForkOwner}/${options.repoName}. Repository does not exist. Either fork the repository (https://github.com/${options.repoOwner}/${options.repoName}) or disable fork mode via "--no-fork".\nRead more about fork mode in the docs: https://github.com/sqren/backport/blob/main/docs/configuration.md#fork`);
424
+ throw new BackportError_1.BackportError(`Error pushing to https://github.com/${repoForkOwner}/${options.repoName}. Repository does not exist. Either fork the repository (https://github.com/${options.repoOwner}/${options.repoName}) or disable fork mode via "--no-fork".\nRead more about fork mode in the docs: https://github.com/sqren/backport/blob/main/docs/config-file-options.md#fork`);
425
425
  }
426
426
  if (e instanceof child_process_promisified_1.SpawnError &&
427
427
  e.context.stderr.includes(`could not read Username for`)) {