backport 7.3.6 → 7.4.0

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 (50) hide show
  1. package/README.md +1 -5
  2. package/dist/backportRun.d.ts +9 -3
  3. package/dist/backportRun.js +18 -9
  4. package/dist/entrypoint.cli.js +1 -1
  5. package/dist/entrypoint.module.js +5 -1
  6. package/dist/entrypoint.module.private.test.js +103 -5
  7. package/dist/options/ConfigOptions.d.ts +2 -2
  8. package/dist/options/cliArgs.d.ts +1 -2
  9. package/dist/options/cliArgs.js +4 -6
  10. package/dist/options/config/config.d.ts +2 -2
  11. package/dist/options/config/config.js +2 -2
  12. package/dist/options/config/projectConfig.d.ts +2 -2
  13. package/dist/options/config/projectConfig.js +3 -3
  14. package/dist/options/config/projectConfig.test.js +19 -7
  15. package/dist/options/config/readConfigFile.d.ts +2 -2
  16. package/dist/options/options.d.ts +1 -2
  17. package/dist/options/options.js +2 -3
  18. package/dist/options/options.test.js +2 -3
  19. package/dist/runSequentially.d.ts +1 -1
  20. package/dist/runSequentially.js +0 -1
  21. package/dist/services/HandledError.d.ts +6 -2
  22. package/dist/services/HandledError.js +8 -8
  23. package/dist/services/git.js +0 -4
  24. package/dist/services/git.test.js +0 -34
  25. package/dist/services/github/v3/createStatusComment.js +3 -2
  26. package/dist/services/github/v3/createStatusComment.test.js +2 -0
  27. package/dist/services/github/v4/apiRequestV4.js +6 -9
  28. package/dist/services/github/v4/fetchAuthorId.private.test.js +3 -6
  29. package/dist/services/github/v4/fetchCommits/allFetchers.private.test.js +5 -6
  30. package/dist/services/github/v4/fetchCommits/fetchCommitByPullNumber.private.test.js +5 -8
  31. package/dist/services/github/v4/fetchCommits/fetchCommitBySha.private.test.js +5 -8
  32. package/dist/services/github/v4/fetchCommits/fetchCommitsByAuthor.private.test.js +4 -7
  33. package/dist/services/github/v4/fetchCommits/fetchPullRequestBySearchQuery.private.test.js +3 -6
  34. package/dist/services/github/v4/fetchExistingPullRequest.private.test.js +3 -6
  35. package/dist/services/github/v4/fetchRemoteProjectConfig.private.test.js +4 -7
  36. package/dist/services/github/v4/getOptionsFromGithub/getOptionsFromGithub.d.ts +2 -2
  37. package/dist/services/github/v4/getOptionsFromGithub/getOptionsFromGithub.private.test.js +6 -7
  38. package/dist/services/github/v4/getRepoOwnerAndNameFromGitRemotes.private.test.js +4 -7
  39. package/dist/services/logger.d.ts +1 -4
  40. package/dist/services/logger.js +9 -18
  41. package/dist/test/e2e/cli/entrypoint.cli.private.test.d.ts +1 -0
  42. package/dist/test/e2e/cli/entrypoint.cli.private.test.js +219 -0
  43. package/dist/test/e2e/module/entrypoint.module.mutation.test.d.ts +1 -0
  44. package/dist/test/e2e/module/entrypoint.module.mutation.test.js +369 -0
  45. package/dist/test/handleUnbackportedPullRequests.private.test.js +1 -2
  46. package/dist/test/setupFiles/automatic-mocks.js +11 -11
  47. package/dist/ui/cherrypickAndCreateTargetPullRequest.js +7 -3
  48. package/dist/utils/packageVersion.d.ts +1 -1
  49. package/dist/utils/packageVersion.js +1 -1
  50. package/package.json +1 -1
@@ -19,17 +19,14 @@ var __importStar = (this && this.__importStar) || function (mod) {
19
19
  return result;
20
20
  };
21
21
  Object.defineProperty(exports, "__esModule", { value: true });
22
- exports.updateLogger = exports.consoleLog = exports.initLogger = exports.logger = void 0;
22
+ exports.setAccessToken = exports.consoleLog = exports.initLogger = exports.logger = void 0;
23
23
  const winston_1 = __importStar(require("winston"));
24
24
  const redact_1 = require("../utils/redact");
