backport 7.3.6 → 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 (245) hide show
  1. package/README.md +16 -21
  2. package/dist/backportRun.d.ts +18 -6
  3. package/dist/backportRun.js +70 -50
  4. package/dist/entrypoint.cli.js +4 -8
  5. package/dist/entrypoint.module.d.ts +13 -6
  6. package/dist/entrypoint.module.js +17 -19
  7. package/dist/entrypoint.module.private.test.js +129 -330
  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 +6 -4
  151. package/dist/options/cliArgs.d.ts +16 -9
  152. package/dist/options/cliArgs.js +54 -28
  153. package/dist/options/cliArgs.test.js +128 -4
  154. package/dist/options/config/config.d.ts +7 -6
  155. package/dist/options/config/config.js +5 -7
  156. package/dist/options/config/config.test.js +0 -1
  157. package/dist/options/config/globalConfig.d.ts +5 -3
  158. package/dist/options/config/globalConfig.js +17 -14
  159. package/dist/options/config/projectConfig.d.ts +2 -2
  160. package/dist/options/config/projectConfig.js +3 -3
  161. package/dist/options/config/projectConfig.test.js +19 -7
  162. package/dist/options/config/readConfigFile.d.ts +9 -7
  163. package/dist/options/config/readConfigFile.js +2 -2
  164. package/dist/options/options.d.ts +44 -9
  165. package/dist/options/options.js +22 -27
  166. package/dist/options/options.test.js +119 -58
  167. package/dist/runSequentially.d.ts +14 -7
  168. package/dist/runSequentially.js +26 -11
  169. package/dist/scripts/postinstall.js +4 -3
  170. package/dist/scripts/postinstall.test.js +6 -2
  171. package/dist/services/BackportError.d.ts +19 -0
  172. package/dist/services/BackportError.js +29 -0
  173. package/dist/services/HandledBackportError.d.ts +19 -0
  174. package/dist/services/HandledBackportError.js +29 -0
  175. package/dist/services/HandledError.d.ts +7 -3
  176. package/dist/services/HandledError.js +13 -13
  177. package/dist/services/child-process-promisified.d.ts +19 -3
  178. package/dist/services/child-process-promisified.js +46 -17
  179. package/dist/services/git.d.ts +6 -7
  180. package/dist/services/git.integration.test.js +381 -65
  181. package/dist/services/git.js +189 -127
  182. package/dist/services/git.private.test.d.ts +1 -0
  183. package/dist/services/git.private.test.js +618 -0
  184. package/dist/services/git.test.js +167 -158
  185. package/dist/services/github/v3/addAssigneesToPullRequest.js +1 -1
  186. package/dist/services/github/v3/addLabelsToPullRequest.js +1 -1
  187. package/dist/services/github/v3/addReviewersToPullRequest.js +2 -1
  188. package/dist/services/github/v3/createPullRequest.js +4 -2
  189. package/dist/services/github/v3/createStatusComment.js +17 -17
  190. package/dist/services/github/v3/createStatusComment.test.js +22 -9
  191. package/dist/services/github/v4/apiRequestV4.js +8 -11
  192. package/dist/services/github/v4/apiRequestV4.test.js +2 -2
  193. package/dist/services/github/v4/enablePullRequestAutoMerge.js +2 -4
  194. package/dist/services/github/v4/fetchAuthorId.private.test.js +3 -6
  195. package/dist/services/github/v4/fetchCommits/allFetchers.private.test.js +5 -6
  196. package/dist/services/github/v4/fetchCommits/fetchCommitByPullNumber.js +4 -3
  197. package/dist/services/github/v4/fetchCommits/fetchCommitByPullNumber.private.test.js +10 -9
  198. package/dist/services/github/v4/fetchCommits/fetchCommitBySha.js +3 -2
  199. package/dist/services/github/v4/fetchCommits/fetchCommitBySha.private.test.js +10 -9
  200. package/dist/services/github/v4/fetchCommits/fetchCommitsByAuthor.js +4 -3
  201. package/dist/services/github/v4/fetchCommits/fetchCommitsByAuthor.private.test.js +9 -8
  202. package/dist/services/github/v4/fetchCommits/fetchPullRequestBySearchQuery.private.test.js +3 -6
  203. package/dist/services/github/v4/fetchCommits/fetchPullRequestsBySearchQuery.js +3 -2
  204. package/dist/services/github/v4/fetchExistingPullRequest.private.test.js +3 -6
  205. package/dist/services/github/v4/fetchRemoteProjectConfig.private.test.js +4 -7
  206. package/dist/services/github/v4/getOptionsFromGithub/getOptionsFromGithub.d.ts +2 -2
  207. package/dist/services/github/v4/getOptionsFromGithub/getOptionsFromGithub.js +2 -2
  208. package/dist/services/github/v4/getOptionsFromGithub/getOptionsFromGithub.private.test.js +6 -7
  209. package/dist/services/github/v4/getRepoOwnerAndNameFromGitRemotes.private.test.js +9 -8
  210. package/dist/services/github/v4/throwOnInvalidAccessToken.js +5 -5
  211. package/dist/services/logger.d.ts +1 -4
  212. package/dist/services/logger.js +14 -19
  213. package/dist/services/test.d.ts +1 -0
  214. package/dist/services/test.js +23 -0
  215. package/dist/state.d.ts +0 -0
  216. package/dist/state.js +1 -0
  217. package/dist/test/e2e/cli/commit-author.private.test.js +4 -4
  218. package/dist/test/e2e/cli/different-merge-strategies.private.test.js +26 -24
  219. package/dist/test/e2e/cli/entrypoint.cli.private.test.d.ts +1 -0
  220. package/dist/test/e2e/cli/entrypoint.cli.private.test.js +450 -0
  221. package/dist/test/e2e/cli/repo-with-backportrc-removed.private.test.js +27 -28
  222. package/dist/test/e2e/cli/runBackportViaCli.d.ts +6 -2
  223. package/dist/test/e2e/cli/runBackportViaCli.js +44 -23
  224. package/dist/test/e2e/cli/test-that-repo-can-be-cloned.private.test.js +22 -14
  225. package/dist/test/e2e/module/entrypoint.module.mutation.test.d.ts +1 -0
  226. package/dist/test/e2e/module/entrypoint.module.mutation.test.js +376 -0
  227. package/dist/test/handleUnbackportedPullRequests.private.test.js +12 -10
  228. package/dist/test/sandbox.js +5 -1
  229. package/dist/test/setupFiles/automatic-mocks.js +17 -13
  230. package/dist/ui/cherrypickAndCreateTargetPullRequest.js +11 -7
  231. package/dist/ui/cherrypickAndCreateTargetPullRequest.test.js +7 -159
  232. package/dist/ui/getCommits.js +2 -2
  233. package/dist/ui/getCommitsWithoutBackports.test.js +5 -1
  234. package/dist/ui/getGitConfigAuthor.js +1 -1
  235. package/dist/ui/getTargetBranches.js +3 -3
  236. package/dist/ui/getTargetBranches.test.js +5 -1
  237. package/dist/ui/ora.d.ts +1 -8
  238. package/dist/ui/setupRepo.js +3 -3
  239. package/dist/ui/setupRepo.test.js +98 -61
  240. package/dist/utils/isErrnoError.d.ts +2 -0
  241. package/dist/utils/isErrnoError.js +7 -0
  242. package/dist/utils/packageVersion.d.ts +1 -1
  243. package/dist/utils/packageVersion.js +1 -1
  244. package/package.json +17 -17
  245. package/yarn.lock +461 -695
