backport 7.2.0-beta.1 → 7.2.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 (49) hide show
  1. package/dist/entrypoint.cli.js +0 -0
  2. package/dist/entrypoint.module.d.ts +4 -3
  3. package/dist/entrypoint.module.js +2 -7
  4. package/dist/options/ConfigOptions.d.ts +1 -1
  5. package/dist/options/cliArgs.d.ts +1 -0
  6. package/dist/options/cliArgs.js +4 -0
  7. package/dist/options/config/config.d.ts +1 -1
  8. package/dist/options/config/readConfigFile.d.ts +1 -1
  9. package/dist/options/options.d.ts +2 -1
  10. package/dist/runSequentially.test.js +54 -30
  11. package/dist/services/git.d.ts +1 -3
  12. package/dist/services/git.js +5 -3
  13. package/dist/services/github/v3/createStatusComment.js +1 -1
  14. package/dist/services/github/v4/apiRequestV4.d.ts +2 -3
  15. package/dist/services/github/v4/apiRequestV4.js +15 -14
  16. package/dist/services/github/v4/fetchCommits/fetchCommitByPullNumber.js +2 -2
  17. package/dist/services/github/v4/fetchCommits/fetchCommitBySha.js +2 -2
  18. package/dist/services/github/v4/fetchCommits/fetchCommitsByAuthor.js +2 -2
  19. package/dist/services/github/v4/fetchCommits/fetchPullRequestBySearchQuery.js +2 -2
  20. package/dist/services/github/v4/fetchRemoteProjectConfig.js +1 -1
  21. package/dist/services/github/v4/getOptionsFromGithub/getOptionsFromGithub.d.ts +1 -1
  22. package/dist/services/github/v4/getOptionsFromGithub/query.js +1 -1
  23. package/dist/services/github/v4/mocks/commitsByAuthorMock.js +2 -5
  24. package/dist/services/github/v4/throwOnInvalidAccessToken.js +6 -6
  25. package/dist/services/github/v4/throwOnInvalidAccessToken.test.js +5 -5
  26. package/dist/services/remoteConfig.js +2 -2
  27. package/dist/services/sourceCommit/getExpectedTargetPullRequests.d.ts +4 -1
  28. package/dist/services/sourceCommit/getExpectedTargetPullRequests.js +5 -1
  29. package/dist/services/sourceCommit/getExpectedTargetPullRequests.test.js +73 -39
  30. package/dist/services/sourceCommit/getMockSourceCommit.js +19 -18
  31. package/dist/services/sourceCommit/parseSourceCommit.d.ts +2 -2
  32. package/dist/services/sourceCommit/parseSourceCommit.js +9 -15
  33. package/dist/{entrypoint.cli.e2e.private.test.d.ts → test/e2e/cli.e2e.private.test.d.ts} +0 -0
  34. package/dist/{entrypoint.cli.e2e.private.test.js → test/e2e/cli.e2e.private.test.js} +85 -38
  35. package/dist/test/{backport-e2e.mutation.test.d.ts → e2e/module.e2e.private.test.d.ts} +0 -0
  36. package/dist/test/e2e/module.e2e.private.test.js +363 -0
  37. package/dist/test/handleUnbackportedPullRequests.private.test.js +0 -2
  38. package/dist/ui/cherrypickAndCreateTargetPullRequest.js +12 -18
  39. package/dist/ui/cherrypickAndCreateTargetPullRequest.test.js +2 -2
  40. package/dist/ui/getCommits.js +6 -4
  41. package/dist/ui/maybeSetupRepo.js +13 -16
  42. package/dist/ui/maybeSetupRepo.test.js +50 -16
  43. package/dist/ui/ora.d.ts +1 -1
  44. package/dist/ui/ora.js +2 -2
  45. package/dist/utils/packageVersion.d.ts +1 -1
  46. package/dist/utils/packageVersion.js +1 -1
  47. package/package.json +9 -9
  48. package/yarn.lock +121 -114
  49. package/dist/test/backport-e2e.mutation.test.js +0 -347
