backport 8.0.0 → 8.1.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 (205) hide show
  1. package/README.md +4 -4
  2. package/dist/backportRun.d.ts +5 -4
  3. package/dist/backportRun.js +41 -42
  4. package/dist/entrypoint.cli.js +3 -7
  5. package/dist/entrypoint.module.d.ts +7 -5
  6. package/dist/entrypoint.module.js +11 -9
  7. package/dist/entrypoint.module.private.test.js +4 -4
  8. package/dist/errors/BackportError.d.ts +19 -0
  9. package/dist/errors/BackportError.js +29 -0
  10. package/dist/lib/BackportError.d.ts +19 -0
  11. package/dist/lib/BackportError.js +29 -0
  12. package/dist/lib/cherrypickAndCreateTargetPullRequest.d.ts +13 -0
  13. package/dist/lib/cherrypickAndCreateTargetPullRequest.js +238 -0
  14. package/dist/lib/cherrypickAndCreateTargetPullRequest.test.d.ts +1 -0
  15. package/dist/lib/cherrypickAndCreateTargetPullRequest.test.js +321 -0
  16. package/dist/lib/child-process-promisified.d.ts +25 -0
  17. package/dist/lib/child-process-promisified.js +58 -0
  18. package/dist/lib/env.d.ts +7 -0
  19. package/dist/lib/env.js +33 -0
  20. package/dist/lib/env.test.d.ts +1 -0
  21. package/dist/lib/env.test.js +26 -0
  22. package/dist/lib/getCommits.d.ts +2 -0
  23. package/dist/lib/getCommits.js +75 -0
  24. package/dist/lib/getCommitsWithoutBackports.d.ts +11 -0
  25. package/dist/lib/getCommitsWithoutBackports.js +68 -0
  26. package/dist/lib/getCommitsWithoutBackports.test.d.ts +1 -0
  27. package/dist/lib/getCommitsWithoutBackports.test.js +335 -0
  28. package/dist/lib/getGitConfigAuthor.d.ts +6 -0
  29. package/dist/lib/getGitConfigAuthor.js +15 -0
  30. package/dist/lib/getTargetBranches.d.ts +5 -0
  31. package/dist/lib/getTargetBranches.js +67 -0
  32. package/dist/lib/getTargetBranches.test.d.ts +1 -0
  33. package/dist/lib/getTargetBranches.test.js +206 -0
  34. package/dist/lib/git.d.ts +77 -0
  35. package/dist/lib/git.js +439 -0
  36. package/dist/lib/git.private.test.d.ts +1 -0
  37. package/dist/lib/git.private.test.js +618 -0
  38. package/dist/lib/git.test.d.ts +1 -0
  39. package/dist/lib/git.test.js +580 -0
  40. package/dist/lib/github/commitFormatters.d.ts +3 -0
  41. package/dist/lib/github/commitFormatters.js +17 -0
  42. package/dist/lib/github/commitFormatters.test.d.ts +1 -0
  43. package/dist/lib/github/commitFormatters.test.js +11 -0
  44. package/dist/lib/github/v3/addAssigneesToPullRequest.d.ts +2 -0
  45. package/dist/lib/github/v3/addAssigneesToPullRequest.js +32 -0
  46. package/dist/lib/github/v3/addAssigneesToPullRequest.test.d.ts +1 -0
  47. package/dist/lib/github/v3/addAssigneesToPullRequest.test.js +27 -0
  48. package/dist/lib/github/v3/addLabelsToPullRequest.d.ts +2 -0
  49. package/dist/lib/github/v3/addLabelsToPullRequest.js +30 -0
  50. package/dist/lib/github/v3/addReviewersToPullRequest.d.ts +2 -0
  51. package/dist/lib/github/v3/addReviewersToPullRequest.js +32 -0
  52. package/dist/lib/github/v3/createPullRequest.d.ts +29 -0
  53. package/dist/lib/github/v3/createPullRequest.js +91 -0
  54. package/dist/lib/github/v3/createPullRequest.test.d.ts +1 -0
  55. package/dist/lib/github/v3/createPullRequest.test.js +377 -0
  56. package/dist/lib/github/v3/createStatusComment.d.ts +11 -0
  57. package/dist/lib/github/v3/createStatusComment.js +136 -0
  58. package/dist/lib/github/v3/createStatusComment.test.d.ts +1 -0
  59. package/dist/lib/github/v3/createStatusComment.test.js +461 -0
  60. package/dist/lib/github/v3/getGithubV3ErrorMessage.d.ts +14 -0
  61. package/dist/lib/github/v3/getGithubV3ErrorMessage.js +16 -0
  62. package/dist/lib/github/v4/FetchPullRequestId.d.ts +2 -0
  63. package/dist/lib/github/v4/FetchPullRequestId.js +36 -0
  64. package/dist/lib/github/v4/apiRequestV4.d.ts +31 -0
  65. package/dist/lib/github/v4/apiRequestV4.js +71 -0
  66. package/dist/lib/github/v4/apiRequestV4.test.d.ts +1 -0
  67. package/dist/lib/github/v4/apiRequestV4.test.js +109 -0
  68. package/dist/lib/github/v4/disablePullRequestAutoMerge.d.ts +2 -0
  69. package/dist/lib/github/v4/disablePullRequestAutoMerge.js +32 -0
  70. package/dist/lib/github/v4/enablePullRequestAutoMerge.d.ts +2 -0
  71. package/dist/lib/github/v4/enablePullRequestAutoMerge.js +50 -0
  72. package/dist/lib/github/v4/enablePullRequestAutoMerge.private.test.d.ts +1 -0
  73. package/dist/lib/github/v4/enablePullRequestAutoMerge.private.test.js +112 -0
  74. package/dist/lib/github/v4/fetchAuthorId.d.ts +10 -0
  75. package/dist/lib/github/v4/fetchAuthorId.js +28 -0
  76. package/dist/lib/github/v4/fetchAuthorId.private.test.d.ts +1 -0
  77. package/dist/lib/github/v4/fetchAuthorId.private.test.js +25 -0
  78. package/dist/lib/github/v4/fetchCommits/allFetchers.private.test.d.ts +1 -0
  79. package/dist/lib/github/v4/fetchCommits/allFetchers.private.test.js +93 -0
  80. package/dist/lib/github/v4/fetchCommits/fetchCommitByPullNumber.d.ts +11 -0
  81. package/dist/lib/github/v4/fetchCommits/fetchCommitByPullNumber.js +58 -0
  82. package/dist/lib/github/v4/fetchCommits/fetchCommitByPullNumber.private.test.d.ts +1 -0
  83. package/dist/lib/github/v4/fetchCommits/fetchCommitByPullNumber.private.test.js +136 -0
  84. package/dist/lib/github/v4/fetchCommits/fetchCommitBySha.d.ts +11 -0
  85. package/dist/lib/github/v4/fetchCommits/fetchCommitBySha.js +48 -0
  86. package/dist/lib/github/v4/fetchCommits/fetchCommitBySha.private.test.d.ts +1 -0
  87. package/dist/lib/github/v4/fetchCommits/fetchCommitBySha.private.test.js +118 -0
  88. package/dist/lib/github/v4/fetchCommits/fetchCommitsByAuthor.d.ts +29 -0
  89. package/dist/lib/github/v4/fetchCommits/fetchCommitsByAuthor.js +110 -0
  90. package/dist/lib/github/v4/fetchCommits/fetchCommitsByAuthor.private.test.d.ts +1 -0
  91. package/dist/lib/github/v4/fetchCommits/fetchCommitsByAuthor.private.test.js +196 -0
  92. package/dist/lib/github/v4/fetchCommits/fetchCommitsByAuthor.test.d.ts +1 -0
  93. package/dist/lib/github/v4/fetchCommits/fetchCommitsByAuthor.test.js +157 -0
  94. package/dist/lib/github/v4/fetchCommits/fetchPullRequestBySearchQuery.private.test.d.ts +1 -0
  95. package/dist/lib/github/v4/fetchCommits/fetchPullRequestBySearchQuery.private.test.js +107 -0
  96. package/dist/lib/github/v4/fetchCommits/fetchPullRequestsBySearchQuery.d.ts +12 -0
  97. package/dist/lib/github/v4/fetchCommits/fetchPullRequestsBySearchQuery.js +69 -0
  98. package/dist/lib/github/v4/fetchExistingPullRequest.d.ts +9 -0
  99. package/dist/lib/github/v4/fetchExistingPullRequest.js +64 -0
  100. package/dist/lib/github/v4/fetchExistingPullRequest.private.test.d.ts +1 -0
  101. package/dist/lib/github/v4/fetchExistingPullRequest.private.test.js +44 -0
  102. package/dist/lib/github/v4/fetchPullRequestAutoMergeMethod.d.ts +2 -0
  103. package/dist/lib/github/v4/fetchPullRequestAutoMergeMethod.js +39 -0
  104. package/dist/lib/github/v4/fetchRemoteProjectConfig.d.ts +8 -0
  105. package/dist/lib/github/v4/fetchRemoteProjectConfig.js +49 -0
  106. package/dist/lib/github/v4/fetchRemoteProjectConfig.private.test.d.ts +1 -0
  107. package/dist/lib/github/v4/fetchRemoteProjectConfig.private.test.js +49 -0
  108. package/dist/lib/github/v4/getOptionsFromGithub/getOptionsFromGithub.d.ts +72 -0
  109. package/dist/lib/github/v4/getOptionsFromGithub/getOptionsFromGithub.js +78 -0
  110. package/dist/lib/github/v4/getOptionsFromGithub/getOptionsFromGithub.private.test.d.ts +1 -0
  111. package/dist/lib/github/v4/getOptionsFromGithub/getOptionsFromGithub.private.test.js +116 -0
  112. package/dist/lib/github/v4/getOptionsFromGithub/query.d.ts +16 -0
  113. package/dist/lib/github/v4/getOptionsFromGithub/query.js +29 -0
  114. package/dist/lib/github/v4/getRepoOwnerAndNameFromGitRemotes.d.ts +29 -0
  115. package/dist/lib/github/v4/getRepoOwnerAndNameFromGitRemotes.js +61 -0
  116. package/dist/lib/github/v4/getRepoOwnerAndNameFromGitRemotes.private.test.d.ts +1 -0
  117. package/dist/lib/github/v4/getRepoOwnerAndNameFromGitRemotes.private.test.js +72 -0
  118. package/dist/lib/github/v4/mocks/commitsByAuthorMock.d.ts +2 -0
  119. package/dist/lib/github/v4/mocks/commitsByAuthorMock.js +176 -0
  120. package/dist/lib/github/v4/throwOnInvalidAccessToken.d.ts +7 -0
  121. package/dist/lib/github/v4/throwOnInvalidAccessToken.js +45 -0
  122. package/dist/lib/github/v4/throwOnInvalidAccessToken.test.d.ts +1 -0
  123. package/dist/lib/github/v4/throwOnInvalidAccessToken.test.js +87 -0
  124. package/dist/lib/logger.d.ts +9 -0
  125. package/dist/lib/logger.js +74 -0
  126. package/dist/lib/ora.d.ts +2 -0
  127. package/dist/lib/ora.js +21 -0
  128. package/dist/lib/prompt.test.d.ts +1 -0
  129. package/dist/lib/prompt.test.js +139 -0
  130. package/dist/lib/prompts.d.ts +17 -0
  131. package/dist/lib/prompts.js +132 -0
  132. package/dist/lib/remoteConfig.d.ts +20 -0
  133. package/dist/lib/remoteConfig.js +52 -0
  134. package/dist/lib/sequentially.d.ts +1 -0
  135. package/dist/lib/sequentially.js +10 -0
  136. package/dist/lib/setupRepo.d.ts +2 -0
  137. package/dist/lib/setupRepo.js +56 -0
  138. package/dist/lib/setupRepo.test.d.ts +1 -0
  139. package/dist/lib/setupRepo.test.js +278 -0
  140. package/dist/lib/sourceCommit/getExpectedTargetPullRequests.d.ts +16 -0
  141. package/dist/lib/sourceCommit/getExpectedTargetPullRequests.js +102 -0
  142. package/dist/lib/sourceCommit/getExpectedTargetPullRequests.test.d.ts +1 -0
  143. package/dist/lib/sourceCommit/getExpectedTargetPullRequests.test.js +467 -0
  144. package/dist/lib/sourceCommit/getMockSourceCommit.d.ts +26 -0
  145. package/dist/lib/sourceCommit/getMockSourceCommit.js +103 -0
  146. package/dist/lib/sourceCommit/parseSourceCommit.d.ts +108 -0
  147. package/dist/lib/sourceCommit/parseSourceCommit.js +123 -0
  148. package/dist/lib/sourceCommit/parseSourceCommit.test.d.ts +1 -0
  149. package/dist/lib/sourceCommit/parseSourceCommit.test.js +226 -0
  150. package/dist/options/ConfigOptions.d.ts +4 -2
  151. package/dist/options/cliArgs.d.ts +15 -12
  152. package/dist/options/cliArgs.js +34 -19
  153. package/dist/options/cliArgs.test.js +125 -1
  154. package/dist/options/config/config.d.ts +5 -4
  155. package/dist/options/config/config.js +3 -5
  156. package/dist/options/config/config.test.js +0 -1
  157. package/dist/options/config/globalConfig.d.ts +3 -1
  158. package/dist/options/config/globalConfig.js +5 -5
  159. package/dist/options/config/readConfigFile.d.ts +9 -7
  160. package/dist/options/config/readConfigFile.js +2 -2
  161. package/dist/options/options.d.ts +43 -7
  162. package/dist/options/options.js +20 -24
  163. package/dist/options/options.test.js +112 -54
  164. package/dist/runSequentially.d.ts +10 -7
  165. package/dist/runSequentially.js +5 -5
  166. package/dist/scripts/postinstall.js +3 -3
  167. package/dist/scripts/postinstall.test.js +1 -1
  168. package/dist/services/BackportError.d.ts +19 -0
  169. package/dist/services/BackportError.js +29 -0
  170. package/dist/services/HandledBackportError.d.ts +19 -0
  171. package/dist/services/HandledBackportError.js +29 -0
  172. package/dist/services/HandledError.d.ts +1 -1
  173. package/dist/services/HandledError.js +5 -5
  174. package/dist/services/git.js +7 -7
  175. package/dist/services/github/v3/createPullRequest.js +2 -2
  176. package/dist/services/github/v3/createStatusComment.js +2 -2
  177. package/dist/services/github/v3/createStatusComment.test.js +5 -4
  178. package/dist/services/github/v4/apiRequestV4.js +2 -2
  179. package/dist/services/github/v4/apiRequestV4.test.js +2 -2
  180. package/dist/services/github/v4/fetchCommits/fetchCommitByPullNumber.js +3 -3
  181. package/dist/services/github/v4/fetchCommits/fetchCommitBySha.js +2 -2
  182. package/dist/services/github/v4/fetchCommits/fetchCommitsByAuthor.js +3 -3
  183. package/dist/services/github/v4/fetchCommits/fetchPullRequestsBySearchQuery.js +2 -2
  184. package/dist/services/github/v4/getOptionsFromGithub/getOptionsFromGithub.js +2 -2
  185. package/dist/services/github/v4/throwOnInvalidAccessToken.js +5 -5
  186. package/dist/state.d.ts +0 -0
  187. package/dist/state.js +1 -0
  188. package/dist/test/e2e/cli/commit-author.private.test.js +4 -4
  189. package/dist/test/e2e/cli/different-merge-strategies.private.test.js +26 -24
  190. package/dist/test/e2e/cli/entrypoint.cli.private.test.js +189 -140
  191. package/dist/test/e2e/cli/repo-with-backportrc-removed.private.test.js +12 -14
  192. package/dist/test/e2e/cli/runBackportViaCli.d.ts +5 -2
  193. package/dist/test/e2e/cli/runBackportViaCli.js +42 -29
  194. package/dist/test/e2e/cli/test-that-repo-can-be-cloned.private.test.js +22 -14
  195. package/dist/test/e2e/module/entrypoint.module.mutation.test.js +2 -2
  196. package/dist/test/handleUnbackportedPullRequests.private.test.js +3 -2
  197. package/dist/test/setupFiles/automatic-mocks.js +1 -1
  198. package/dist/ui/cherrypickAndCreateTargetPullRequest.js +3 -3
  199. package/dist/ui/getCommits.js +2 -2
  200. package/dist/ui/getTargetBranches.js +3 -3
  201. package/dist/ui/setupRepo.js +2 -2
  202. package/dist/utils/packageVersion.d.ts +1 -1
  203. package/dist/utils/packageVersion.js +1 -1
  204. package/package.json +12 -12
  205. package/yarn.lock +112 -65