@@ -0,0 +1,7 @@
1
+ import { GithubV4Exception } from './apiRequestV4';
2
+ export declare function throwOnInvalidAccessToken({ error, repoOwner, repoName, globalConfigFile, }: {
3
+ error: GithubV4Exception<unknown>;
4
+ repoOwner: string;
5
+ repoName: string;
6
+ globalConfigFile?: string;
7
+ }): undefined;
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.throwOnInvalidAccessToken = void 0;
4
+ const lodash_1 = require("lodash");
5
+ const maybe_1 = require("../../../utils/maybe");
6
+ const BackportError_1 = require("../../BackportError");
7
+ const env_1 = require("../../env");
8
+ function throwOnInvalidAccessToken({ error, repoOwner, repoName, globalConfigFile, }) {
9
+ function getSSOAuthUrl(ssoHeader) {
10
+ const matches = ssoHeader?.match(/url=(.*)/);
11
+ if (matches) {
12
+ return matches[1];
13
+ }
14
+ }
15
+ const statusCode = error.githubResponse.status;
16
+ switch (statusCode) {
17
+ case 200: {
18
+ const repoNotFound = error.githubResponse.data.errors?.some((error) => error.type === 'NOT_FOUND' && error.path?.join('.') === 'repository');
19
+ const grantedScopes = error.githubResponse.headers['x-oauth-scopes'] || '';
20
+ const requiredScopes = error.githubResponse.headers['x-accepted-oauth-scopes'] || '';
21
+ const ssoHeader = (0, maybe_1.maybe)(error.githubResponse.headers['x-github-sso']);
22
+ if (repoNotFound) {
23
+ const hasRequiredScopes = (0, lodash_1.isEmpty)((0, lodash_1.difference)(requiredScopes.split(','), grantedScopes.split(',')));
24
+ // user does not have permission to the repo
25
+ if (!hasRequiredScopes) {
26
+ throw new BackportError_1.BackportError(`You do not have access to the repository "${repoOwner}/${repoName}". Please make sure your access token has the required scopes.\n\nRequired scopes: ${requiredScopes}\nAccess token scopes: ${grantedScopes}`);
27
+ }
28
+ // repo does not exist
29
+ throw new BackportError_1.BackportError(`The repository "${repoOwner}/${repoName}" doesn't exist`);
30
+ }
31
+ const repoAccessForbidden = error.githubResponse.data.errors?.some((error) => error.type === 'FORBIDDEN');
32
+ const ssoAuthUrl = getSSOAuthUrl(ssoHeader);
33
+ // user does not have permissions
34
+ if (repoAccessForbidden && ssoAuthUrl) {
35
+ throw new BackportError_1.BackportError(`Please follow the link to authorize your personal access token with SSO:\n\n${ssoAuthUrl}`);
36
+ }
37
+ break;
38
+ }
39
+ case 401:
40
+ throw new BackportError_1.BackportError(`Please check your access token and make sure it is valid.\nConfig: ${(0, env_1.getGlobalConfigPath)(globalConfigFile)}`);
41
+ default:
42
+ return undefined;
43
+ }
44
+ }
45
+ exports.throwOnInvalidAccessToken = throwOnInvalidAccessToken;
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const throwOnInvalidAccessToken_1 = require("./throwOnInvalidAccessToken");
4
+ describe('throwOnInvalidAccessToken', () => {
5
+ describe('when status code is', () => {
6
+ it('should handle invalid access token', () => {
7
+ const error = {
8
+ githubResponse: {
9
+ status: 401,
10
+ headers: {},
11
+ },
12
+ };
13
+ return expect(() => (0, throwOnInvalidAccessToken_1.throwOnInvalidAccessToken)({
14
+ repoOwner: 'elastic',
15
+ repoName: 'kibana',
16
+ error,
17
+ })).toThrowError('Please check your access token and make sure it is valid');
18
+ });
19
+ it('should handle SSO error', () => {
20
+ const error = {
21
+ githubResponse: {
22
+ status: 200,
23
+ headers: { 'x-github-sso': 'required; url=https://ssourl.com' },
24
+ data: {
25
+ errors: [{ type: 'FORBIDDEN' }],
26
+ },
27
+ },
28
+ };
29
+ return expect(() => (0, throwOnInvalidAccessToken_1.throwOnInvalidAccessToken)({
30
+ repoOwner: 'elastic',
31
+ repoName: 'kibana',
32
+ error,
33
+ })).toThrowErrorMatchingSnapshot();
34
+ });
35
+ it('should handle non-existing repo', () => {
36
+ const error = {
37
+ githubResponse: {
38
+ status: 200,
39
+ headers: {
40
+ 'x-oauth-scopes': 'a,b,c',
41
+ 'x-accepted-oauth-scopes': 'a,b,c',
42
+ },
43
+ data: {
44
+ errors: [{ type: 'NOT_FOUND', path: ['repository'] }],
45
+ },
46
+ },
47
+ };
48
+ return expect(() => (0, throwOnInvalidAccessToken_1.throwOnInvalidAccessToken)({
49
+ repoOwner: 'elastic',
50
+ repoName: 'kibana',
51
+ error,
52
+ })).toThrowError(`The repository "elastic/kibana" doesn't exist`);
53
+ });
54
+ it('should handle insufficient permissions (oauth scopes)', () => {
55
+ const error = {
56
+ githubResponse: {
57
+ status: 200,
58
+ headers: {
59
+ 'x-oauth-scopes': 'a,b',
60
+ 'x-accepted-oauth-scopes': 'a,b,c',
61
+ },
62
+ data: {
63
+ errors: [{ type: 'NOT_FOUND', path: ['repository'] }],
64
+ },
65
+ },
66
+ };
67
+ return expect(() => (0, throwOnInvalidAccessToken_1.throwOnInvalidAccessToken)({
68
+ repoOwner: 'elastic',
69
+ repoName: 'kibana',
70
+ error,
71
+ })).toThrowErrorMatchingSnapshot();
72
+ });
73
+ it('should not handle unknown cases', () => {
74
+ const error = {
75
+ githubResponse: {
76
+ status: 500,
77
+ headers: {},
78
+ },
79
+ };
80
+ return expect((0, throwOnInvalidAccessToken_1.throwOnInvalidAccessToken)({
81
+ repoOwner: 'elastic',
82
+ repoName: 'kibana',
83
+ error,
84
+ })).toBe(undefined);
85
+ });
86
+ });
87
+ });
@@ -0,0 +1,9 @@
1
+ import winston from 'winston';
2
+ export declare let logger: winston.Logger;
3
+ export declare function initLogger({ interactive, accessToken, logFilePath, }: {
4
+ interactive: boolean;
5
+ accessToken?: string;
6
+ logFilePath?: string;
7
+ }): winston.Logger;
8
+ export declare function consoleLog(message: string): void;
9
+ export declare function setAccessToken(accessToken: string): void;
@@ -0,0 +1,74 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.setAccessToken = exports.consoleLog = exports.initLogger = exports.logger = void 0;
27
+ const winston_1 = __importStar(require("winston"));
28
+ const redact_1 = require("../utils/redact");
29
+ const env_1 = require("./env");
30
+ let _accessToken;
31
+ let _interactive;
32
+ function initLogger({ interactive, accessToken, logFilePath, }) {
33
+ _accessToken = accessToken;
34
+ _interactive = interactive;
35
+ exports.logger = winston_1.default.createLogger({
36
+ format: winston_1.format.combine(winston_1.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
37
+ // Format the metadata object
38
+ winston_1.format.metadata({
39
+ fillExcept: ['message', 'level', 'timestamp', 'label'],
40
+ })),
41
+ transports: new winston_1.default.transports.File({
42
+ filename: (0, env_1.getLogfilePath)({ logFilePath }),
43
+ level: 'debug',
44
+ format: winston_1.format.combine(winston_1.format.json()),
45
+ }),
46
+ });
47
+ return exports.logger;
48
+ }
49
+ exports.initLogger = initLogger;
50
+ // wrapper around console.log
51
+ function consoleLog(message) {
52
+ if (_interactive) {
53
+ // eslint-disable-next-line no-console
54
+ console.log(redactAccessToken(message));
55
+ }
56
+ }
57
+ exports.consoleLog = consoleLog;
58
+ function setAccessToken(accessToken) {
59
+ _accessToken = accessToken;
60
+ }
61
+ exports.setAccessToken = setAccessToken;
62
+ function redactAccessToken(str) {
63
+ // `redactAccessToken` might be called before access token is set
64
+ if (_accessToken) {
65
+ return (0, redact_1.redact)(_accessToken, str);
66
+ }
67
+ return str;
68
+ }
69
+ // log levels:
70
+ // - error
71
+ // - warn
72
+ // - info
73
+ // - verbose
74
+ // - debug
@@ -0,0 +1,2 @@
1
+ import oraOriginal from 'ora';
2
+ export declare function ora(interactive: boolean | undefined, text?: string | undefined): oraOriginal.Ora;
@@ -0,0 +1,21 @@
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.ora = void 0;
7
+ const ora_1 = __importDefault(require("ora"));
8
+ /* eslint-disable @typescript-eslint/no-empty-function */
9
+ const oraMock = {
10
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
11
+ start: (text) => oraMock,
12
+ succeed: () => { },
13
+ stop: () => { },
14
+ fail: () => { },
15
+ stopAndPersist: () => { },
16
+ set text(value) { },
17
+ };
18
+ function ora(interactive, text) {
19
+ return interactive ? (0, ora_1.default)({ text }) : oraMock;
20
+ }
21
+ exports.ora = ora;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,139 @@
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 strip_ansi_1 = __importDefault(require("strip-ansi"));
7
+ const prompts_1 = require("./prompts");
8
+ describe('prompt', () => {
9
+ describe('getChoicesForCommitPrompt', () => {
10
+ it('should display status badges via `expectedTargetPullRequests`', () => {
11
+ const commits = [
12
+ {
13
+ author: { email: 'soren.louv@elastic.co', name: 'Søren Louv-Jansen' },
14
+ sourceBranch: 'master',
15
+ sourceCommit: {
16
+ committedDate: '1',
17
+ sha: 'ae9d51b7fe3ee6f30d0d196c782e0dcabb7ac5ff',
18
+ message: '[APM] Remove log-log descriptions from correlation charts (#119700)',
19
+ },
20
+ sourcePullRequest: {
21
+ number: 119700,
22
+ url: 'foo',
23
+ mergeCommit: {
24
+ sha: 'ae9d51b7fe3ee6f30d0d196c782e0dcabb7ac5ff',
25
+ message: '[APM] Remove log-log descriptions from correlation charts (#119700)',
26
+ },
27
+ },
28
+ expectedTargetPullRequests: [
29
+ { number: 120178, branch: '8.0', state: 'MERGED' },
30
+ { number: 120179, branch: '7.16', state: 'MERGED' },
31
+ { number: 120179, branch: '7.15', state: 'NOT_CREATED' },
32
+ ],
33
+ },
34
+ ];
35
+ const choices = (0, prompts_1.getChoicesForCommitPrompt)(commits, false).map(({ name, short }) => ({ name: (0, strip_ansi_1.default)(name), short }));
36
+ expect(choices).toEqual([
37
+ {
38
+ name: '1. [APM] Remove log-log descriptions from correlation charts (#119700) 8.0, 7.16, 7.15',
39
+ short: '#119700 (ae9d51b7)',
40
+ },
41
+ ]);
42
+ });
43
+ it('should list choices', () => {
44
+ const commits = [
45
+ {
46
+ author: { email: 'soren.louv@elastic.co', name: 'Søren Louv-Jansen' },
47
+ sourceBranch: 'master',
48
+ sourceCommit: {
49
+ committedDate: '',
50
+ sha: 'b1b491959dab47aeb83c88ee2accb2db46d23793',
51
+ message: '[APM] Prefer service.name for logs correlation (#120694)',
52
+ },
53
+ sourcePullRequest: {
54
+ number: 120694,
55
+ url: 'foo',
56
+ mergeCommit: {
57
+ sha: 'b1b491959dab47aeb83c88ee2accb2db46d23793',
58
+ message: '[APM] Prefer service.name for logs correlation (#120694)',
59
+ },
60
+ },
61
+ expectedTargetPullRequests: [],
62
+ },
63
+ {
64
+ author: { email: 'soren.louv@elastic.co', name: 'Søren Louv-Jansen' },
65
+ sourceBranch: 'master',
66
+ sourceCommit: {
67
+ committedDate: '',
68
+ sha: 'b1bb4a93959f19a653b9cfb207a5c6acb6559482',
69
+ message: '[APM] Disable telemetry in agent config endpoint (#120106)',
70
+ },
71
+ sourcePullRequest: {
72
+ number: 120106,
73
+ url: 'foo',
74
+ mergeCommit: {
75
+ sha: 'b1bb4a93959f19a653b9cfb207a5c6acb6559482',
76
+ message: '[APM] Disable telemetry in agent config endpoint (#120106)',
77
+ },
78
+ },
79
+ expectedTargetPullRequests: [],
80
+ },
81
+ {
82
+ author: { email: 'soren.louv@elastic.co', name: 'Søren Louv-Jansen' },
83
+ sourceBranch: 'master',
84
+ sourceCommit: {
85
+ committedDate: '',
86
+ sha: '434f6e6a88faf24dc1ea41f9f726db78e46355a7',
87
+ message: '[APM] Remove index_pattern.json and add custom field formatters (#119915)',
88
+ },
89
+ sourcePullRequest: {
90
+ number: 119915,
91
+ url: 'foo',
92
+ mergeCommit: {
93
+ sha: '434f6e6a88faf24dc1ea41f9f726db78e46355a7',
94
+ message: '[APM] Remove index_pattern.json and add custom field formatters (#119915)',
95
+ },
96
+ },
97
+ expectedTargetPullRequests: [],
98
+ },
99
+ {
100
+ author: { email: 'soren.louv@elastic.co', name: 'Søren Louv-Jansen' },
101
+ sourceBranch: 'master',
102
+ sourceCommit: {
103
+ committedDate: '',
104
+ sha: 'ae9d51b7fe3ee6f30d0d196c782e0dcabb7ac5ff',
105
+ message: '[APM] Remove log-log descriptions from correlation charts (#119700)',
106
+ },
107
+ sourcePullRequest: {
108
+ number: 119700,
109
+ url: 'foo',
110
+ mergeCommit: {
111
+ sha: 'ae9d51b7fe3ee6f30d0d196c782e0dcabb7ac5ff',
112
+ message: '[APM] Remove log-log descriptions from correlation charts (#119700)',
113
+ },
114
+ },
115
+ expectedTargetPullRequests: [],
116
+ },
117
+ ];
118
+ const choices = (0, prompts_1.getChoicesForCommitPrompt)(commits, false).map(({ name, short }) => ({ name: (0, strip_ansi_1.default)(name), short }));
119
+ expect(choices).toEqual([
120
+ {
121
+ name: '1. [APM] Prefer service.name for logs correlation (#120694) ',
122
+ short: '#120694 (b1b49195)',
123
+ },
124
+ {
125
+ name: '2. [APM] Disable telemetry in agent config endpoint (#120106) ',
126
+ short: '#120106 (b1bb4a93)',
127
+ },
128
+ {
129
+ name: '3. [APM] Remove index_pattern.json and add custom field formatters (#119915) ',
130
+ short: '#119915 (434f6e6a)',
131
+ },
132
+ {
133
+ name: '4. [APM] Remove log-log descriptions from correlation charts (#119700) ',
134
+ short: '#119700 (ae9d51b7)',
135
+ },
136
+ ]);
137
+ });
138
+ });
139
+ });
@@ -0,0 +1,17 @@
1
+ import { TargetBranchChoice } from '../options/ConfigOptions';
2
+ import { Commit } from './sourceCommit/parseSourceCommit';
3
+ export declare function getChoicesForCommitPrompt(commits: Commit[], showDetails: boolean): {
4
+ name: string;
5
+ short: string;
6
+ value: Commit;
7
+ }[];
8
+ export declare function promptForCommits({ commitChoices, isMultipleChoice, showDetails, }: {
9
+ commitChoices: Commit[];
10
+ isMultipleChoice: boolean;
11
+ showDetails: boolean;
12
+ }): Promise<Commit[]>;
13
+ export declare function promptForTargetBranches({ targetBranchChoices, isMultipleChoice, }: {
14
+ targetBranchChoices: TargetBranchChoice[];
15
+ isMultipleChoice: boolean;
16
+ }): Promise<string[]>;
17
+ export declare function confirmPrompt(message: string): Promise<boolean>;
@@ -0,0 +1,132 @@
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.confirmPrompt = exports.promptForTargetBranches = exports.promptForCommits = exports.getChoicesForCommitPrompt = void 0;
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ const inquirer_1 = __importDefault(require("inquirer"));
9
+ const lodash_1 = require("lodash");
10
+ const terminal_link_1 = __importDefault(require("terminal-link"));
11
+ const commitFormatters_1 = require("./github/commitFormatters");
12
+ async function prompt(options) {
13
+ const { promptResult } = (await inquirer_1.default.prompt([
14
+ { ...options, name: 'promptResult' },
15
+ ]));
16
+ return promptResult;
17
+ }
18
+ function getPrStateIcon(state) {
19
+ if (state === 'MERGED') {
20
+ return '🟢';
21
+ }
22
+ if (state === 'NOT_CREATED') {
23
+ return '🔴';
24
+ }
25
+ if (state === 'OPEN') {
26
+ return '🔵';
27
+ }
28
+ // unknown state
29
+ return '🔴';
30
+ }
31
+ function getPrStateText(state) {
32
+ if (state === 'MERGED') {
33
+ return chalk_1.default.gray('Merged');
34
+ }
35
+ if (state === 'NOT_CREATED') {
36
+ return chalk_1.default.gray('Backport not created');
37
+ }
38
+ if (state === 'OPEN') {
39
+ return chalk_1.default.gray('Open, not merged');
40
+ }
41
+ return chalk_1.default.gray('Unknown state');
42
+ }
43
+ function getPrLink(number, url) {
44
+ return url ? `(${(0, terminal_link_1.default)(`#${number}`, url)})` : '';
45
+ }
46
+ function getDetailedPullStatus(c) {
47
+ const items = c.expectedTargetPullRequests.map((pr) => {
48
+ const prLink = getPrLink(pr.number, pr.url);
49
+ return ` └ ${getPrStateIcon(pr.state)} ${pr.branch} ${prLink} ${getPrStateText(pr.state)}`;
50
+ });
51
+ const list = items.length > 0
52
+ ? `\n${chalk_1.default.reset(items.join('\n'))}`
53
+ : `\n └ ${chalk_1.default.gray('No backports expected')}`;
54
+ return `${list}\n`;
55
+ }
56
+ function getSimplePullStatus(c) {
57
+ return c.expectedTargetPullRequests
58
+ .map(({ state, branch }) => {
59
+ if (state === 'MERGED') {
60
+ return chalk_1.default.green(branch);
61
+ }
62
+ if (state === 'NOT_CREATED') {
63
+ return chalk_1.default.red(branch);
64
+ }
65
+ if (state === 'OPEN') {
66
+ return chalk_1.default.gray(branch);
67
+ }
68
+ return chalk_1.default.gray('Unknown state');
69
+ })
70
+ .join(', ');
71
+ }
72
+ function getChoicesForCommitPrompt(commits, showDetails) {
73
+ return commits.map((c, i) => {
74
+ const leadingWhitespace = (0, lodash_1.repeat)(' ', 2 - (i + 1).toString().length);
75
+ const position = chalk_1.default.gray(`${i + 1}.${leadingWhitespace}`);
76
+ let name;
77
+ if (showDetails) {
78
+ const message = (0, commitFormatters_1.stripPullNumber)(c.sourceCommit.message);
79
+ const prLink = c.sourcePullRequest
80
+ ? ` ` + getPrLink(c.sourcePullRequest.number, c.sourcePullRequest.url)
81
+ : '';
82
+ const pullStatus = getDetailedPullStatus(c);
83
+ name = `${position}${message}${prLink}${pullStatus}`;
84
+ }
85
+ else {
86
+ const message = (0, commitFormatters_1.getFirstLine)(c.sourceCommit.message);
87
+ const pullStatus = getSimplePullStatus(c);
88
+ name = `${position}${message} ${pullStatus}`;
89
+ }
90
+ const short = c.sourcePullRequest
91
+ ? `#${c.sourcePullRequest.number} (${(0, commitFormatters_1.getShortSha)(c.sourcePullRequest.mergeCommit.sha)})`
92
+ : (0, commitFormatters_1.getShortSha)(c.sourceCommit.sha);
93
+ return { name, short, value: c };
94
+ });
95
+ }
96
+ exports.getChoicesForCommitPrompt = getChoicesForCommitPrompt;
97
+ async function promptForCommits({ commitChoices, isMultipleChoice, showDetails, }) {
98
+ const choices = getChoicesForCommitPrompt(commitChoices, showDetails);
99
+ const res = await prompt({
100
+ loop: false,
101
+ pageSize: 30,
102
+ choices: choices,
103
+ message: 'Select commit',
104
+ type: isMultipleChoice ? 'checkbox' : 'list',
105
+ });
106
+ const selectedCommits = Array.isArray(res) ? res.reverse() : [res];
107
+ return (0, lodash_1.isEmpty)(selectedCommits)
108
+ ? promptForCommits({ commitChoices, isMultipleChoice, showDetails })
109
+ : selectedCommits;
110
+ }
111
+ exports.promptForCommits = promptForCommits;
112
+ async function promptForTargetBranches({ targetBranchChoices, isMultipleChoice, }) {
113
+ const res = await prompt({
114
+ loop: false,
115
+ pageSize: 15,
116
+ choices: targetBranchChoices,
117
+ message: 'Select branch',
118
+ type: isMultipleChoice ? 'checkbox' : 'list',
119
+ });
120
+ const selectedBranches = Array.isArray(res) ? res : [res];
121
+ return (0, lodash_1.isEmpty)(selectedBranches)
122
+ ? promptForTargetBranches({
123
+ targetBranchChoices,
124
+ isMultipleChoice,
125
+ })
126
+ : selectedBranches;
127
+ }
128
+ exports.promptForTargetBranches = promptForTargetBranches;
129
+ function confirmPrompt(message) {
130
+ return prompt({ message, type: 'confirm' });
131
+ }
132
+ exports.confirmPrompt = confirmPrompt;
@@ -0,0 +1,20 @@
1
+ import { ConfigFileOptions } from '../entrypoint.module';
2
+ import { GithubV4Exception } from './github/v4/apiRequestV4';
3
+ export declare const RemoteConfigHistoryFragment: import("graphql").DocumentNode;
4
+ export interface RemoteConfig {
5
+ committedDate: string;
6
+ file: {
7
+ object: {
8
+ text: string;
9
+ };
10
+ };
11
+ }
12
+ export interface RemoteConfigHistory {
13
+ remoteConfigHistory: {
14
+ edges: Array<{
15
+ remoteConfig: RemoteConfig;
16
+ }> | null;
17
+ };
18
+ }
19
+ export declare function parseRemoteConfig(remoteConfig: RemoteConfig): ConfigFileOptions | undefined;
20
+ export declare function swallowMissingConfigFileException<T>(error: GithubV4Exception<T>): T;
@@ -0,0 +1,52 @@
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.swallowMissingConfigFileException = exports.parseRemoteConfig = exports.RemoteConfigHistoryFragment = void 0;
7
+ const graphql_tag_1 = __importDefault(require("graphql-tag"));
8
+ const readConfigFile_1 = require("../options/config/readConfigFile");
9
+ const logger_1 = require("./logger");
10
+ exports.RemoteConfigHistoryFragment = (0, graphql_tag_1.default) `
11
+ fragment RemoteConfigHistoryFragment on Commit {
12
+ remoteConfigHistory: history(first: 1, path: ".backportrc.json") {
13
+ edges {
14
+ remoteConfig: node {
15
+ committedDate
16
+ file(path: ".backportrc.json") {
17
+ ... on TreeEntry {
18
+ object {
19
+ ... on Blob {
20
+ text
21
+ }
22
+ }
23
+ }
24
+ }
25
+ }
26
+ }
27
+ }
28
+ }
29
+ `;
30
+ function parseRemoteConfig(remoteConfig) {
31
+ try {
32
+ return (0, readConfigFile_1.withConfigMigrations)(JSON.parse(remoteConfig.file.object.text));
33
+ }
34
+ catch (e) {
35
+ logger_1.logger.info('Parsing remote config failed', e);
36
+ return;
37
+ }
38
+ }
39
+ exports.parseRemoteConfig = parseRemoteConfig;
40
+ function swallowMissingConfigFileException(error) {
41
+ const { data, errors } = error.githubResponse.data;
42
+ const missingConfigError = errors?.some((error) => {
43
+ return error.path?.includes('remoteConfig') && error.type === 'NOT_FOUND';
44
+ });
45
+ // swallow error if it's just the config file that's missing
46
+ if (missingConfigError && data != null) {
47
+ return data;
48
+ }
49
+ // Throw unexpected error
50
+ throw error;
51
+ }
52
+ exports.swallowMissingConfigFileException = swallowMissingConfigFileException;
@@ -0,0 +1 @@
1
+ export declare function sequentially<T>(items: T[], handler: (item: T) => Promise<void>): Promise<void>;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sequentially = void 0;
4
+ function sequentially(items, handler) {
5
+ return items.reduce(async (p, item) => {
6
+ await p;
7
+ return handler(item);
8
+ }, Promise.resolve());
9
+ }
10
+ exports.sequentially = sequentially;
@@ -0,0 +1,2 @@
1
+ import { ValidConfigOptions } from '../options/options';
2
+ export declare function setupRepo(options: ValidConfigOptions): Promise<void>;