@@ -0,0 +1,363 @@
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.setTimeout(15000);
10
+ const accessToken = (0, getDevAccessToken_1.getDevAccessToken)();
11
+ const octokit = new rest_1.Octokit({ auth: accessToken });
12
+ const sandboxPath = (0, sandbox_1.getSandboxPath)({ filename: __filename });
13
+ // repo
14
+ const REPO_OWNER = 'backport-org';
15
+ const REPO_NAME = 'integration-test';
16
+ const AUTHOR = 'sqren';
17
+ // commit 1
18
+ const COMMIT_SHA_1 = '5bf29b7d847ea3dbde9280448f0f62ad0f22d3ad';
19
+ const BRANCH_WITH_ONE_COMMIT = `backport/7.x/commit-${(0, commitFormatters_1.getShortSha)(COMMIT_SHA_1)}`;
20
+ // commit 2
21
+ const COMMIT_SHA_2 = '59d6ff1ca90a4ce210c0a4f0e159214875c19d60';
22
+ const BRANCH_WITH_TWO_COMMITS = `backport/7.x/commit-${(0, commitFormatters_1.getShortSha)(COMMIT_SHA_1)}_commit-${(0, commitFormatters_1.getShortSha)(COMMIT_SHA_2)}`;
23
+ describe('backport e2e', () => {
24
+ describe('when a single commit is backported', () => {
25
+ let res;
26
+ let pullRequestResponse;
27
+ beforeAll(async () => {
28
+ await resetState(accessToken);
29
+ res = await (0, entrypoint_module_1.backportRun)({
30
+ dir: sandboxPath,
31
+ accessToken,
32
+ repoOwner: 'backport-org',
33
+ repoName: 'integration-test',
34
+ sha: COMMIT_SHA_1,
35
+ targetBranches: ['7.x'],
36
+ });
37
+ // @ts-expect-error
38
+ const pullRequestNumber = res.results[0].pullRequestNumber;
39
+ pullRequestResponse = await octokit.pulls.get({
40
+ owner: REPO_OWNER,
41
+ repo: REPO_NAME,
42
+ pull_number: pullRequestNumber,
43
+ });
44
+ });
45
+ it('returns the backport result', () => {
46
+ expect(res).toEqual({
47
+ commits: [
48
+ {
49
+ expectedTargetPullRequests: [],
50
+ sourceBranch: 'master',
51
+ sourceCommit: {
52
+ committedDate: '2020-08-15T10:37:41Z',
53
+ message: 'Add ❤️ emoji',
54
+ sha: COMMIT_SHA_1,
55
+ },
56
+ sourcePullRequest: undefined,
57
+ },
58
+ ],
59
+ results: [
60
+ {
61
+ didUpdate: false,
62
+ pullRequestNumber: expect.any(Number),
63
+ pullRequestUrl: expect.stringContaining('https://github.com/backport-org/integration-test/pull/'),
64
+ status: 'success',
65
+ targetBranch: '7.x',
66
+ },
67
+ ],
68
+ status: 'success',
69
+ });
70
+ });
71
+ it('pull request: status code', async () => {
72
+ expect(pullRequestResponse.status).toEqual(200);
73
+ });
74
+ it('pull request: title', async () => {
75
+ expect(pullRequestResponse.data.title).toEqual('[7.x] Add ❤️ emoji');
76
+ });
77
+ it('pull request: body', async () => {
78
+ expect(pullRequestResponse.data.body).toMatchInlineSnapshot(`
79
+ "# Backport
80
+
81
+ This will backport the following commits from \`master\` to \`7.x\`:
82
+ - Add ❤️ emoji (5bf29b7d)
83
+
84
+ <!--- Backport version: 1.2.3-mocked -->
85
+
86
+ ### Questions ?
87
+ Please refer to the [Backport tool documentation](https://github.com/sqren/backport)"
88
+ `);
89
+ });
90
+ it('pull request: head branch is in fork repo', async () => {
91
+ expect(pullRequestResponse.data.head.label).toEqual(`sqren:${BRANCH_WITH_ONE_COMMIT}`);
92
+ });
93
+ it('pull request: base branch', async () => {
94
+ expect(pullRequestResponse.data.base.label).toEqual('backport-org:7.x');
95
+ });
96
+ it('does not create any new branches in origin (backport-org/integration-test)', async () => {
97
+ const branches = await getBranchesOnGithub({
98
+ accessToken,
99
+ repoOwner: REPO_OWNER,
100
+ repoName: REPO_NAME,
101
+ });
102
+ expect(branches.map((b) => b.name)).toEqual(['7.x', 'master']);
103
+ });
104
+ it('creates a branch in the fork (sqren/integration-test)', async () => {
105
+ const branches = await getBranchesOnGithub({
106
+ accessToken,
107
+ repoOwner: AUTHOR,
108
+ repoName: REPO_NAME,
109
+ });
110
+ expect(branches.map((b) => b.name)).toEqual([
111
+ '7.x',
112
+ BRANCH_WITH_ONE_COMMIT,
113
+ 'master',
114
+ ]);
115
+ });
116
+ });
117
+ describe('when two commits are backported', () => {
118
+ let res;
119
+ let pullRequestResponse;
120
+ beforeAll(async () => {
121
+ await resetState(accessToken);
122
+ res = await (0, entrypoint_module_1.backportRun)({
123
+ dir: sandboxPath,
124
+ accessToken,
125
+ repoOwner: 'backport-org',
126
+ repoName: 'integration-test',
127
+ sha: [COMMIT_SHA_1, COMMIT_SHA_2],
128
+ targetBranches: ['7.x'],
129
+ });
130
+ // @ts-expect-error
131
+ const pullRequestNumber = res.results[0].pullRequestNumber;
132
+ pullRequestResponse = await octokit.pulls.get({
133
+ owner: REPO_OWNER,
134
+ repo: REPO_NAME,
135
+ pull_number: pullRequestNumber,
136
+ });
137
+ });
138
+ it('returns the backport result containing both commits', () => {
139
+ expect(res).toEqual({
140
+ commits: [
141
+ {
142
+ expectedTargetPullRequests: [],
143
+ sourceBranch: 'master',
144
+ sourceCommit: {
145
+ committedDate: '2020-08-15T10:37:41Z',
146
+ message: 'Add ❤️ emoji',
147
+ sha: COMMIT_SHA_1,
148
+ },
149
+ sourcePullRequest: undefined,
150
+ },
151
+ {
152
+ expectedTargetPullRequests: [],
153
+ sourceBranch: 'master',
154
+ sourceCommit: {
155
+ committedDate: '2020-08-15T10:44:04Z',
156
+ message: 'Add family emoji (#2)',
157
+ sha: COMMIT_SHA_2,
158
+ },
159
+ sourcePullRequest: undefined,
160
+ },
161
+ ],
162
+ results: [
163
+ {
164
+ didUpdate: false,
165
+ pullRequestNumber: expect.any(Number),
166
+ pullRequestUrl: expect.stringContaining('https://github.com/backport-org/integration-test/pull/'),
167
+ status: 'success',
168
+ targetBranch: '7.x',
169
+ },
170
+ ],
171
+ status: 'success',
172
+ });
173
+ });
174
+ it('pull request: status code', async () => {
175
+ expect(pullRequestResponse.status).toEqual(200);
176
+ });
177
+ it('pull request: title', async () => {
178
+ expect(pullRequestResponse.data.title).toEqual('[7.x] Add ❤️ emoji | Add family emoji (#2)');
179
+ });
180
+ it('pull request: body', async () => {
181
+ expect(pullRequestResponse.data.body).toMatchInlineSnapshot(`
182
+ "# Backport
183
+
184
+ This will backport the following commits from \`master\` to \`7.x\`:
185
+ - Add ❤️ emoji (5bf29b7d)
186
+ - Add family emoji (#2) (59d6ff1c)
187
+
188
+ <!--- Backport version: 1.2.3-mocked -->
189
+
190
+ ### Questions ?
191
+ Please refer to the [Backport tool documentation](https://github.com/sqren/backport)"
192
+ `);
193
+ });
194
+ it('pull request: head branch contains both commits in name', async () => {
195
+ expect(pullRequestResponse.data.head.label).toEqual(`sqren:${BRANCH_WITH_TWO_COMMITS}`);
196
+ });
197
+ it('pull request: base branch', async () => {
198
+ expect(pullRequestResponse.data.base.label).toEqual('backport-org:7.x');
199
+ });
200
+ });
201
+ describe('when disabling fork mode', () => {
202
+ let res;
203
+ let pullRequestResponse;
204
+ beforeAll(async () => {
205
+ await resetState(accessToken);
206
+ res = await (0, entrypoint_module_1.backportRun)({
207
+ fork: false,
208
+ dir: sandboxPath,
209
+ accessToken,
210
+ repoOwner: 'backport-org',
211
+ repoName: 'integration-test',
212
+ sha: COMMIT_SHA_1,
213
+ targetBranches: ['7.x'],
214
+ });
215
+ // @ts-expect-error
216
+ const pullRequestNumber = res.results[0].pullRequestNumber;
217
+ pullRequestResponse = await octokit.pulls.get({
218
+ owner: REPO_OWNER,
219
+ repo: REPO_NAME,
220
+ pull_number: pullRequestNumber,
221
+ });
222
+ });
223
+ it('pull request: title', async () => {
224
+ expect(pullRequestResponse.data.title).toEqual('[7.x] Add ❤️ emoji');
225
+ });
226
+ it('pull request: body', async () => {
227
+ expect(pullRequestResponse.data.body).toMatchInlineSnapshot(`
228
+ "# Backport
229
+
230
+ This will backport the following commits from \`master\` to \`7.x\`:
231
+ - Add ❤️ emoji (5bf29b7d)
232
+
233
+ <!--- Backport version: 1.2.3-mocked -->
234
+
235
+ ### Questions ?
236
+ Please refer to the [Backport tool documentation](https://github.com/sqren/backport)"
237
+ `);
238
+ });
239
+ it('pull request: head branch is in origin (non-fork) repo', async () => {
240
+ expect(pullRequestResponse.data.head.label).toEqual(`backport-org:${BRANCH_WITH_ONE_COMMIT}`);
241
+ });
242
+ it('pull request: base branch', async () => {
243
+ expect(pullRequestResponse.data.base.label).toEqual('backport-org:7.x');
244
+ });
245
+ it('returns pull request', () => {
246
+ expect(res).toEqual({
247
+ commits: [
248
+ {
249
+ expectedTargetPullRequests: [],
250
+ sourceBranch: 'master',
251
+ sourceCommit: {
252
+ committedDate: '2020-08-15T10:37:41Z',
253
+ message: 'Add ❤️ emoji',
254
+ sha: COMMIT_SHA_1,
255
+ },
256
+ sourcePullRequest: undefined,
257
+ },
258
+ ],
259
+ results: [
260
+ {
261
+ didUpdate: false,
262
+ pullRequestNumber: expect.any(Number),
263
+ pullRequestUrl: expect.stringContaining('https://github.com/backport-org/integration-test/pull/'),
264
+ status: 'success',
265
+ targetBranch: '7.x',
266
+ },
267
+ ],
268
+ status: 'success',
269
+ });
270
+ });
271
+ it('creates a new branch in origin (backport-org/integration-test)', async () => {
272
+ const branches = await getBranchesOnGithub({
273
+ accessToken,
274
+ repoOwner: REPO_OWNER,
275
+ repoName: REPO_NAME,
276
+ });
277
+ expect(branches.map((b) => b.name)).toEqual([
278
+ '7.x',
279
+ BRANCH_WITH_ONE_COMMIT,
280
+ 'master',
281
+ ]);
282
+ });
283
+ it('does not create branches in the fork (sqren/integration-test)', async () => {
284
+ const branches = await getBranchesOnGithub({
285
+ accessToken,
286
+ repoOwner: AUTHOR,
287
+ repoName: REPO_NAME,
288
+ });
289
+ expect(branches.map((b) => b.name)).toEqual(['7.x', 'master']);
290
+ });
291
+ });
292
+ });
293
+ async function getBranchesOnGithub({ accessToken, repoOwner, repoName, }) {
294
+ // console.log(`fetch branches for ${repoOwner}`);
295
+ const octokit = new rest_1.Octokit({
296
+ auth: accessToken,
297
+ });
298
+ const res = await octokit.repos.listBranches({
299
+ owner: repoOwner,
300
+ repo: repoName,
301
+ });
302
+ return res.data;
303
+ }
304
+ async function deleteBranchOnGithub({ accessToken, repoOwner, repoName, branchName, }) {
305
+ try {
306
+ const octokit = new rest_1.Octokit({
307
+ auth: accessToken,
308
+ });
309
+ // console.log({ accessToken });
310
+ const opts = {
311
+ owner: repoOwner,
312
+ repo: repoName,
313
+ ref: `heads/${branchName}`,
314
+ };
315
+ const res = await octokit.git.deleteRef(opts);
316
+ // console.log(`Deleted ${repoOwner}:heads/${branchName}`);
317
+ return res.data;
318
+ }
319
+ catch (e) {
320
+ // console.log(
321
+ // `Could not delete ${repoOwner}:heads/${branchName} (${e.message})`
322
+ // );
323
+ if (e.message === 'Reference does not exist') {
324
+ return;
325
+ }
326
+ throw e;
327
+ }
328
+ }
329
+ async function resetState(accessToken) {
330
+ const ownerBranches = await getBranchesOnGithub({
331
+ accessToken,
332
+ repoOwner: REPO_OWNER,
333
+ repoName: REPO_NAME,
334
+ });
335
+ // delete all branches except master and 7.x
336
+ await Promise.all(ownerBranches
337
+ .filter((b) => b.name !== 'master' && b.name !== '7.x')
338
+ .map((b) => {
339
+ return deleteBranchOnGithub({
340
+ accessToken,
341
+ repoOwner: REPO_OWNER,
342
+ repoName: REPO_NAME,
343
+ branchName: b.name,
344
+ });
345
+ }));
346
+ const forkBranches = await getBranchesOnGithub({
347
+ accessToken,
348
+ repoOwner: AUTHOR,
349
+ repoName: REPO_NAME,
350
+ });
351
+ // delete all branches except master and 7.x
352
+ await Promise.all(forkBranches
353
+ .filter((b) => b.name !== 'master' && b.name !== '7.x')
354
+ .map((b) => {
355
+ return deleteBranchOnGithub({
356
+ accessToken,
357
+ repoOwner: AUTHOR,
358
+ repoName: REPO_NAME,
359
+ branchName: b.name,
360
+ });
361
+ }));
362
+ await (0, sandbox_1.resetSandbox)(sandboxPath);
363
+ }
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const entrypoint_module_1 = require("../entrypoint.module");
4
- const child_process_promisified_1 = require("../services/child-process-promisified");
5
4
  const getDevAccessToken_1 = require("./private/getDevAccessToken");