@@ -0,0 +1,321 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ const os_1 = __importDefault(require("os"));
30
+ const nock_1 = __importDefault(require("nock"));
31
+ const ora_1 = __importDefault(require("ora"));
32
+ const nockHelpers_1 = require("../test/nockHelpers");
33
+ const cherrypickAndCreateTargetPullRequest_1 = require("./cherrypickAndCreateTargetPullRequest");
34
+ const childProcess = __importStar(require("./child-process-promisified"));
35
+ const logger = __importStar(require("./logger"));
36
+ describe('cherrypickAndCreateTargetPullRequest', () => {
37
+ let execSpy;
38
+ let addLabelsScope;
39
+ let consoleLogSpy;
40
+ beforeEach(() => {
41
+ jest.spyOn(os_1.default, 'homedir').mockReturnValue('/myHomeDir');
42
+ execSpy = jest
43
+ .spyOn(childProcess, 'spawnPromise')
44
+ // mock all exec commands to respond without errors
45
+ .mockResolvedValue({ stdout: '', stderr: '', code: 0, cmdArgs: [] });
46
+ consoleLogSpy = jest.spyOn(logger, 'consoleLog');
47
+ // ensure labels are added
48
+ addLabelsScope = (0, nock_1.default)('https://api.github.com')
49
+ .post('/repos/elastic/kibana/issues/1337/labels', {
50
+ labels: ['backport'],
51
+ })
52
+ .reply(200);
53
+ });
54
+ afterEach(() => {
55
+ jest.clearAllMocks();
56
+ addLabelsScope.done();
57
+ nock_1.default.cleanAll();
58
+ });
59
+ describe('when commit has a pull request reference', () => {
60
+ let res;
61
+ let createPullRequestCalls;
62
+ beforeEach(async () => {
63
+ const options = {
64
+ assignees: [],
65
+ authenticatedUsername: 'sqren_authenticated',
66
+ author: 'sqren',
67
+ fork: true,
68
+ interactive: true,
69
+ prTitle: '[{targetBranch}] {commitMessages}',
70
+ repoForkOwner: 'sqren',
71
+ repoName: 'kibana',
72
+ repoOwner: 'elastic',
73
+ reviewers: [],
74
+ sourceBranch: 'myDefaultSourceBranch',
75
+ sourcePRLabels: [],
76
+ targetPRLabels: ['backport'],
77
+ };
78
+ const commits = [
79
+ {
80
+ author: {
81
+ email: 'soren.louv@elastic.co',
82
+ name: 'Søren Louv-Jansen',
83
+ },
84
+ sourceBranch: '7.x',
85
+ sourceCommit: {
86
+ committedDate: 'fff',
87
+ sha: 'mySha',
88
+ message: 'My original commit message (#1000)',
89
+ },
90
+ sourcePullRequest: {
91
+ url: 'foo',
92
+ number: 1000,
93
+ mergeCommit: {
94
+ sha: 'mySha',
95
+ message: 'My original commit message (#1000)',
96
+ },
97
+ },
98
+ expectedTargetPullRequests: [],
99
+ },
100
+ {
101
+ author: {
102
+ email: 'soren.louv@elastic.co',
103
+ name: 'Søren Louv-Jansen',
104
+ },
105
+ sourceBranch: '7.x',
106
+ sourceCommit: {
107
+ committedDate: 'ggg',
108
+ sha: 'mySha2',
109
+ message: 'My other commit message (#2000)',
110
+ },
111
+ sourcePullRequest: {
112
+ url: 'foo',
113
+ number: 2000,
114
+ mergeCommit: {
115
+ sha: 'mySha2',
116
+ message: 'My other commit message (#2000)',
117
+ },
118
+ },
119
+ expectedTargetPullRequests: [],
120
+ },
121
+ ];
122
+ const scope = (0, nock_1.default)('https://api.github.com')
123
+ .post('/repos/elastic/kibana/pulls')
124
+ .reply(200, { number: 1337, html_url: 'myHtmlUrl' });
125
+ createPullRequestCalls = (0, nockHelpers_1.listenForCallsToNockScope)(scope);
126
+ res = await (0, cherrypickAndCreateTargetPullRequest_1.cherrypickAndCreateTargetPullRequest)({
127
+ options,
128
+ commits,
129
+ targetBranch: '6.x',
130
+ });
131
+ scope.done();
132
+ nock_1.default.cleanAll();
133
+ });
134
+ it('creates the pull request with multiple PR references', () => {
135
+ expect(createPullRequestCalls).toMatchInlineSnapshot(`
136
+ Array [
137
+ Object {
138
+ "base": "6.x",
139
+ "body": "# Backport
140
+
141
+ This will backport the following commits from \`7.x\` to \`6.x\`:
142
+ - [My original commit message (#1000)](foo)
143
+ - [My other commit message (#2000)](foo)
144
+
145
+ <!--- Backport version: 1.2.3-mocked -->
146
+
147
+ ### Questions ?
148
+ Please refer to the [Backport tool documentation](https://github.com/sqren/backport)",
149
+ "head": "sqren:backport/6.x/pr-1000_pr-2000",
150
+ "title": "[6.x] My original commit message (#1000) | My other commit message (#2000)",
151
+ },
152
+ ]
153
+ `);
154
+ });
155
+ it('returns the expected response', () => {
156
+ expect(res).toEqual({ didUpdate: false, url: 'myHtmlUrl', number: 1337 });
157
+ });
158
+ it('should make correct git commands', () => {
159
+ expect(execSpy.mock.calls).toMatchSnapshot();
160
+ });
161
+ it('logs correctly', () => {
162
+ expect(consoleLogSpy.mock.calls.length).toBe(2);
163
+ expect(consoleLogSpy.mock.calls[0][0]).toMatchInlineSnapshot(`
164
+ "
165
+ Backporting to 6.x:"
166
+ `);
167
+ expect(consoleLogSpy.mock.calls[1][0]).toMatchInlineSnapshot(`"View pull request: myHtmlUrl"`);
168
+ });
169
+ it('should start the spinner with the correct text', () => {
170
+ expect(ora_1.default.mock.calls.map((call) => call[0].text))
171
+ .toMatchInlineSnapshot(`
172
+ Array [
173
+ "Pulling latest changes",
174
+ "Cherry-picking: My original commit message (#1000)",
175
+ "Cherry-picking: My other commit message (#2000)",
176
+ "Pushing branch \\"sqren:backport/6.x/pr-1000_pr-2000\\"",
177
+ undefined,
178
+ "Creating pull request",
179
+ "Adding labels: backport",
180
+ ]
181
+ `);
182
+ });
183
+ });
184
+ describe('when commit does not have a pull request reference', () => {
185
+ let res;
186
+ let createPullRequestCalls;
187
+ beforeEach(async () => {
188
+ const options = {
189
+ assignees: [],
190
+ authenticatedUsername: 'sqren_authenticated',
191
+ author: 'sqren',
192
+ fork: true,
193
+ prTitle: '[{targetBranch}] {commitMessages}',
194
+ repoForkOwner: 'the_fork_owner',
195
+ repoName: 'kibana',
196
+ repoOwner: 'elastic',
197
+ reviewers: [],
198
+ sourcePRLabels: [],
199
+ targetPRLabels: ['backport'],
200
+ };
201
+ const commits = [
202
+ {
203
+ author: {
204
+ email: 'soren.louv@elastic.co',
205
+ name: 'Søren Louv-Jansen',
206
+ },
207
+ sourceCommit: {
208
+ committedDate: 'hhh',
209
+ sha: 'mySha',
210
+ message: 'My original commit message',
211
+ },
212
+ sourceBranch: '7.x',
213
+ expectedTargetPullRequests: [],
214
+ },
215
+ ];
216
+ const scope = (0, nock_1.default)('https://api.github.com')
217
+ .post('/repos/elastic/kibana/pulls')
218
+ .reply(200, { number: 1337, html_url: 'myHtmlUrl' });
219
+ createPullRequestCalls = (0, nockHelpers_1.listenForCallsToNockScope)(scope);
220
+ res = await (0, cherrypickAndCreateTargetPullRequest_1.cherrypickAndCreateTargetPullRequest)({
221
+ options,
222
+ commits,
223
+ targetBranch: '6.x',
224
+ });
225
+ scope.done();
226
+ nock_1.default.cleanAll();
227
+ });
228
+ it('creates the pull request with commit reference', () => {
229
+ expect(createPullRequestCalls).toMatchInlineSnapshot(`
230
+ Array [
231
+ Object {
232
+ "base": "6.x",
233
+ "body": "# Backport
234
+
235
+ This will backport the following commits from \`7.x\` to \`6.x\`:
236
+ - My original commit message (mySha)
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
+ "head": "the_fork_owner:backport/6.x/commit-mySha",
243
+ "title": "[6.x] My original commit message",
244
+ },
245
+ ]
246
+ `);
247
+ });
248
+ it('returns the expected response', () => {
249
+ expect(res).toEqual({ didUpdate: false, url: 'myHtmlUrl', number: 1337 });
250
+ });
251
+ });
252
+ describe('when cherry-picking fails', () => {
253
+ let res;
254
+ let createPullRequestCalls;
255
+ beforeEach(async () => {
256
+ const options = {
257
+ assignees: [],
258
+ authenticatedUsername: 'sqren_authenticated',
259
+ author: 'sqren',
260
+ fork: true,
261
+ githubApiBaseUrlV4: 'http://localhost/graphql',
262
+ prTitle: '[{targetBranch}] {commitMessages}',
263
+ repoForkOwner: 'sqren',
264
+ repoName: 'kibana',
265
+ repoOwner: 'elastic',
266
+ reviewers: [],
267
+ sourceBranch: 'myDefaultSourceBranch',
268
+ sourcePRLabels: [],
269
+ targetPRLabels: ['backport'],
270
+ };
271
+ const scope = (0, nock_1.default)('https://api.github.com')
272
+ .post('/repos/elastic/kibana/pulls')
273
+ .reply(200, { number: 1337, html_url: 'myHtmlUrl' });
274
+ createPullRequestCalls = (0, nockHelpers_1.listenForCallsToNockScope)(scope);
275
+ res = await (0, cherrypickAndCreateTargetPullRequest_1.cherrypickAndCreateTargetPullRequest)({
276
+ options,
277
+ commits: [
278
+ {
279
+ author: {
280
+ email: 'soren.louv@elastic.co',
281
+ name: 'Søren Louv-Jansen',
282
+ },
283
+ sourceCommit: {
284
+ committedDate: '2021-08-18T16:11:38Z',
285
+ sha: 'mySha',
286
+ message: 'My original commit message',
287
+ },
288
+ sourceBranch: '7.x',
289
+ expectedTargetPullRequests: [],
290
+ },
291
+ ],
292
+ targetBranch: '6.x',
293
+ });
294
+ scope.done();
295
+ nock_1.default.cleanAll();
296
+ });
297
+ it('creates the pull request with commit reference', () => {
298
+ expect(createPullRequestCalls).toMatchInlineSnapshot(`
299
+ Array [
300
+ Object {
301
+ "base": "6.x",
302
+ "body": "# Backport
303
+
304
+ This will backport the following commits from \`7.x\` to \`6.x\`:
305
+ - My original commit message (mySha)
306
+
307
+ <!--- Backport version: 1.2.3-mocked -->
308
+
309
+ ### Questions ?
310
+ Please refer to the [Backport tool documentation](https://github.com/sqren/backport)",
311
+ "head": "sqren:backport/6.x/commit-mySha",
312
+ "title": "[6.x] My original commit message",
313
+ },
314
+ ]
315
+ `);
316
+ });
317
+ it('returns the expected response', () => {
318
+ expect(res).toEqual({ didUpdate: false, url: 'myHtmlUrl', number: 1337 });
319
+ });
320
+ });
321
+ });
@@ -0,0 +1,25 @@
1
+ /// <reference types="node" />
2
+ import childProcess from 'child_process';
3
+ export declare function exec(cmd: string, options: childProcess.ExecOptions & {
4
+ cwd: string;
5
+ }): Promise<{
6
+ stdout: string;
7
+ stderr: string;
8
+ }>;
9
+ export declare function spawnPromise(cmd: string, cmdArgs: string[], cwd: string): Promise<{
10
+ cmdArgs: string[];
11
+ code: number | null;
12
+ stderr: string;
13
+ stdout: string;
14
+ }>;
15
+ export declare const spawnOriginal: typeof childProcess.spawn;
16
+ export declare type SpawnErrorContext = {
17
+ cmdArgs: string[];
18
+ code: number;
19
+ stderr: string;
20
+ stdout: string;
21
+ };
22
+ export declare class SpawnError extends Error {
23
+ context: SpawnErrorContext;
24
+ constructor(context: SpawnErrorContext);
25
+ }
@@ -0,0 +1,58 @@
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.SpawnError = exports.spawnOriginal = exports.spawnPromise = exports.exec = void 0;
7
+ const child_process_1 = __importDefault(require("child_process"));
8
+ const util_1 = require("util");
9
+ const logger_1 = require("./logger");
10
+ const execPromisified = (0, util_1.promisify)(child_process_1.default.exec);
11
+ async function exec(cmd, options) {
12
+ const res = await execPromisified(cmd, {
13
+ maxBuffer: 100 * 1024 * 1024,
14
+ ...options,
15
+ });
16
+ return res;
17
+ }
18
+ exports.exec = exec;
19
+ async function spawnPromise(cmd, cmdArgs, cwd) {
20
+ return new Promise(function (resolve, reject) {
21
+ const subprocess = child_process_1.default.spawn(cmd, cmdArgs, { cwd });
22
+ let stderr = '';
23
+ let stdout = '';
24
+ subprocess.stdout.on('data', (data) => {
25
+ stdout += data;
26
+ });
27
+ subprocess.stderr.on('data', (data) => {
28
+ stderr += data;
29
+ });
30
+ subprocess.on('close', (code) => {
31
+ if (code === 0 || code === null) {
32
+ logger_1.logger.verbose(`spawn success "${cmdArgs}"`);
33
+ resolve({ cmdArgs, code, stderr, stdout });
34
+ }
35
+ else {
36
+ const err = new SpawnError({ cmdArgs, code, stderr, stdout });
37
+ logger_1.logger.info('spawn error', err);
38
+ reject(err);
39
+ }
40
+ });
41
+ subprocess.on('error', (err) => {
42
+ reject(err);
43
+ });
44
+ });
45
+ }
46
+ exports.spawnPromise = spawnPromise;
47
+ exports.spawnOriginal = child_process_1.default.spawn;
48
+ class SpawnError extends Error {
49
+ constructor(context) {
50
+ const message = `Code: ${context.code}; Args: ${JSON.stringify(context.cmdArgs)}; ${context.stderr.trim()}`;
51
+ super(message);
52
+ Error.captureStackTrace(this, SpawnError);
53
+ this.name = 'SpawnError';
54
+ this.message = message;
55
+ this.context = context;
56
+ }
57
+ }
58
+ exports.SpawnError = SpawnError;
@@ -0,0 +1,7 @@
1
+ import { ValidConfigOptions } from '../options/options';
2
+ export declare function getBackportDirPath(): string;
3
+ export declare function getLogfilePath({ logFilePath }: {
4
+ logFilePath?: string;
5
+ }): string;
6
+ export declare function getGlobalConfigPath(globalConfigFile: string | undefined): string;
7
+ export declare function getRepoPath({ repoOwner, repoName, dir }: ValidConfigOptions): string;
@@ -0,0 +1,33 @@
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.getRepoPath = exports.getGlobalConfigPath = exports.getLogfilePath = exports.getBackportDirPath = void 0;
7
+ const os_1 = require("os");
8
+ const path_1 = __importDefault(require("path"));
9
+ function getBackportDirPath() {
10
+ return path_1.default.join((0, os_1.homedir)(), '.backport');
11
+ }
12
+ exports.getBackportDirPath = getBackportDirPath;
13
+ function getLogfilePath({ logFilePath }) {
14
+ if (logFilePath) {
15
+ return path_1.default.resolve(logFilePath);
16
+ }
17
+ return path_1.default.join((0, os_1.homedir)(), '.backport', 'backport.log');
18
+ }
19
+ exports.getLogfilePath = getLogfilePath;
20
+ function getGlobalConfigPath(globalConfigFile) {
21
+ if (globalConfigFile) {
22
+ return path_1.default.resolve(globalConfigFile);
23
+ }
24
+ return path_1.default.join((0, os_1.homedir)(), '.backport', 'config.json');
25
+ }
26
+ exports.getGlobalConfigPath = getGlobalConfigPath;
27
+ function getRepoPath({ repoOwner, repoName, dir }) {
28
+ if (dir) {
29
+ return dir;
30
+ }
31
+ return path_1.default.join((0, os_1.homedir)(), '.backport', 'repositories', repoOwner, repoName);
32
+ }
33
+ exports.getRepoPath = getRepoPath;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,26 @@
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
+ const os_1 = __importDefault(require("os"));
7
+ const env_1 = require("./env");
8
+ describe('env', () => {
9
+ beforeEach(() => {
10
+ jest.spyOn(os_1.default, 'homedir').mockReturnValue('/myHomeDir');
11
+ });
12
+ describe('getGlobalConfigPath', () => {
13
+ it('uses homedir when no argument is given', () => {
14
+ expect((0, env_1.getGlobalConfigPath)(undefined)).toBe('/myHomeDir/.backport/config.json');
15
+ });
16
+ it('uses custom config when given', () => {
17
+ expect((0, env_1.getGlobalConfigPath)('/my/path/to/global/config.json')).toBe('/my/path/to/global/config.json');
18
+ });
19
+ });
20
+ it('getRepoPath', () => {
21
+ expect((0, env_1.getRepoPath)({
22
+ repoOwner: 'elastic',
23
+ repoName: 'kibana',
24
+ })).toBe('/myHomeDir/.backport/repositories/elastic/kibana');
25
+ });
26
+ });
@@ -0,0 +1,2 @@
1
+ import { ValidConfigOptions } from '../options/options';
2
+ export declare function getCommits(options: ValidConfigOptions): Promise<import("./sourceCommit/parseSourceCommit").Commit[]>;
@@ -0,0 +1,75 @@
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.getCommits = void 0;
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ const BackportError_1 = require("./BackportError");
9
+ const commitFormatters_1 = require("./github/commitFormatters");
10
+ const fetchCommitByPullNumber_1 = require("./github/v4/fetchCommits/fetchCommitByPullNumber");
11
+ const fetchCommitBySha_1 = require("./github/v4/fetchCommits/fetchCommitBySha");
12
+ const fetchCommitsByAuthor_1 = require("./github/v4/fetchCommits/fetchCommitsByAuthor");
13
+ const fetchPullRequestsBySearchQuery_1 = require("./github/v4/fetchCommits/fetchPullRequestsBySearchQuery");
14
+ const ora_1 = require("./ora");
15
+ const prompts_1 = require("./prompts");
16
+ function getOraPersistsOption(question, answer) {
17
+ return {
18
+ symbol: chalk_1.default.green('?'),
19
+ text: `${chalk_1.default.bold(question)} ${chalk_1.default.cyan(answer)}`,
20
+ };
21
+ }
22
+ async function getCommits(options) {
23
+ const spinner = (0, ora_1.ora)(options.interactive).start();
24
+ try {
25
+ if (options.sha) {
26
+ const shas = Array.isArray(options.sha) ? options.sha : [options.sha];
27
+ // TODO: use Intl.ListFormat to format the sha's
28
+ spinner.text = `Loading commit "${shas.map(commitFormatters_1.getShortSha)}"`;
29
+ const commits = await Promise.all(shas.map((sha) => (0, fetchCommitBySha_1.fetchCommitBySha)({ ...options, sha })));
30
+ spinner.stopAndPersist(getOraPersistsOption('Select commit', commits.map((commit) => commit.sourceCommit.message).join(', ')));
31
+ return commits;
32
+ }
33
+ if (options.pullNumber) {
34
+ spinner.text = `Loading pull request #${options.pullNumber}`;
35
+ const commit = await (0, fetchCommitByPullNumber_1.fetchCommitByPullNumber)({
36
+ ...options,
37
+ pullNumber: options.pullNumber, // must extract pullNumber to satisfy the ts gods
38
+ });
39
+ // add styles to make it look like a prompt question
40
+ spinner.stopAndPersist(getOraPersistsOption('Select pull request', (0, commitFormatters_1.getFirstLine)(commit.sourceCommit.message)));
41
+ return [commit];
42
+ }
43
+ if (!options.interactive && !options.ls) {
44
+ throw new BackportError_1.BackportError('When "--interactive" is disabled either `--sha` or `--pr` must be specified');
45
+ }
46
+ spinner.text = options.prFilter
47
+ ? 'Loading pull requests...'
48
+ : `Loading commits from branch "${options.sourceBranch}"...`;
49
+ const commitChoices = options.prFilter
50
+ ? await (0, fetchPullRequestsBySearchQuery_1.fetchPullRequestsBySearchQuery)({
51
+ ...options,
52
+ prFilter: options.prFilter,
53
+ })
54
+ : await (0, fetchCommitsByAuthor_1.fetchCommitsByAuthor)(options);
55
+ spinner.stop();
56
+ if (options.ls) {
57
+ return commitChoices;
58
+ }
59
+ return (0, prompts_1.promptForCommits)({
60
+ commitChoices,
61
+ isMultipleChoice: options.multipleCommits,
62
+ showDetails: options.details,
63
+ });
64
+ }
65
+ catch (e) {
66
+ if (options.ls) {
67
+ spinner.stop();
68
+ }
69
+ else {
70
+ spinner.fail();
71
+ }
72
+ throw e;
73
+ }
74
+ }
75
+ exports.getCommits = getCommits;
@@ -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,68 @@
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 git_1 = require("./git");
9
+ const commitFormatters_1 = require("./github/commitFormatters");
10
+ const fetchCommitsByAuthor_1 = require("./github/v4/fetchCommits/fetchCommitsByAuthor");
11
+ // when the user is facing a git conflict we should help them understand
12
+ // why the conflict occurs. In many cases it's because one or more commits haven't been backported yet
13
+ async function getCommitsWithoutBackports({ options,
14
+ // commit that is being backported
15
+ commit,
16
+ // branch the commit is being backported to
17
+ targetBranch,
18
+ // the files with conflicts on the target branch
19
+ conflictingFiles, }) {
20
+ // commits on the source branch that also touched the conflicting files
21
+ const commitsInConflictingPaths = await (0, fetchCommitsByAuthor_1.fetchCommitsByAuthor)({
22
+ ...options,
23
+ author: null,
24
+ dateSince: null,
25
+ dateUntil: commit.sourceCommit.committedDate,
26
+ commitPaths: conflictingFiles,
27
+ });
28
+ const promises = await Promise.all(commitsInConflictingPaths
29
+ .filter((c) => {
30
+ // exclude the commit we are currently trying to backport
31
+ if (c.sourceCommit.sha === commit.sourceCommit.sha) {
32
+ return false;
33
+ }
34
+ // exclude commits that are newer than the commit we are trying to backport
35
+ if (c.sourceCommit.committedDate > commit.sourceCommit.committedDate) {
36
+ return false;
37
+ }
38
+ // only consider commits that have an associated pull request
39
+ if (!c.sourcePullRequest?.url) {
40
+ return false;
41
+ }
42
+ // only include commit if it has an unmerged PR for the given target branch
43
+ const hasUnmergedPr = c.expectedTargetPullRequests.some((pr) => pr.branch === targetBranch && pr.state !== 'MERGED');
44
+ return hasUnmergedPr;
45
+ })
46
+ .slice(0, 10) // limit to max 10 commits
47
+ .map(async (c) => {
48
+ const results = await Promise.all(c.expectedTargetPullRequests.map(async (targetPr) => {
49
+ if (!targetPr.mergeCommit) {
50
+ return false;
51
+ }
52
+ return (0, git_1.getIsCommitInBranch)(options, targetPr.mergeCommit.sha);
53
+ }));
54
+ const isCommitInBranch = results.some((inBranch) => inBranch === true);
55
+ return { c, isCommitInBranch };
56
+ }));
57
+ return promises
58
+ .filter(({ isCommitInBranch }) => !isCommitInBranch)
59
+ .map(({ c }) => {
60
+ // get pull request for the target branch (if it exists)
61
+ const pendingBackportPr = c.expectedTargetPullRequests.find((pr) => pr.branch === targetBranch && pr.state === 'OPEN');
62
+ const formatted = pendingBackportPr
63
+ ? ` - ${(0, commitFormatters_1.getFirstLine)(c.sourceCommit.message)} ${chalk_1.default.gray('(backport pending)')}\n ${pendingBackportPr.url}`
64
+ : ` - ${(0, commitFormatters_1.getFirstLine)(c.sourceCommit.message)} ${chalk_1.default.red('(backport missing)')}\n ${c.sourcePullRequest?.url}`;
65
+ return { formatted, commit: c };
66
+ });
67
+ }
68
+ exports.getCommitsWithoutBackports = getCommitsWithoutBackports;
@@ -0,0 +1 @@
1
+ export {};