25
25
  const env_1 = require("./env");
26
26
  let _accessToken;
27
27
  let _ci;
28
28
  function initLogger({ ci, accessToken, logFilePath, }) {
29
- const fileTransport = getFileTransport({ logFilePath });
30
- if (accessToken) {
31
- _accessToken = accessToken;
32
- }
29
+ _accessToken = accessToken;
33
30
  _ci = ci;
34
31
  exports.logger = winston_1.default.createLogger({
35
32
  format: winston_1.format.combine(winston_1.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
@@ -37,7 +34,11 @@ function initLogger({ ci, accessToken, logFilePath, }) {
37
34
  winston_1.format.metadata({
38
35
  fillExcept: ['message', 'level', 'timestamp', 'label'],
39
36
  })),
40
- transports: fileTransport,
37
+ transports: new winston_1.default.transports.File({
38
+ filename: (0, env_1.getLogfilePath)({ logFilePath }),
39
+ level: 'debug',
40
+ format: winston_1.format.combine(winston_1.format.json()),
41
+ }),
41
42
  });
42
43
  return exports.logger;
43
44
  }
@@ -50,13 +51,10 @@ function consoleLog(message) {
50
51
  }
51
52
  }
52
53
  exports.consoleLog = consoleLog;
53
- function updateLogger({ accessToken, verbose, }) {
54
- // set access token
54
+ function setAccessToken(accessToken) {
55
55
  _accessToken = accessToken;
56
- // set log level
57
- exports.logger.level = verbose ? 'debug' : 'info';
58
56
  }
59
- exports.updateLogger = updateLogger;
57
+ exports.setAccessToken = setAccessToken;
60
58
  function redactAccessToken(str) {
61
59
  // `redactAccessToken` might be called before access token is set
62
60
  if (_accessToken) {
@@ -64,13 +62,6 @@ function redactAccessToken(str) {
64
62
  }
65
63
  return str;
66
64
  }
67
- function getFileTransport({ logFilePath }) {
68
- return new winston_1.default.transports.File({
69
- filename: (0, env_1.getLogfilePath)({ logFilePath }),
70
- level: 'debug',
71
- format: winston_1.format.combine(winston_1.format.json()),
72
- });
73
- }
74
65
  // log levels:
75
66
  // - error
76
67
  // - warn
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,219 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ const child_process_promisified_1 = require("../../../services/child-process-promisified");
23
+ const packageVersion = __importStar(require("../../../utils/packageVersion"));
24
+ const getDevAccessToken_1 = require("../../private/getDevAccessToken");
25
+ const sandbox_1 = require("../../sandbox");
26
+ const runBackportViaCli_1 = require("./runBackportViaCli");
27
+ const TIMEOUT_IN_SECONDS = 15;
28
+ jest.setTimeout(TIMEOUT_IN_SECONDS * 1000);
29
+ const accessToken = (0, getDevAccessToken_1.getDevAccessToken)();
30
+ describe('entrypoint cli', () => {
31
+ it('--version', async () => {
32
+ const res = await (0, runBackportViaCli_1.runBackportViaCli)([`--version`], {
33
+ showOra: true,
34
+ });
35
+ expect(res).toEqual(process.env.npm_package_version);
36
+ });
37
+ it('-v', async () => {
38
+ const res = await (0, runBackportViaCli_1.runBackportViaCli)([`-v`], {
39
+ showOra: true,
40
+ });
41
+ expect(res).toEqual(process.env.npm_package_version);
42
+ });
43
+ it('PACKAGE_VERSION should match', async () => {
44
+ // @ts-expect-error
45
+ expect(packageVersion.UNMOCKED_PACKAGE_VERSION).toBe(process.env.npm_package_version);
46
+ });
47
+ it('--help', async () => {
48
+ const res = await (0, runBackportViaCli_1.runBackportViaCli)([`--help`]);
49
+ expect(res).toMatchInlineSnapshot(`
50
+ "entrypoint.cli.ts [args]
51
+ Options:
52
+ -v, --version Show version number [boolean]
53
+ --accessToken, --accesstoken Github access token [string]
54
+ -a, --all List all commits [boolean]
55
+ --assignee, --assign Add assignees to the target pull request [array]
56
+ --autoAssign Auto assign the target pull request to yourself [boolean]
57
+ --autoMerge Enable auto-merge for created pull requests [boolean]
58
+ --autoMergeMethod Sets auto-merge method when using --auto-merge. Default:
59
+ merge [string] [choices: \\"merge\\", \\"rebase\\", \\"squash\\"]
60
+ --ci Disable interactive prompts [boolean]
61
+ --cherrypickRef Append commit message with \\"(cherry picked from commit...)
62
+ [boolean]
63
+ --projectConfigFile, --config Path to project config [string]
64
+ --since ISO-8601 date for filtering commits [string]
65
+ --until ISO-8601 date for filtering commits [string]
66
+ --dir Location where the temporary repository will be stored
67
+ [string]
68
+ --details Show details about each commit [boolean]
69
+ --dryRun Run backport locally without pushing to Github [boolean]
70
+ --editor Editor to be opened during conflict resolution [string]
71
+ --skipRemoteConfig Use local .backportrc.json config instead of loading from
72
+ Github [boolean]
73
+ --fork Create backports in fork or origin repo. Defaults to true
74
+ [boolean]
75
+ --gitAuthorName Set commit author name [string]
76
+ --gitAuthorEmail Set commit author email [string]
77
+ --ls List commits instead of backporting them [boolean]
78
+ --mainline Parent id of merge commit. Defaults to 1 when supplied
79
+ without arguments [number]
80
+ -n, --maxNumber, --number Number of commits to choose from [number]
81
+ --multiple Select multiple branches/commits [boolean]
82
+ --multipleBranches Backport to multiple branches [boolean]
83
+ --multipleCommits Backport multiple commits [boolean]
84
+ --noCherrypickRef Do not append commit message with \\"(cherry picked from
85
+ commit...)\\" [boolean]
86
+ --noStatusComment Don't publish status comment to Github [boolean]
87
+ --noVerify Bypass the pre-commit and commit-msg hooks [boolean]
88
+ --noFork Create backports in the origin repo [boolean]
89
+ --onlyMissing Only list commits with missing or unmerged backports
90
+ [boolean]
91
+ -p, --path Only list commits touching files under the specified path
92
+ [array]
93
+ --prDescription, --description Description to be added to pull request [string]
94
+ --prTitle, --title Title of pull request [string]
95
+ --prFilter Filter source pull requests by a query [string]
96
+ --pullNumber, --pr Pull request to backport [number]
97
+ --resetAuthor Set yourself as commit author [boolean]
98
+ --reviewer Add reviewer to the target PR [array]
99
+ --repoForkOwner The owner of the fork where the backport branch is pushed.
100
+ Defaults to the currently authenticated user [string]
101
+ --repo Repo owner and name [string]
102
+ --sha, --commit Commit sha to backport [string]
103
+ --sourceBranch Specify a non-default branch (normally \\"master\\") to backport
104
+ from [string]
105
+ --sourcePRLabel, --sourcePrLabel Add labels to the source (original) PR [array]
106
+ -b, --targetBranch, --branch Branch(es) to backport to [array]
107
+ --targetBranchChoice List branches to backport to [array]
108
+ -l, --targetPRLabel, --label Add labels to the target (backport) PR [array]
109
+ --verify Opposite of no-verify [boolean]
110
+ --help Show help [boolean]
111
+ For bugs, feature requests or questions: https://github.com/sqren/backport/issues
112
+ Or contact me directly: https://twitter.com/sorenlouv"
113
+ `);
114
+ });
115
+ it('should return error when branch is missing', async () => {
116
+ const res = await (0, runBackportViaCli_1.runBackportViaCli)([
117
+ '--skip-remote-config',
118
+ '--repo=backport-org/backport-e2e',
119
+ `--accessToken=${accessToken}`,
120
+ ]);
121
+ expect(res).toMatchInlineSnapshot(`
122
+ "Please specify a target branch: \\"--branch 6.1\\".
123
+ Read more: https://github.com/sqren/backport/blob/main/docs/configuration.md#project-config-backportrcjson"
124
+ `);
125
+ });
126
+ it('should list commits based on .git/config when `repoOwner`/`repoName` is missing', async () => {
127
+ const sandboxPath = (0, sandbox_1.getSandboxPath)({ filename: __filename });
128
+ await (0, sandbox_1.resetSandbox)(sandboxPath);
129
+ await (0, child_process_promisified_1.exec)(`git init`, { cwd: sandboxPath });
130
+ await (0, child_process_promisified_1.exec)(`git remote add origin git@github.com:backport-org/backport-e2e.git`, { cwd: sandboxPath });
131
+ const res = await (0, runBackportViaCli_1.runBackportViaCli)([`--accessToken=${accessToken}`], {
132
+ cwd: sandboxPath,
133
+ waitForString: 'Select commit',
134
+ });
135
+ expect(res).toMatchInlineSnapshot(`
136
+ "? Select commit (Use arrow keys)
137
+ ❯ 1. Add sheep emoji (#9) 7.8
138
+ 2. Change Ulysses to Gretha (conflict) (#8) 7.x
139
+ 3. Add 🍏 emoji (#5) 7.x, 7.8
140
+ 4. Add family emoji (#2) 7.x
141
+ 5. Add \`backport\` dep
142
+ 6. Merge pull request #1 from backport-org/add-heart-emoji
143
+ 7. Add ❤️ emoji
144
+ 8. Update .backportrc.json
145
+ 9. Bump to 8.0.0
146
+ 10.Add package.json"
147
+ `);
148
+ });
149
+ it('should return error when access token is invalid', async () => {
150
+ const res = await (0, runBackportViaCli_1.runBackportViaCli)([
151
+ '--branch=foo',
152
+ '--repo=foo/bar',
153
+ '--accessToken=some-token',
154
+ ]);
155
+ expect(res).toContain('Please check your access token and make sure it is valid');
156
+ });
157
+ it(`should return error when repo doesn't exist`, async () => {
158
+ const res = await (0, runBackportViaCli_1.runBackportViaCli)([
159
+ '--branch=foo',
160
+ '--repo=foo/bar',
161
+ '--author=sqren',
162
+ `--accessToken=${accessToken}`,
163
+ ]);
164
+ expect(res).toMatchInlineSnapshot(`"The repository \\"foo/bar\\" doesn't exist"`);
165
+ });
166
+ it(`should list commits from master`, async () => {
167
+ const output = await (0, runBackportViaCli_1.runBackportViaCli)([
168
+ '--branch=foo',
169
+ '--repo=backport-org/backport-e2e',
170
+ '--author=sqren',
171
+ `--accessToken=${accessToken}`,
172
+ '--max-number=6',
173
+ ], { waitForString: 'Select commit' });
174
+ expect(output).toMatchInlineSnapshot(`
175
+ "? Select commit (Use arrow keys)
176
+ ❯ 1. Add sheep emoji (#9) 7.8
177
+ 2. Change Ulysses to Gretha (conflict) (#8) 7.x
178
+ 3. Add 🍏 emoji (#5) 7.x, 7.8
179
+ 4. Add family emoji (#2) 7.x
180
+ 5. Add \`backport\` dep
181
+ 6. Merge pull request #1 from backport-org/add-heart-emoji"
182
+ `);
183
+ });
184
+ it(`should filter commits by "since" and "until"`, async () => {
185
+ const output = await (0, runBackportViaCli_1.runBackportViaCli)([
186
+ '--branch=foo',
187
+ '--repo=backport-org/backport-e2e',
188
+ `--accessToken=${accessToken}`,
189
+ '--since=2020-08-15T10:00:00.000Z',
190
+ '--until=2020-08-15T10:30:00.000Z',
191
+ ], { waitForString: 'Select commit' });
192
+ expect(output).toMatchInlineSnapshot(`
193
+ "? Select commit (Use arrow keys)
194
+ ❯ 1. Bump to 8.0.0
195
+ 2. Add package.json
196
+ 3. Update .backportrc.json
197
+ 4. Create .backportrc.json"
198
+ `);
199
+ });
200
+ it(`should list commits from 7.x`, async () => {
201
+ const output = await (0, runBackportViaCli_1.runBackportViaCli)([
202
+ '--branch=foo',
203
+ '--repo=backport-org/backport-e2e',
204
+ '--author=sqren',
205
+ `--accessToken=${accessToken}`,
206
+ '--max-number=6',
207
+ '--source-branch=7.x',
208
+ ], { waitForString: 'Select commit' });
209
+ expect(output).toMatchInlineSnapshot(`
210
+ "? Select commit (Use arrow keys)
211
+ ❯ 1. Add 🍏 emoji (#5) (#6)
212
+ 2. Change Ulysses to Carol
213
+ 3. Add family emoji (#2) (#4)
214
+ 4. Update .backportrc.json
215
+ 5. Branch off: 7.9.0 (7.x)
216
+ 6. Bump to 8.0.0"
217
+ `);
218
+ });
219
+ });
@@ -0,0 +1,369 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const rest_1 = require("@octokit/rest");
4
+ const entrypoint_module_1 = require("../../../entrypoint.module");
5
+ const commitFormatters_1 = require("../../../services/github/commitFormatters");
6
+ const getDevAccessToken_1 = require("../../private/getDevAccessToken");
7
+ const sandbox_1 = require("../../sandbox");
8
+ jest.unmock('find-up');
9
+ jest.unmock('del');
10
+ jest.unmock('make-dir');
11
+ jest.setTimeout(15000);
12
+ const accessToken = (0, getDevAccessToken_1.getDevAccessToken)();
13
+ const octokit = new rest_1.Octokit({ auth: accessToken });
14
+ const sandboxPath = (0, sandbox_1.getSandboxPath)({ filename: __filename });
15
+ // repo
16
+ const REPO_OWNER = 'backport-org';
17
+ const REPO_NAME = 'integration-test';
18
+ const AUTHOR = 'sqren';
19
+ // commit 1
20
+ const COMMIT_SHA_1 = '5bf29b7d847ea3dbde9280448f0f62ad0f22d3ad';
21
+ const BRANCH_WITH_ONE_COMMIT = `backport/7.x/commit-${(0, commitFormatters_1.getShortSha)(COMMIT_SHA_1)}`;
22
+ // commit 2
23
+ const COMMIT_SHA_2 = '59d6ff1ca90a4ce210c0a4f0e159214875c19d60';
24
+ const BRANCH_WITH_TWO_COMMITS = `backport/7.x/commit-${(0, commitFormatters_1.getShortSha)(COMMIT_SHA_1)}_commit-${(0, commitFormatters_1.getShortSha)(COMMIT_SHA_2)}`;
25
+ describe('entrypoint.module', () => {
26
+ describe('when a single commit is backported', () => {
27
+ let res;
28
+ let pullRequestResponse;
29
+ beforeAll(async () => {
30
+ await resetState(accessToken);
31
+ res = await (0, entrypoint_module_1.backportRun)({
32
+ dir: sandboxPath,
33
+ accessToken,
34
+ repoOwner: 'backport-org',
35
+ repoName: 'integration-test',
36
+ sha: COMMIT_SHA_1,
37
+ targetBranches: ['7.x'],
38
+ });
39
+ // @ts-expect-error
40
+ const pullRequestNumber = res.results[0].pullRequestNumber;
41
+ pullRequestResponse = await octokit.pulls.get({
42
+ owner: REPO_OWNER,
43
+ repo: REPO_NAME,
44
+ pull_number: pullRequestNumber,
45
+ });
46
+ });
47
+ it('returns the backport result', () => {
48
+ expect(res).toEqual({
49
+ commits: [
50
+ {
51
+ author: { email: 'sorenlouv@gmail.com', name: 'Søren Louv-Jansen' },
52
+ expectedTargetPullRequests: [],
53
+ sourceBranch: 'master',
54
+ sourceCommit: {
55
+ committedDate: '2020-08-15T10:37:41Z',
56
+ message: 'Add ❤️ emoji',
57
+ sha: COMMIT_SHA_1,
58
+ },
59
+ sourcePullRequest: undefined,
60
+ },
61
+ ],
62
+ results: [
63
+ {
64
+ didUpdate: false,
65
+ pullRequestNumber: expect.any(Number),
66
+ pullRequestUrl: expect.stringContaining('https://github.com/backport-org/integration-test/pull/'),
67
+ status: 'success',
68
+ targetBranch: '7.x',
69
+ },
70
+ ],
71
+ status: 'success',
72
+ });
73
+ });
74
+ it('pull request: status code', async () => {
75
+ expect(pullRequestResponse.status).toEqual(200);
76
+ });
77
+ it('pull request: title', async () => {
78
+ expect(pullRequestResponse.data.title).toEqual('[7.x] Add ❤️ emoji');
79
+ });
80
+ it('pull request: body', async () => {
81
+ expect(pullRequestResponse.data.body).toMatchInlineSnapshot(`
82
+ "# Backport
83
+
84
+ This will backport the following commits from \`master\` to \`7.x\`:
85
+ - Add ❤️ emoji (5bf29b7d)
86
+
87
+ <!--- Backport version: 1.2.3-mocked -->
88
+
89
+ ### Questions ?
90
+ Please refer to the [Backport tool documentation](https://github.com/sqren/backport)"
91
+ `);
92
+ });
93
+ it('pull request: head branch is in fork repo', async () => {
94
+ expect(pullRequestResponse.data.head.label).toEqual(`sqren:${BRANCH_WITH_ONE_COMMIT}`);
95
+ });
96
+ it('pull request: base branch', async () => {
97
+ expect(pullRequestResponse.data.base.label).toEqual('backport-org:7.x');
98
+ });
99
+ it('does not create any new branches in origin (backport-org/integration-test)', async () => {
100
+ const branches = await getBranchesOnGithub({
101
+ accessToken,
102
+ repoOwner: REPO_OWNER,
103
+ repoName: REPO_NAME,
104
+ });
105
+ expect(branches.map((b) => b.name)).toEqual(['7.x', 'master']);
106
+ });
107
+ it('creates a branch in the fork (sqren/integration-test)', async () => {
108
+ const branches = await getBranchesOnGithub({
109
+ accessToken,
110
+ repoOwner: AUTHOR,
111
+ repoName: REPO_NAME,
112
+ });
113
+ expect(branches.map((b) => b.name)).toEqual([
114
+ '7.x',
115
+ BRANCH_WITH_ONE_COMMIT,
116
+ 'master',
117
+ ]);
118
+ });
119
+ });
120
+ describe('when two commits are backported', () => {
121
+ let res;
122
+ let pullRequestResponse;
123
+ beforeAll(async () => {
124
+ await resetState(accessToken);
125
+ res = await (0, entrypoint_module_1.backportRun)({
126
+ dir: sandboxPath,
127
+ accessToken,
128
+ repoOwner: 'backport-org',
129
+ repoName: 'integration-test',
130
+ sha: [COMMIT_SHA_1, COMMIT_SHA_2],
131
+ targetBranches: ['7.x'],
132
+ });
133
+ // @ts-expect-error
134
+ const pullRequestNumber = res.results[0].pullRequestNumber;
135
+ pullRequestResponse = await octokit.pulls.get({
136
+ owner: REPO_OWNER,
137
+ repo: REPO_NAME,
138
+ pull_number: pullRequestNumber,
139
+ });
140
+ });
141
+ it('returns the backport result containing both commits', () => {
142
+ expect(res).toEqual({
143
+ commits: [
144
+ {
145
+ author: { email: 'sorenlouv@gmail.com', name: 'Søren Louv-Jansen' },
146
+ expectedTargetPullRequests: [],
147
+ sourceBranch: 'master',
148
+ sourceCommit: {
149
+ committedDate: '2020-08-15T10:37:41Z',
150
+ message: 'Add ❤️ emoji',
151
+ sha: COMMIT_SHA_1,
152
+ },
153
+ sourcePullRequest: undefined,
154
+ },
155
+ {
156
+ author: { email: 'sorenlouv@gmail.com', name: 'Søren Louv-Jansen' },
157
+ expectedTargetPullRequests: [],
158
+ sourceBranch: 'master',
159
+ sourceCommit: {
160
+ committedDate: '2020-08-15T10:44:04Z',
161
+ message: 'Add family emoji (#2)',
162
+ sha: COMMIT_SHA_2,
163
+ },
164
+ sourcePullRequest: undefined,
165
+ },
166
+ ],
167
+ results: [
168
+ {
169
+ didUpdate: false,
170
+ pullRequestNumber: expect.any(Number),
171
+ pullRequestUrl: expect.stringContaining('https://github.com/backport-org/integration-test/pull/'),
172
+ status: 'success',
173
+ targetBranch: '7.x',
174
+ },
175
+ ],
176
+ status: 'success',
177
+ });
178
+ });
179
+ it('pull request: status code', async () => {
180
+ expect(pullRequestResponse.status).toEqual(200);
181
+ });
182
+ it('pull request: title', async () => {
183
+ expect(pullRequestResponse.data.title).toEqual('[7.x] Add ❤️ emoji | Add family emoji (#2)');
184
+ });
185
+ it('pull request: body', async () => {
186
+ expect(pullRequestResponse.data.body).toMatchInlineSnapshot(`
187
+ "# Backport
188
+
189
+ This will backport the following commits from \`master\` to \`7.x\`:
190
+ - Add ❤️ emoji (5bf29b7d)
191
+ - Add family emoji (#2) (59d6ff1c)
192
+
193
+ <!--- Backport version: 1.2.3-mocked -->
194
+
195
+ ### Questions ?
196
+ Please refer to the [Backport tool documentation](https://github.com/sqren/backport)"
197
+ `);
198
+ });
199
+ it('pull request: head branch contains both commits in name', async () => {
200
+ expect(pullRequestResponse.data.head.label).toEqual(`sqren:${BRANCH_WITH_TWO_COMMITS}`);
201
+ });
202
+ it('pull request: base branch', async () => {
203
+ expect(pullRequestResponse.data.base.label).toEqual('backport-org:7.x');
204
+ });
205
+ });
206
+ describe('when disabling fork mode', () => {
207
+ let res;
208
+ let pullRequestResponse;
209
+ beforeAll(async () => {
210
+ await resetState(accessToken);
211
+ res = await (0, entrypoint_module_1.backportRun)({
212
+ fork: false,
213
+ dir: sandboxPath,
214
+ accessToken,
215
+ repoOwner: 'backport-org',
216
+ repoName: 'integration-test',
217
+ sha: COMMIT_SHA_1,
218
+ targetBranches: ['7.x'],
219
+ });
220
+ // @ts-expect-error
221
+ const pullRequestNumber = res.results[0].pullRequestNumber;
222
+ pullRequestResponse = await octokit.pulls.get({
223
+ owner: REPO_OWNER,
224
+ repo: REPO_NAME,
225
+ pull_number: pullRequestNumber,
226
+ });
227
+ });
228
+ it('pull request: title', async () => {
229
+ expect(pullRequestResponse.data.title).toEqual('[7.x] Add ❤️ emoji');
230
+ });
231
+ it('pull request: body', async () => {
232
+ expect(pullRequestResponse.data.body).toMatchInlineSnapshot(`
233
+ "# Backport
234
+
235
+ This will backport the following commits from \`master\` to \`7.x\`:
236
+ - Add ❤️ emoji (5bf29b7d)
237
+
238
+ <!--- Backport version: 1.2.3-mocked -->
239
+
240
+ ### Questions ?
241
+ Please refer to the [Backport tool documentation](https://github.com/sqren/backport)"
242
+ `);
243
+ });
244
+ it('pull request: head branch is in origin (non-fork) repo', async () => {
245
+ expect(pullRequestResponse.data.head.label).toEqual(`backport-org:${BRANCH_WITH_ONE_COMMIT}`);
246
+ });
247
+ it('pull request: base branch', async () => {
248
+ expect(pullRequestResponse.data.base.label).toEqual('backport-org:7.x');
249
+ });
250
+ it('returns pull request', () => {
251
+ expect(res).toEqual({
252
+ commits: [
253
+ {
254
+ author: { email: 'sorenlouv@gmail.com', name: 'Søren Louv-Jansen' },
255
+ expectedTargetPullRequests: [],
256
+ sourceBranch: 'master',
257
+ sourceCommit: {
258
+ committedDate: '2020-08-15T10:37:41Z',
259
+ message: 'Add ❤️ emoji',
260
+ sha: COMMIT_SHA_1,
261
+ },
262
+ sourcePullRequest: undefined,
263
+ },
264
+ ],
265
+ results: [
266
+ {
267
+ didUpdate: false,
268
+ pullRequestNumber: expect.any(Number),
269
+ pullRequestUrl: expect.stringContaining('https://github.com/backport-org/integration-test/pull/'),
270
+ status: 'success',
271
+ targetBranch: '7.x',
272
+ },
273
+ ],
274
+ status: 'success',
275
+ });
276
+ });
277
+ it('creates a new branch in origin (backport-org/integration-test)', async () => {
278
+ const branches = await getBranchesOnGithub({
279
+ accessToken,
280
+ repoOwner: REPO_OWNER,
281
+ repoName: REPO_NAME,
282
+ });
283
+ expect(branches.map((b) => b.name)).toEqual([
284
+ '7.x',
285
+ BRANCH_WITH_ONE_COMMIT,
286
+ 'master',
287
+ ]);
288
+ });
289
+ it('does not create branches in the fork (sqren/integration-test)', async () => {
290
+ const branches = await getBranchesOnGithub({
291
+ accessToken,
292
+ repoOwner: AUTHOR,
293
+ repoName: REPO_NAME,
294
+ });
295
+ expect(branches.map((b) => b.name)).toEqual(['7.x', 'master']);
296
+ });
297
+ });
298
+ });
299
+ async function getBranchesOnGithub({ accessToken, repoOwner, repoName, }) {
300
+ // console.log(`fetch branches for ${repoOwner}`);
301
+ const octokit = new rest_1.Octokit({
302
+ auth: accessToken,
303
+ });
304
+ const res = await octokit.repos.listBranches({
305
+ owner: repoOwner,
306
+ repo: repoName,
307
+ });
308
+ return res.data;
309
+ }
310
+ async function deleteBranchOnGithub({ accessToken, repoOwner, repoName, branchName, }) {
311
+ try {
312
+ const octokit = new rest_1.Octokit({
313
+ auth: accessToken,
314
+ });
315
+ // console.log({ accessToken });
316
+ const opts = {
317
+ owner: repoOwner,
318
+ repo: repoName,
319
+ ref: `heads/${branchName}`,
320
+ };
321
+ const res = await octokit.git.deleteRef(opts);
322
+ // console.log(`Deleted ${repoOwner}:heads/${branchName}`);
323
+ return res.data;
324
+ }
325
+ catch (e) {
326
+ // console.log(
327
+ // `Could not delete ${repoOwner}:heads/${branchName} (${e.message})`
328
+ // );
329
+ if (e.message === 'Reference does not exist') {
330
+ return;
331
+ }
332
+ throw e;
333
+ }
334
+ }
335
+ async function resetState(accessToken) {
336
+ const ownerBranches = await getBranchesOnGithub({
337
+ accessToken,
338
+ repoOwner: REPO_OWNER,
339
+ repoName: REPO_NAME,
340
+ });
341
+ // delete all branches except master and 7.x
342
+ await Promise.all(ownerBranches
343
+ .filter((b) => b.name !== 'master' && b.name !== '7.x')
344
+ .map((b) => {
345
+ return deleteBranchOnGithub({
346
+ accessToken,
347
+ repoOwner: REPO_OWNER,
348
+ repoName: REPO_NAME,
349
+ branchName: b.name,
350
+ });
351
+ }));
352
+ const forkBranches = await getBranchesOnGithub({
353
+ accessToken,
354
+ repoOwner: AUTHOR,
355
+ repoName: REPO_NAME,
356
+ });
357
+ // delete all branches except master and 7.x
358
+ await Promise.all(forkBranches
359
+ .filter((b) => b.name !== 'master' && b.name !== '7.x')
360
+ .map((b) => {
361
+ return deleteBranchOnGithub({
362
+ accessToken,
363
+ repoOwner: AUTHOR,
364
+ repoName: REPO_NAME,
365
+ branchName: b.name,
366
+ });
367
+ }));
368
+ await (0, sandbox_1.resetSandbox)(sandboxPath);
369
+ }
@@ -3,11 +3,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const entrypoint_module_1 = require("../entrypoint.module");
4
4
  const getDevAccessToken_1 = require("./private/getDevAccessToken");
5
5
  const sandbox_1 = require("./sandbox");
6
+ const accessToken = (0, getDevAccessToken_1.getDevAccessToken)();
6
7
  jest.unmock('find-up');
7
8
  jest.setTimeout(15000);
8
9
  describe('Handle unbackported pull requests', () => {
9
10
  it('shows missing backports for PR number 8', async () => {
10
- const accessToken = (0, getDevAccessToken_1.getDevAccessToken)();
11
11
  const commits = await (0, entrypoint_module_1.getCommits)({
12
12
  accessToken: accessToken,
13
13
  repoOwner: 'backport-org',
@@ -35,7 +35,6 @@ describe('Handle unbackported pull requests', () => {
35
35
  expect(commits[0]).toEqual(expectedCommit);
36
36
  });
37
37
  it('shows that backport failed because PR number 8 was not backported', async () => {
38
- const accessToken = (0, getDevAccessToken_1.getDevAccessToken)();
39
38
  const sandboxPath = (0, sandbox_1.getSandboxPath)({ filename: __filename });
40
39
  await (0, sandbox_1.resetSandbox)(sandboxPath);
41
40
  const result = await (0, entrypoint_module_1.backportRun)({