6
5
  const sandbox_1 = require("./sandbox");
7
6
  jest.unmock('find-up');
@@ -38,7 +37,6 @@ describe('Handle unbackported pull requests', () => {
38
37
  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
- await (0, child_process_promisified_1.exec)('git init', { cwd: sandboxPath });
42
40
  const result = await (0, entrypoint_module_1.backportRun)({
43
41
  accessToken: accessToken,
44
42
  repoOwner: 'backport-org',
@@ -25,6 +25,17 @@ async function cherrypickAndCreateTargetPullRequest({ options, commits, targetBr
25
25
  const backportBranch = getBackportBranchName(targetBranch, commits);
26
26
  const repoForkOwner = (0, git_1.getRepoForkOwner)(options);
27
27
  (0, logger_1.consoleLog)(`\n${chalk_1.default.bold(`Backporting to ${targetBranch}:`)}`);
28
+ await (0, git_1.createBackportBranch)({ options, targetBranch, backportBranch });
29
+ await (0, sequentially_1.sequentially)(commits, (commit) => waitForCherrypick(options, commit, targetBranch));
30
+ if (options.resetAuthor) {
31
+ await (0, git_1.setCommitAuthor)(options, options.authenticatedUsername);
32
+ }
33
+ if (options.dryRun) {
34
+ (0, ora_1.ora)(options.ci).succeed('Dry run');
35
+ return { url: 'https://localhost/dry-run', didUpdate: false, number: 1337 };
36
+ }
37
+ await (0, git_1.pushBackportBranch)({ options, backportBranch });
38
+ await (0, git_1.deleteBackportBranch)({ options, backportBranch });
28
39
  const prPayload = {
29
40
  owner: options.repoOwner,
30
41
  repo: options.repoName,
@@ -33,13 +44,7 @@ async function cherrypickAndCreateTargetPullRequest({ options, commits, targetBr
33
44
  head: `${repoForkOwner}:${backportBranch}`,
34
45
  base: targetBranch, // eg. 7.x
35
46
  };
36
- const targetPullRequest = await backportViaFilesystem({
37
- options,
38
- prPayload,
39
- targetBranch,
40
- backportBranch,
41
- commits,
42
- });
47
+ const targetPullRequest = await (0, createPullRequest_1.createPullRequest)({ options, prPayload });
43
48
  // add assignees to target pull request
44
49
  const assignees = options.autoAssign
45
50
  ? [options.authenticatedUsername]
@@ -72,17 +77,6 @@ async function cherrypickAndCreateTargetPullRequest({ options, commits, targetBr
72
77
  return targetPullRequest;
73
78
  }
74
79
  exports.cherrypickAndCreateTargetPullRequest = cherrypickAndCreateTargetPullRequest;
75
- async function backportViaFilesystem({ options, prPayload, commits, targetBranch, backportBranch, }) {
76
- logger_1.logger.info('Backporting via filesystem');
77
- await (0, git_1.createBackportBranch)({ options, targetBranch, backportBranch });
78
- await (0, sequentially_1.sequentially)(commits, (commit) => waitForCherrypick(options, commit, targetBranch));
79
- if (options.resetAuthor) {
80
- await (0, git_1.setCommitAuthor)(options, options.authenticatedUsername);
81
- }
82
- await (0, git_1.pushBackportBranch)({ options, backportBranch });
83
- await (0, git_1.deleteBackportBranch)({ options, backportBranch });
84
- return (0, createPullRequest_1.createPullRequest)({ options, prPayload });
85
- }
86
80
  /*
87
81
  * Returns the name of the backport branch without remote name
88
82
  *
@@ -156,7 +156,7 @@ describe('cherrypickAndCreateTargetPullRequest', () => {
156
156
  expect(consoleLogSpy.mock.calls[1][0]).toMatchInlineSnapshot(`"View pull request: myHtmlUrl"`);
157
157
  });
158
158
  it('should start the spinner with the correct text', () => {
159
- expect(ora_1.default.mock.calls.map((call) => call[0]))
159
+ expect(ora_1.default.mock.calls.map((call) => call[0].text))
160
160
  .toMatchInlineSnapshot(`
161
161
  Array [
162
162
  "Pulling latest changes",
@@ -356,7 +356,7 @@ describe('cherrypickAndCreateTargetPullRequest', () => {
356
356
  expect(execSpy.mock.calls).toMatchSnapshot();
357
357
  });
358
358
  it('calls ora correctly', () => {
359
- expect(ora_1.default.mock.calls.map((call) => call[0]))
359
+ expect(ora_1.default.mock.calls.map((call) => call[0].text))
360
360
  .toMatchInlineSnapshot(`
361
361
  Array [
362
362
  "Pulling latest changes",
@@ -23,10 +23,12 @@ async function getCommits(options) {
23
23
  const spinner = (0, ora_1.ora)(options.ci).start();
24
24
  try {
25
25
  if (options.sha) {
26
- spinner.text = `Loading commit "${(0, commitFormatters_1.getShortSha)(options.sha)}"`;
27
- const commit = await (0, fetchCommitBySha_1.fetchCommitBySha)({ ...options, sha: options.sha });
28
- spinner.stopAndPersist(getOraPersistsOption('Select commit', commit.sourceCommit.message));
29
- return [commit];
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;
30
32
  }
31
33
  if (options.pullNumber) {
32
34
  spinner.text = `Loading pull request #${options.pullNumber}`;
@@ -1,17 +1,20 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.maybeSetupRepo = void 0;
4
- const promises_1 = require("fs/promises");
5
4
  const del = require("del");
6
- const ora = require("ora");
5
+ const HandledError_1 = require("../services/HandledError");
7
6
  const env_1 = require("../services/env");
8
7
  const git_1 = require("../services/git");
8
+ const ora_1 = require("./ora");
9
9
  async function maybeSetupRepo(options) {
10
10
  const repoPath = (0, env_1.getRepoPath)(options);
11
- const isAlreadyCloned = await getIsRepoCloned(repoPath);
11
+ const isAlreadyCloned = await getIsRepoCloned(options);
12
+ if (options.cwd.includes(repoPath)) {
13
+ throw new HandledError_1.HandledError(`Refusing to clone repo into "${repoPath}" when current working directory is "${options.cwd}". Please change backport directory via \`--dir\` option or run backport from another location`);
14
+ }
12
15
  // clone repo if folder does not already exists
13
16
  if (!isAlreadyCloned) {
14
- const spinner = ora().start();
17
+ const spinner = (0, ora_1.ora)(options.ci).start();
15
18
  try {
16
19
  const sourcePath = await (0, git_1.getSourceRepoPath)(options);
17
20
  const sourcePathHumanReadable = sourcePath.includes(options.gitHostname)
@@ -19,6 +22,7 @@ async function maybeSetupRepo(options) {
19
22
  : sourcePath;
20
23
  const spinnerCloneText = `Cloning repository from ${sourcePathHumanReadable} (one-time operation)`;
21
24
  spinner.text = `0% ${spinnerCloneText}`;
25
+ await del(repoPath, { force: true });
22
26
  await (0, git_1.cloneRepo)({ sourcePath, targetPath: repoPath }, (progress) => {
23
27
  spinner.text = `${progress}% ${spinnerCloneText}`;
24
28
  });
@@ -26,7 +30,7 @@ async function maybeSetupRepo(options) {
26
30
  }
27
31
  catch (e) {
28
32
  spinner.fail();
29
- await del(repoPath);
33
+ await del(repoPath, { force: true });
30
34
  throw e;
31
35
  }
32
36
  }
@@ -42,15 +46,8 @@ async function maybeSetupRepo(options) {
42
46
  }
43
47
  }
44
48
  exports.maybeSetupRepo = maybeSetupRepo;
45
- async function getIsRepoCloned(path) {
46
- try {
47
- const stats = await (0, promises_1.stat)(path);
48
- return stats.isDirectory();
49
- }
50
- catch (e) {
51
- if (e.code === 'ENOENT') {
52
- return false;
53
- }
54
- throw e;
55
- }
49
+ async function getIsRepoCloned(options) {
50
+ const repoPath = (0, env_1.getRepoPath)(options);
51
+ const projectRoot = await (0, git_1.getGitProjectRoot)(repoPath);
52
+ return repoPath === projectRoot;
56
53
  }
@@ -22,14 +22,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
22
22
  return (mod && mod.__esModule) ? mod : { "default": mod };
23
23
  };
24
24
  Object.defineProperty(exports, "__esModule", { value: true });
25
- const promises_1 = require("fs/promises");
26
25
  const os_1 = __importDefault(require("os"));
27
26
  const del_1 = __importDefault(require("del"));
28
27
  const childProcess = __importStar(require("../services/child-process-promisified"));
29
28
  const git = __importStar(require("../services/git"));
30
29
  const mocks_1 = require("../test/mocks");
31
30
  const maybeSetupRepo_1 = require("./maybeSetupRepo");
32
- const fs = { stat: promises_1.stat };
33
31
  describe('maybeSetupRepo', () => {
34
32
  let execSpy;
35
33
  beforeEach(() => {
@@ -55,8 +53,9 @@ describe('maybeSetupRepo', () => {
55
53
  await expect((0, maybeSetupRepo_1.maybeSetupRepo)({
56
54
  repoName: 'kibana',
57
55
  repoOwner: 'elastic',
56
+ cwd: '/path/to/source/repo',
58
57
  })).rejects.toThrowError('Simulated git clone failure');
59
- expect(del_1.default).toHaveBeenCalledWith('/myHomeDir/.backport/repositories/elastic/kibana');
58
+ expect(del_1.default).toHaveBeenCalledWith('/myHomeDir/.backport/repositories/elastic/kibana', { force: true });
60
59
  });
61
60
  });
62
61
  describe('while cloning the repo', () => {
@@ -100,6 +99,7 @@ describe('maybeSetupRepo', () => {
100
99
  await (0, maybeSetupRepo_1.maybeSetupRepo)({
101
100
  repoName: 'kibana',
102
101
  repoOwner: 'elastic',
102
+ cwd: '/path/to/source/repo',
103
103
  });
104
104
  expect(spinnerTextSpy.mock.calls.map((call) => call[0]))
105
105
  .toMatchInlineSnapshot(`
@@ -120,8 +120,6 @@ describe('maybeSetupRepo', () => {
120
120
  });
121
121
  describe('if repo already exists', () => {
122
122
  beforeEach(() => {
123
- // @ts-expect-error
124
- jest.spyOn(fs, 'stat').mockResolvedValue({ isDirectory: () => true });
125
123
  jest
126
124
  .spyOn(childProcess, 'execAsCallback')
127
125
  //@ts-expect-error
@@ -139,21 +137,42 @@ describe('maybeSetupRepo', () => {
139
137
  authenticatedUsername: 'sqren_authenticated',
140
138
  repoName: 'kibana',
141
139
  repoOwner: 'elastic',
140
+ cwd: '/path/to/source/repo',
142
141
  });
143
- expect(execSpy.mock.calls.map(([cmd]) => cmd)).toEqual([
144
- 'git remote --verbose',
145
- 'git remote rm origin',
146
- 'git remote rm sqren_authenticated',
147
- 'git remote add sqren_authenticated https://x-access-token:myAccessToken@github.com/sqren_authenticated/kibana.git',
148
- 'git remote rm elastic',
149
- 'git remote add elastic https://x-access-token:myAccessToken@github.com/elastic/kibana.git',
142
+ expect(execSpy.mock.calls.map(([cmd, { cwd }]) => ({ cmd, cwd }))).toEqual([
143
+ {
144
+ cmd: 'git rev-parse --show-toplevel',
145
+ cwd: '/myHomeDir/.backport/repositories/elastic/kibana',
146
+ },
147
+ {
148
+ cmd: 'git remote --verbose',
149
+ cwd: '/path/to/source/repo',
150
+ },
151
+ {
152
+ cmd: 'git remote rm origin',
153
+ cwd: '/myHomeDir/.backport/repositories/elastic/kibana',
154
+ },
155
+ {
156
+ cmd: 'git remote rm sqren_authenticated',
157
+ cwd: '/myHomeDir/.backport/repositories/elastic/kibana',
158
+ },
159
+ {
160
+ cmd: 'git remote add sqren_authenticated https://x-access-token:myAccessToken@github.com/sqren_authenticated/kibana.git',
161
+ cwd: '/myHomeDir/.backport/repositories/elastic/kibana',
162
+ },
163
+ {
164
+ cmd: 'git remote rm elastic',
165
+ cwd: '/myHomeDir/.backport/repositories/elastic/kibana',
166
+ },
167
+ {
168
+ cmd: 'git remote add elastic https://x-access-token:myAccessToken@github.com/elastic/kibana.git',
169
+ cwd: '/myHomeDir/.backport/repositories/elastic/kibana',
170
+ },
150
171
  ]);
151
172
  });
152
173
  });
153
174
  describe('if repo does not exists locally', () => {
154
175
  beforeEach(() => {
155
- // @ts-expect-error
156
- jest.spyOn(fs, 'stat').mockResolvedValue({ isDirectory: () => true });
157
176
  jest
158
177
  .spyOn(childProcess, 'execAsCallback')
159
178
  //@ts-expect-error
@@ -171,14 +190,13 @@ describe('maybeSetupRepo', () => {
171
190
  gitHostname: 'github.com',
172
191
  repoName: 'kibana',
173
192
  repoOwner: 'elastic',
193
+ cwd: '/path/to/source/repo',
174
194
  });
175
195
  expect(childProcess.execAsCallback).toHaveBeenCalledWith('git clone https://x-access-token:myAccessToken@github.com/elastic/kibana.git /myHomeDir/.backport/repositories/elastic/kibana --progress', expect.any(Object), expect.any(Function));
176
196
  });
177
197
  });
178
198
  describe('if repo does exist locally', () => {
179
199
  beforeEach(() => {
180
- // @ts-expect-error
181
- jest.spyOn(fs, 'stat').mockResolvedValue({ isDirectory: () => true });
182
200
  jest
183
201
  .spyOn(git, 'getSourceRepoPath')
184
202
  .mockResolvedValue('/path/to/source/repo');
@@ -197,8 +215,24 @@ describe('maybeSetupRepo', () => {
197
215
  await (0, maybeSetupRepo_1.maybeSetupRepo)({
198
216
  repoName: 'kibana',
199
217
  repoOwner: 'elastic',
218
+ cwd: '/path/to/source/repo',
200
219
  });
201
220
  expect(childProcess.execAsCallback).toHaveBeenCalledWith('git clone /path/to/source/repo /myHomeDir/.backport/repositories/elastic/kibana --progress', expect.any(Object), expect.any(Function));
202
221
  });
203
222
  });
223
+ describe('if `repoPath` is a parent of current working directory (cwd)', () => {
224
+ beforeEach(() => {
225
+ jest
226
+ .spyOn(git, 'getSourceRepoPath')
227
+ .mockResolvedValue('/path/to/source/repo');
228
+ jest.spyOn(childProcess, 'execAsCallback');
229
+ });
230
+ it('should clone it from local folder', async () => {
231
+ await expect(() => (0, maybeSetupRepo_1.maybeSetupRepo)({
232
+ repoName: 'kibana',
233
+ repoOwner: 'elastic',
234
+ cwd: '/myHomeDir/.backport/repositories/elastic/kibana/foo',
235
+ })).rejects.toThrowError('Refusing to clone repo into "/myHomeDir/.backport/repositories/elastic/kibana" when current working directory is "/myHomeDir/.backport/repositories/elastic/kibana/foo". Please change backport directory via `--dir` option or run backport from another location');
236
+ });
237
+ });
204
238
  });
package/dist/ui/ora.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import oraOriginal from 'ora';
2
- export declare function ora(ci: boolean | undefined, options?: string | oraOriginal.Options | undefined): oraOriginal.Ora | {
2
+ export declare function ora(ci: boolean | undefined, text?: string | undefined): oraOriginal.Ora | {
3
3
  start: (text?: string | undefined) => any;
4
4
  succeed: () => void;
5
5
  stop: () => void;