diff --git a/dist/cli/index.js b/dist/cli/index.js index 2f6ab30..df9bcc2 100755 --- a/dist/cli/index.js +++ b/dist/cli/index.js @@ -251,9 +251,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const configs_types_1 = __nccwpck_require__(4753); const logger_service_factory_1 = __importDefault(__nccwpck_require__(8936)); -const git_types_1 = __nccwpck_require__(750); /** * Abstract configuration parser class in charge to parse * Args and produces a common Configs object @@ -275,42 +273,6 @@ class ConfigsParser { } return Promise.resolve(configs); } - /** - * Retrieve the git token from env variable, the default is taken from GIT_TOKEN env. - * All specific git env variable have precedence and override the default one. - * @param gitType - * @returns tuple where - * - the first element is the corresponding env value - * - the second element is true if the value is not undefined nor empty - */ - getGitTokenFromEnv(gitType) { - let [token] = this.getEnv(configs_types_1.AuthTokenId.GIT_TOKEN); - let [specToken, specOk] = [undefined, false]; - if (git_types_1.GitClientType.GITHUB == gitType) { - [specToken, specOk] = this.getEnv(configs_types_1.AuthTokenId.GITHUB_TOKEN); - } - else if (git_types_1.GitClientType.GITLAB == gitType) { - [specToken, specOk] = this.getEnv(configs_types_1.AuthTokenId.GITLAB_TOKEN); - } - else if (git_types_1.GitClientType.CODEBERG == gitType) { - [specToken, specOk] = this.getEnv(configs_types_1.AuthTokenId.CODEBERG_TOKEN); - } - if (specOk) { - token = specToken; - } - return token; - } - /** - * Get process env variable given the input key string - * @param key - * @returns tuple where - * - the first element is the corresponding env value - * - the second element is true if the value is not undefined nor empty - */ - getEnv(key) { - const val = process.env[key]; - return [val, val !== undefined && val !== ""]; - } } exports["default"] = ConfigsParser; @@ -371,18 +333,9 @@ class PullRequestConfigsParser extends configs_parser_1.default { if (bpBranchNames.length > 1 && bpBranchNames.length != targetBranches.length) { throw new Error(`The number of backport branch names, if provided, must match the number of target branches or just one, provided ${bpBranchNames.length} branch names instead`); } - // setup the auth token - let token = args.auth; - if (token === undefined) { - this.logger.info("Auth argument not provided, checking available tokens from env.."); - token = this.getGitTokenFromEnv(this.gitClient.getClientType()); - if (!token) { - this.logger.info("Git token not set in the env"); - } - } return { dryRun: args.dryRun, - auth: token, + auth: args.auth, folder: `${folder.startsWith("/") ? "" : process.cwd() + "/"}${args.folder ?? this.getDefaultFolder()}`, mergeStrategy: args.strategy, mergeStrategyOption: args.strategyOption, @@ -662,8 +615,9 @@ GitClientFactory.logger = logger_service_factory_1.default.getLogger(); "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.inferGitApiUrl = exports.inferGitClient = void 0; +exports.getEnv = exports.getGitTokenFromEnv = exports.inferGitApiUrl = exports.inferGitClient = void 0; const git_types_1 = __nccwpck_require__(750); +const configs_types_1 = __nccwpck_require__(4753); const PUBLIC_GITHUB_URL = "https://github.com"; const PUBLIC_GITHUB_API = "https://api.github.com"; /** @@ -701,6 +655,44 @@ const inferGitApiUrl = (prUrl, apiVersion = "v4") => { return `${baseUrl}/api/${apiVersion}`; }; exports.inferGitApiUrl = inferGitApiUrl; +/** + * Retrieve the git token from env variable, the default is taken from GIT_TOKEN env. + * All specific git env variable have precedence and override the default one. + * @param gitType + * @returns tuple where + * - the first element is the corresponding env value + * - the second element is true if the value is not undefined nor empty + */ +const getGitTokenFromEnv = (gitType) => { + let [token] = (0, exports.getEnv)(configs_types_1.AuthTokenId.GIT_TOKEN); + let [specToken, specOk] = [undefined, false]; + if (git_types_1.GitClientType.GITHUB == gitType) { + [specToken, specOk] = (0, exports.getEnv)(configs_types_1.AuthTokenId.GITHUB_TOKEN); + } + else if (git_types_1.GitClientType.GITLAB == gitType) { + [specToken, specOk] = (0, exports.getEnv)(configs_types_1.AuthTokenId.GITLAB_TOKEN); + } + else if (git_types_1.GitClientType.CODEBERG == gitType) { + [specToken, specOk] = (0, exports.getEnv)(configs_types_1.AuthTokenId.CODEBERG_TOKEN); + } + if (specOk) { + token = specToken; + } + return token; +}; +exports.getGitTokenFromEnv = getGitTokenFromEnv; +/** + * Get process env variable given the input key string + * @param key + * @returns tuple where + * - the first element is the corresponding env value + * - the second element is true if the value is not undefined nor empty + */ +const getEnv = (key) => { + const val = process.env[key]; + return [val, val !== undefined && val !== ""]; +}; +exports.getEnv = getEnv; /***/ }), @@ -1354,9 +1346,11 @@ class Runner { const gitClientType = (0, git_util_1.inferGitClient)(args.pullRequest); // the api version is ignored in case of github const apiUrl = (0, git_util_1.inferGitApiUrl)(args.pullRequest, gitClientType === git_types_1.GitClientType.CODEBERG ? "v1" : undefined); - const gitApi = git_client_factory_1.default.getOrCreate(gitClientType, args.auth, apiUrl); + const token = this.fetchToken(args, gitClientType); + const gitApi = git_client_factory_1.default.getOrCreate(gitClientType, token, apiUrl); // 3. parse configs this.logger.debug("Parsing configs.."); + args.auth = token; // override auth const configs = await new pr_configs_parser_1.default().parseAndValidate(args); const backportPRs = configs.backportPullRequests; // start local git operations @@ -1381,6 +1375,25 @@ class Runner { throw new Error(`Failure occurred during one of the backports: [${failures.join(" ; ")}]`); } } + /** + * Fetch the GIT token from the provided Args obj, if not empty, otherwise fallback + * to the environment variables. + * @param args input arguments + * @param gitType git client type + * @returns the provided or fetched token, or undefined if not set anywhere + */ + fetchToken(args, gitType) { + let token = args.auth; + if (token === undefined) { + // try to fetch the auth from env variable + this.logger.info("Auth argument not provided, checking available tokens from env.."); + token = (0, git_util_1.getGitTokenFromEnv)(gitType); + if (!token) { + this.logger.info("Git token not found in the environment"); + } + } + return token; + } async executeBackport(configs, backportPR, git) { this.logger.setContext(backportPR.base); const originalPR = configs.originalPullRequest; diff --git a/dist/gha/index.js b/dist/gha/index.js index 60b0fea..529a401 100755 --- a/dist/gha/index.js +++ b/dist/gha/index.js @@ -221,9 +221,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const configs_types_1 = __nccwpck_require__(4753); const logger_service_factory_1 = __importDefault(__nccwpck_require__(8936)); -const git_types_1 = __nccwpck_require__(750); /** * Abstract configuration parser class in charge to parse * Args and produces a common Configs object @@ -245,42 +243,6 @@ class ConfigsParser { } return Promise.resolve(configs); } - /** - * Retrieve the git token from env variable, the default is taken from GIT_TOKEN env. - * All specific git env variable have precedence and override the default one. - * @param gitType - * @returns tuple where - * - the first element is the corresponding env value - * - the second element is true if the value is not undefined nor empty - */ - getGitTokenFromEnv(gitType) { - let [token] = this.getEnv(configs_types_1.AuthTokenId.GIT_TOKEN); - let [specToken, specOk] = [undefined, false]; - if (git_types_1.GitClientType.GITHUB == gitType) { - [specToken, specOk] = this.getEnv(configs_types_1.AuthTokenId.GITHUB_TOKEN); - } - else if (git_types_1.GitClientType.GITLAB == gitType) { - [specToken, specOk] = this.getEnv(configs_types_1.AuthTokenId.GITLAB_TOKEN); - } - else if (git_types_1.GitClientType.CODEBERG == gitType) { - [specToken, specOk] = this.getEnv(configs_types_1.AuthTokenId.CODEBERG_TOKEN); - } - if (specOk) { - token = specToken; - } - return token; - } - /** - * Get process env variable given the input key string - * @param key - * @returns tuple where - * - the first element is the corresponding env value - * - the second element is true if the value is not undefined nor empty - */ - getEnv(key) { - const val = process.env[key]; - return [val, val !== undefined && val !== ""]; - } } exports["default"] = ConfigsParser; @@ -341,18 +303,9 @@ class PullRequestConfigsParser extends configs_parser_1.default { if (bpBranchNames.length > 1 && bpBranchNames.length != targetBranches.length) { throw new Error(`The number of backport branch names, if provided, must match the number of target branches or just one, provided ${bpBranchNames.length} branch names instead`); } - // setup the auth token - let token = args.auth; - if (token === undefined) { - this.logger.info("Auth argument not provided, checking available tokens from env.."); - token = this.getGitTokenFromEnv(this.gitClient.getClientType()); - if (!token) { - this.logger.info("Git token not set in the env"); - } - } return { dryRun: args.dryRun, - auth: token, + auth: args.auth, folder: `${folder.startsWith("/") ? "" : process.cwd() + "/"}${args.folder ?? this.getDefaultFolder()}`, mergeStrategy: args.strategy, mergeStrategyOption: args.strategyOption, @@ -632,8 +585,9 @@ GitClientFactory.logger = logger_service_factory_1.default.getLogger(); "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.inferGitApiUrl = exports.inferGitClient = void 0; +exports.getEnv = exports.getGitTokenFromEnv = exports.inferGitApiUrl = exports.inferGitClient = void 0; const git_types_1 = __nccwpck_require__(750); +const configs_types_1 = __nccwpck_require__(4753); const PUBLIC_GITHUB_URL = "https://github.com"; const PUBLIC_GITHUB_API = "https://api.github.com"; /** @@ -671,6 +625,44 @@ const inferGitApiUrl = (prUrl, apiVersion = "v4") => { return `${baseUrl}/api/${apiVersion}`; }; exports.inferGitApiUrl = inferGitApiUrl; +/** + * Retrieve the git token from env variable, the default is taken from GIT_TOKEN env. + * All specific git env variable have precedence and override the default one. + * @param gitType + * @returns tuple where + * - the first element is the corresponding env value + * - the second element is true if the value is not undefined nor empty + */ +const getGitTokenFromEnv = (gitType) => { + let [token] = (0, exports.getEnv)(configs_types_1.AuthTokenId.GIT_TOKEN); + let [specToken, specOk] = [undefined, false]; + if (git_types_1.GitClientType.GITHUB == gitType) { + [specToken, specOk] = (0, exports.getEnv)(configs_types_1.AuthTokenId.GITHUB_TOKEN); + } + else if (git_types_1.GitClientType.GITLAB == gitType) { + [specToken, specOk] = (0, exports.getEnv)(configs_types_1.AuthTokenId.GITLAB_TOKEN); + } + else if (git_types_1.GitClientType.CODEBERG == gitType) { + [specToken, specOk] = (0, exports.getEnv)(configs_types_1.AuthTokenId.CODEBERG_TOKEN); + } + if (specOk) { + token = specToken; + } + return token; +}; +exports.getGitTokenFromEnv = getGitTokenFromEnv; +/** + * Get process env variable given the input key string + * @param key + * @returns tuple where + * - the first element is the corresponding env value + * - the second element is true if the value is not undefined nor empty + */ +const getEnv = (key) => { + const val = process.env[key]; + return [val, val !== undefined && val !== ""]; +}; +exports.getEnv = getEnv; /***/ }), @@ -1324,9 +1316,11 @@ class Runner { const gitClientType = (0, git_util_1.inferGitClient)(args.pullRequest); // the api version is ignored in case of github const apiUrl = (0, git_util_1.inferGitApiUrl)(args.pullRequest, gitClientType === git_types_1.GitClientType.CODEBERG ? "v1" : undefined); - const gitApi = git_client_factory_1.default.getOrCreate(gitClientType, args.auth, apiUrl); + const token = this.fetchToken(args, gitClientType); + const gitApi = git_client_factory_1.default.getOrCreate(gitClientType, token, apiUrl); // 3. parse configs this.logger.debug("Parsing configs.."); + args.auth = token; // override auth const configs = await new pr_configs_parser_1.default().parseAndValidate(args); const backportPRs = configs.backportPullRequests; // start local git operations @@ -1351,6 +1345,25 @@ class Runner { throw new Error(`Failure occurred during one of the backports: [${failures.join(" ; ")}]`); } } + /** + * Fetch the GIT token from the provided Args obj, if not empty, otherwise fallback + * to the environment variables. + * @param args input arguments + * @param gitType git client type + * @returns the provided or fetched token, or undefined if not set anywhere + */ + fetchToken(args, gitType) { + let token = args.auth; + if (token === undefined) { + // try to fetch the auth from env variable + this.logger.info("Auth argument not provided, checking available tokens from env.."); + token = (0, git_util_1.getGitTokenFromEnv)(gitType); + if (!token) { + this.logger.info("Git token not found in the environment"); + } + } + return token; + } async executeBackport(configs, backportPR, git) { this.logger.setContext(backportPR.base); const originalPR = configs.originalPullRequest; diff --git a/src/service/configs/configs-parser.ts b/src/service/configs/configs-parser.ts index 379e39b..5b901cb 100644 --- a/src/service/configs/configs-parser.ts +++ b/src/service/configs/configs-parser.ts @@ -1,8 +1,7 @@ import { Args } from "@bp/service/args/args.types"; -import { AuthTokenId, Configs } from "@bp/service/configs/configs.types"; +import { Configs } from "@bp/service/configs/configs.types"; import LoggerService from "../logger/logger-service"; import LoggerServiceFactory from "../logger/logger-service-factory"; -import { GitClientType } from "../git/git.types"; /** * Abstract configuration parser class in charge to parse @@ -35,42 +34,4 @@ import { GitClientType } from "../git/git.types"; return Promise.resolve(configs); } - - /** - * Retrieve the git token from env variable, the default is taken from GIT_TOKEN env. - * All specific git env variable have precedence and override the default one. - * @param gitType - * @returns tuple where - * - the first element is the corresponding env value - * - the second element is true if the value is not undefined nor empty - */ - public getGitTokenFromEnv(gitType: GitClientType): string | undefined { - let [token] = this.getEnv(AuthTokenId.GIT_TOKEN); - let [specToken, specOk]: [string | undefined, boolean] = [undefined, false]; - if (GitClientType.GITHUB == gitType) { - [specToken, specOk] = this.getEnv(AuthTokenId.GITHUB_TOKEN); - } else if (GitClientType.GITLAB == gitType) { - [specToken, specOk] = this.getEnv(AuthTokenId.GITLAB_TOKEN); - } else if (GitClientType.CODEBERG == gitType) { - [specToken, specOk] = this.getEnv(AuthTokenId.CODEBERG_TOKEN); - } - - if (specOk) { - token = specToken; - } - - return token; - } - - /** - * Get process env variable given the input key string - * @param key - * @returns tuple where - * - the first element is the corresponding env value - * - the second element is true if the value is not undefined nor empty - */ - public getEnv(key: string): [string | undefined, boolean] { - const val = process.env[key]; - return [val, val !== undefined && val !== ""]; - } } \ No newline at end of file diff --git a/src/service/configs/pullrequest/pr-configs-parser.ts b/src/service/configs/pullrequest/pr-configs-parser.ts index 34c3c88..cca2c8d 100644 --- a/src/service/configs/pullrequest/pr-configs-parser.ts +++ b/src/service/configs/pullrequest/pr-configs-parser.ts @@ -33,19 +33,9 @@ export default class PullRequestConfigsParser extends ConfigsParser { throw new Error(`The number of backport branch names, if provided, must match the number of target branches or just one, provided ${bpBranchNames.length} branch names instead`); } - // setup the auth token - let token = args.auth; - if (token === undefined) { - this.logger.info("Auth argument not provided, checking available tokens from env.."); - token = this.getGitTokenFromEnv(this.gitClient.getClientType()); - if (!token) { - this.logger.info("Git token not set in the env"); - } - } - return { dryRun: args.dryRun!, - auth: token, + auth: args.auth, // this has been already pre-processed before parsing configs folder: `${folder.startsWith("/") ? "" : process.cwd() + "/"}${args.folder ?? this.getDefaultFolder()}`, mergeStrategy: args.strategy, mergeStrategyOption: args.strategyOption, diff --git a/src/service/git/git-util.ts b/src/service/git/git-util.ts index 2ac1f2b..67d32ff 100644 --- a/src/service/git/git-util.ts +++ b/src/service/git/git-util.ts @@ -1,4 +1,5 @@ import { GitClientType } from "@bp/service/git/git.types"; +import { AuthTokenId } from "@bp/service/configs/configs.types"; const PUBLIC_GITHUB_URL = "https://github.com"; const PUBLIC_GITHUB_API = "https://api.github.com"; @@ -38,4 +39,42 @@ export const inferGitApiUrl = (prUrl: string, apiVersion = "v4"): string => { } return `${baseUrl}/api/${apiVersion}`; +}; + +/** + * Retrieve the git token from env variable, the default is taken from GIT_TOKEN env. + * All specific git env variable have precedence and override the default one. + * @param gitType + * @returns tuple where + * - the first element is the corresponding env value + * - the second element is true if the value is not undefined nor empty + */ +export const getGitTokenFromEnv = (gitType: GitClientType): string | undefined => { + let [token] = getEnv(AuthTokenId.GIT_TOKEN); + let [specToken, specOk]: [string | undefined, boolean] = [undefined, false]; + if (GitClientType.GITHUB == gitType) { + [specToken, specOk] = getEnv(AuthTokenId.GITHUB_TOKEN); + } else if (GitClientType.GITLAB == gitType) { + [specToken, specOk] = getEnv(AuthTokenId.GITLAB_TOKEN); + } else if (GitClientType.CODEBERG == gitType) { + [specToken, specOk] = getEnv(AuthTokenId.CODEBERG_TOKEN); + } + + if (specOk) { + token = specToken; + } + + return token; +}; + +/** + * Get process env variable given the input key string + * @param key + * @returns tuple where + * - the first element is the corresponding env value + * - the second element is true if the value is not undefined nor empty + */ +export const getEnv = (key: string): [string | undefined, boolean] => { + const val = process.env[key]; + return [val, val !== undefined && val !== ""]; }; \ No newline at end of file diff --git a/src/service/runner/runner.ts b/src/service/runner/runner.ts index ce6d543..1e48193 100644 --- a/src/service/runner/runner.ts +++ b/src/service/runner/runner.ts @@ -8,7 +8,7 @@ import GitClientFactory from "@bp/service/git/git-client-factory"; import { BackportPullRequest, GitClientType, GitPullRequest } from "@bp/service/git/git.types"; import LoggerService from "@bp/service/logger/logger-service"; import LoggerServiceFactory from "@bp/service/logger/logger-service-factory"; -import { inferGitClient, inferGitApiUrl } from "@bp/service/git/git-util"; +import { inferGitClient, inferGitApiUrl, getGitTokenFromEnv } from "@bp/service/git/git-util"; interface Git { gitClientType: GitClientType; @@ -63,10 +63,12 @@ export default class Runner { const gitClientType: GitClientType = inferGitClient(args.pullRequest); // the api version is ignored in case of github const apiUrl = inferGitApiUrl(args.pullRequest, gitClientType === GitClientType.CODEBERG ? "v1" : undefined); - const gitApi: GitClient = GitClientFactory.getOrCreate(gitClientType, args.auth, apiUrl); + const token = this.fetchToken(args, gitClientType); + const gitApi: GitClient = GitClientFactory.getOrCreate(gitClientType, token, apiUrl); // 3. parse configs this.logger.debug("Parsing configs.."); + args.auth = token; // override auth const configs: Configs = await new PullRequestConfigsParser().parseAndValidate(args); const backportPRs: BackportPullRequest[] = configs.backportPullRequests; @@ -94,6 +96,27 @@ export default class Runner { } } + /** + * Fetch the GIT token from the provided Args obj, if not empty, otherwise fallback + * to the environment variables. + * @param args input arguments + * @param gitType git client type + * @returns the provided or fetched token, or undefined if not set anywhere + */ + fetchToken(args: Args, gitType: GitClientType): string | undefined { + let token = args.auth; + if (token === undefined) { + // try to fetch the auth from env variable + this.logger.info("Auth argument not provided, checking available tokens from env.."); + token = getGitTokenFromEnv(gitType); + if (!token) { + this.logger.info("Git token not found in the environment"); + } + } + + return token; + } + async executeBackport(configs: Configs, backportPR: BackportPullRequest, git: Git): Promise { this.logger.setContext(backportPR.base); diff --git a/test/service/configs/pullrequest/github-pr-configs-parser-multiple.test.ts b/test/service/configs/pullrequest/github-pr-configs-parser-multiple.test.ts index 38adb10..eab1bfa 100644 --- a/test/service/configs/pullrequest/github-pr-configs-parser-multiple.test.ts +++ b/test/service/configs/pullrequest/github-pr-configs-parser-multiple.test.ts @@ -4,7 +4,7 @@ import PullRequestConfigsParser from "@bp/service/configs/pullrequest/pr-configs import GitClientFactory from "@bp/service/git/git-client-factory"; import { GitClientType } from "@bp/service/git/git.types"; import { mockGitHubClient } from "../../../support/mock/git-client-mock-support"; -import { resetEnvTokens, resetProcessArgs } from "../../../support/utils"; +import { resetProcessArgs } from "../../../support/utils"; import { MERGED_PR_FIXTURE, REPO, TARGET_OWNER, MULT_COMMITS_PR_FIXTURE } from "../../../support/mock/github-data"; import GitHubMapper from "@bp/service/git/github/github-mapper"; import GitHubClient from "@bp/service/git/github/github-client"; @@ -27,9 +27,6 @@ describe("github pull request config parser", () => { beforeEach(() => { // reset process.env variables resetProcessArgs(); - - // reset env tokens - resetEnvTokens(); // mock octokit mockGitHubClient("http://localhost/api/v3"); diff --git a/test/service/configs/pullrequest/github-pr-configs-parser.test.ts b/test/service/configs/pullrequest/github-pr-configs-parser.test.ts index a45def3..f392cc7 100644 --- a/test/service/configs/pullrequest/github-pr-configs-parser.test.ts +++ b/test/service/configs/pullrequest/github-pr-configs-parser.test.ts @@ -1,10 +1,10 @@ import { Args } from "@bp/service/args/args.types"; -import { AuthTokenId, Configs } from "@bp/service/configs/configs.types"; +import { Configs } from "@bp/service/configs/configs.types"; import PullRequestConfigsParser from "@bp/service/configs/pullrequest/pr-configs-parser"; import GitClientFactory from "@bp/service/git/git-client-factory"; import { GitClientType } from "@bp/service/git/git.types"; import { mockGitHubClient } from "../../../support/mock/git-client-mock-support"; -import { addProcessArgs, createTestFile, removeTestFile, resetEnvTokens, resetProcessArgs } from "../../../support/utils"; +import { addProcessArgs, createTestFile, removeTestFile, resetProcessArgs } from "../../../support/utils"; import { MERGED_PR_FIXTURE, OPEN_PR_FIXTURE, NOT_MERGED_PR_FIXTURE, REPO, TARGET_OWNER, MULT_COMMITS_PR_FIXTURE } from "../../../support/mock/github-data"; import CLIArgsParser from "@bp/service/args/cli/cli-args-parser"; import GitHubMapper from "@bp/service/git/github/github-mapper"; @@ -66,9 +66,6 @@ describe("github pull request config parser", () => { // reset process.env variables resetProcessArgs(); - // reset env tokens - resetEnvTokens(); - // mock octokit mockGitHubClient("http://localhost/api/v3"); @@ -842,82 +839,4 @@ describe("github pull request config parser", () => { comments: ["First comment", "Second comment"], }); }); - - test("override token using auth arg", async () => { - process.env[AuthTokenId.GITHUB_TOKEN] = "mygithubtoken"; - const args: Args = { - dryRun: true, - auth: "whatever", - pullRequest: mergedPRUrl, - targetBranch: "prod", - folder: "/tmp/test", - gitUser: "GitHub", - gitEmail: "noreply@github.com", - reviewers: [], - assignees: [], - inheritReviewers: true, - }; - - const configs: Configs = await configParser.parseAndValidate(args); - - expect(configs.dryRun).toEqual(true); - expect(configs.auth).toEqual("whatever"); - expect(configs.folder).toEqual("/tmp/test"); - expect(configs.git).toEqual({ - user: "GitHub", - email: "noreply@github.com" - }); - }); - - test("auth using GITHUB_TOKEN has precedence over GIT_TOKEN env variable", async () => { - process.env[AuthTokenId.GIT_TOKEN] = "mygittoken"; - process.env[AuthTokenId.GITHUB_TOKEN] = "mygithubtoken"; - const args: Args = { - dryRun: true, - pullRequest: mergedPRUrl, - targetBranch: "prod", - folder: "/tmp/test", - gitUser: "GitHub", - gitEmail: "noreply@github.com", - reviewers: [], - assignees: [], - inheritReviewers: true, - }; - - const configs: Configs = await configParser.parseAndValidate(args); - - expect(configs.dryRun).toEqual(true); - expect(configs.auth).toEqual("mygithubtoken"); - expect(configs.folder).toEqual("/tmp/test"); - expect(configs.git).toEqual({ - user: "GitHub", - email: "noreply@github.com" - }); - }); - - test("ignore env variables related to other git platforms", async () => { - process.env[AuthTokenId.GITLAB_TOKEN] = "mygitlabtoken"; - process.env[AuthTokenId.CODEBERG_TOKEN] = "mycodebergtoken"; - const args: Args = { - dryRun: true, - pullRequest: mergedPRUrl, - targetBranch: "prod", - folder: "/tmp/test", - gitUser: "GitHub", - gitEmail: "noreply@github.com", - reviewers: [], - assignees: [], - inheritReviewers: true, - }; - - const configs: Configs = await configParser.parseAndValidate(args); - - expect(configs.dryRun).toEqual(true); - expect(configs.auth).toEqual(undefined); - expect(configs.folder).toEqual("/tmp/test"); - expect(configs.git).toEqual({ - user: "GitHub", - email: "noreply@github.com" - }); - }); }); \ No newline at end of file diff --git a/test/service/configs/pullrequest/gitlab-pr-configs-parser-multiple.test.ts b/test/service/configs/pullrequest/gitlab-pr-configs-parser-multiple.test.ts index 842a9ca..deff8de 100644 --- a/test/service/configs/pullrequest/gitlab-pr-configs-parser-multiple.test.ts +++ b/test/service/configs/pullrequest/gitlab-pr-configs-parser-multiple.test.ts @@ -7,7 +7,6 @@ import { getAxiosMocked } from "../../../support/mock/git-client-mock-support"; import { MERGED_SQUASHED_MR } from "../../../support/mock/gitlab-data"; import GitLabClient from "@bp/service/git/gitlab/gitlab-client"; import GitLabMapper from "@bp/service/git/gitlab/gitlab-mapper"; -import { resetEnvTokens } from "../../../support/utils"; jest.spyOn(GitLabMapper.prototype, "mapPullRequest"); jest.spyOn(GitLabClient.prototype, "getPullRequest"); @@ -32,9 +31,6 @@ describe("gitlab merge request config parser", () => { }); beforeEach(() => { - // reset env tokens - resetEnvTokens(); - configParser = new PullRequestConfigsParser(); }); diff --git a/test/service/configs/pullrequest/gitlab-pr-configs-parser.test.ts b/test/service/configs/pullrequest/gitlab-pr-configs-parser.test.ts index 0c9248d..981cb25 100644 --- a/test/service/configs/pullrequest/gitlab-pr-configs-parser.test.ts +++ b/test/service/configs/pullrequest/gitlab-pr-configs-parser.test.ts @@ -1,5 +1,5 @@ import { Args } from "@bp/service/args/args.types"; -import { AuthTokenId, Configs } from "@bp/service/configs/configs.types"; +import { Configs } from "@bp/service/configs/configs.types"; import PullRequestConfigsParser from "@bp/service/configs/pullrequest/pr-configs-parser"; import GitClientFactory from "@bp/service/git/git-client-factory"; import { GitClientType } from "@bp/service/git/git.types"; @@ -798,97 +798,4 @@ describe("gitlab merge request config parser", () => { comments: ["First comment", "Second comment"], }); }); - - test("override token using auth arg", async () => { - process.env[AuthTokenId.GITLAB_TOKEN] = "mygitlabtoken"; - const args: Args = { - dryRun: true, - auth: "whatever", - pullRequest: mergedPRUrl, - targetBranch: "prod", - folder: "/tmp/test", - gitUser: "Gitlab", - gitEmail: "noreply@gitlab.com", - reviewers: [], - assignees: [], - inheritReviewers: true, - }; - - const configs: Configs = await configParser.parseAndValidate(args); - - expect(GitLabClient.prototype.getPullRequest).toBeCalledTimes(1); - expect(GitLabClient.prototype.getPullRequest).toBeCalledWith("superuser", "backporting-example", 1, true); - expect(GitLabMapper.prototype.mapPullRequest).toBeCalledTimes(1); - expect(GitLabMapper.prototype.mapPullRequest).toBeCalledWith(expect.anything(), []); - - expect(configs.dryRun).toEqual(true); - expect(configs.auth).toEqual("whatever"); - expect(configs.folder).toEqual("/tmp/test"); - expect(configs.git).toEqual({ - user: "Gitlab", - email: "noreply@gitlab.com" - }); - }); - - test("auth using GITLAB_TOKEN has precedence over GIT_TOKEN env variable", async () => { - process.env[AuthTokenId.GIT_TOKEN] = "mygittoken"; - process.env[AuthTokenId.GITLAB_TOKEN] = "mygitlabtoken"; - const args: Args = { - dryRun: true, - pullRequest: mergedPRUrl, - targetBranch: "prod", - folder: "/tmp/test", - gitUser: "Gitlab", - gitEmail: "noreply@gitlab.com", - reviewers: [], - assignees: [], - inheritReviewers: true, - }; - - const configs: Configs = await configParser.parseAndValidate(args); - - expect(GitLabClient.prototype.getPullRequest).toBeCalledTimes(1); - expect(GitLabClient.prototype.getPullRequest).toBeCalledWith("superuser", "backporting-example", 1, true); - expect(GitLabMapper.prototype.mapPullRequest).toBeCalledTimes(1); - expect(GitLabMapper.prototype.mapPullRequest).toBeCalledWith(expect.anything(), []); - - expect(configs.dryRun).toEqual(true); - expect(configs.auth).toEqual("mygitlabtoken"); - expect(configs.folder).toEqual("/tmp/test"); - expect(configs.git).toEqual({ - user: "Gitlab", - email: "noreply@gitlab.com" - }); - }); - - test("ignore env variables related to other git platforms", async () => { - process.env[AuthTokenId.CODEBERG_TOKEN] = "mycodebergtoken"; - process.env[AuthTokenId.GITHUB_TOKEN] = "mygithubtoken"; - const args: Args = { - dryRun: true, - pullRequest: mergedPRUrl, - targetBranch: "prod", - folder: "/tmp/test", - gitUser: "Gitlab", - gitEmail: "noreply@gitlab.com", - reviewers: [], - assignees: [], - inheritReviewers: true, - }; - - const configs: Configs = await configParser.parseAndValidate(args); - - expect(GitLabClient.prototype.getPullRequest).toBeCalledTimes(1); - expect(GitLabClient.prototype.getPullRequest).toBeCalledWith("superuser", "backporting-example", 1, true); - expect(GitLabMapper.prototype.mapPullRequest).toBeCalledTimes(1); - expect(GitLabMapper.prototype.mapPullRequest).toBeCalledWith(expect.anything(), []); - - expect(configs.dryRun).toEqual(true); - expect(configs.auth).toEqual(undefined); - expect(configs.folder).toEqual("/tmp/test"); - expect(configs.git).toEqual({ - user: "Gitlab", - email: "noreply@gitlab.com" - }); - }); }); \ No newline at end of file diff --git a/test/service/runner/cli-github-runner.test.ts b/test/service/runner/cli-github-runner.test.ts index bbd31da..7d747b4 100644 --- a/test/service/runner/cli-github-runner.test.ts +++ b/test/service/runner/cli-github-runner.test.ts @@ -3,10 +3,11 @@ import Runner from "@bp/service/runner/runner"; import GitCLIService from "@bp/service/git/git-cli"; import GitHubClient from "@bp/service/git/github/github-client"; import CLIArgsParser from "@bp/service/args/cli/cli-args-parser"; -import { addProcessArgs, createTestFile, removeTestFile, resetProcessArgs } from "../../support/utils"; +import { addProcessArgs, createTestFile, removeTestFile, resetEnvTokens, resetProcessArgs } from "../../support/utils"; import { mockGitHubClient } from "../../support/mock/git-client-mock-support"; import GitClientFactory from "@bp/service/git/git-client-factory"; import { BackportPullRequest, GitClientType } from "@bp/service/git/git.types"; +import { AuthTokenId } from "@bp/service/configs/configs.types"; const GITHUB_MERGED_PR_W_OVERRIDES_CONFIG_FILE_CONTENT_PATHNAME = "./cli-github-runner-pr-merged-with-overrides.json"; const GITHUB_MERGED_PR_W_OVERRIDES_CONFIG_FILE_CONTENT = { @@ -48,6 +49,9 @@ beforeEach(() => { // reset process.env variables resetProcessArgs(); + // reset git env tokens + resetEnvTokens(); + // mock octokit mockGitHubClient(); @@ -1104,4 +1108,59 @@ describe("cli runner", () => { }); expect(GitHubClient.prototype.createPullRequest).toThrowError(); }); + + test("auth using GITHUB_TOKEN takes precedence over GIT_TOKEN env variable", async () => { + process.env[AuthTokenId.GIT_TOKEN] = "mygittoken"; + process.env[AuthTokenId.GITHUB_TOKEN] = "mygithubtoken"; + addProcessArgs([ + "-tb", + "target", + "-pr", + "https://github.com/owner/reponame/pull/8632" + ]); + + await runner.execute(); + + expect(GitClientFactory.getOrCreate).toBeCalledTimes(1); + expect(GitClientFactory.getOrCreate).toBeCalledWith(GitClientType.GITHUB, "mygithubtoken", "https://api.github.com"); + + // Not interested in all subsequent calls, already tested in other test cases + }); + + test("auth arg takes precedence over GITHUB_TOKEN", async () => { + process.env[AuthTokenId.GITHUB_TOKEN] = "mygithubtoken"; + addProcessArgs([ + "-tb", + "target", + "-pr", + "https://github.com/owner/reponame/pull/8632", + "-a", + "mytoken" + ]); + + await runner.execute(); + + expect(GitClientFactory.getOrCreate).toBeCalledTimes(1); + expect(GitClientFactory.getOrCreate).toBeCalledWith(GitClientType.GITHUB, "mytoken", "https://api.github.com"); + + // Not interested in all subsequent calls, already tested in other test cases + }); + + test("ignore env variables related to other git platforms", async () => { + process.env[AuthTokenId.GITLAB_TOKEN] = "mygitlabtoken"; + process.env[AuthTokenId.CODEBERG_TOKEN] = "mycodebergtoken"; + addProcessArgs([ + "-tb", + "target", + "-pr", + "https://github.com/owner/reponame/pull/8632" + ]); + + await runner.execute(); + + expect(GitClientFactory.getOrCreate).toBeCalledTimes(1); + expect(GitClientFactory.getOrCreate).toBeCalledWith(GitClientType.GITHUB, undefined, "https://api.github.com"); + + // Not interested in all subsequent calls, already tested in other test cases + }); }); \ No newline at end of file diff --git a/test/service/runner/cli-gitlab-runner.test.ts b/test/service/runner/cli-gitlab-runner.test.ts index 92dc4d7..b5e985a 100644 --- a/test/service/runner/cli-gitlab-runner.test.ts +++ b/test/service/runner/cli-gitlab-runner.test.ts @@ -3,11 +3,12 @@ import Runner from "@bp/service/runner/runner"; import GitCLIService from "@bp/service/git/git-cli"; import GitLabClient from "@bp/service/git/gitlab/gitlab-client"; import CLIArgsParser from "@bp/service/args/cli/cli-args-parser"; -import { addProcessArgs, createTestFile, removeTestFile, resetProcessArgs } from "../../support/utils"; +import { addProcessArgs, createTestFile, removeTestFile, resetEnvTokens, resetProcessArgs } from "../../support/utils"; import { getAxiosMocked } from "../../support/mock/git-client-mock-support"; import { MERGED_SQUASHED_MR } from "../../support/mock/gitlab-data"; import GitClientFactory from "@bp/service/git/git-client-factory"; import { GitClientType } from "@bp/service/git/git.types"; +import { AuthTokenId } from "@bp/service/configs/configs.types"; const GITLAB_MERGED_PR_COMPLEX_CONFIG_FILE_CONTENT_PATHNAME = "./cli-gitlab-runner-pr-merged-with-overrides.json"; const GITLAB_MERGED_PR_COMPLEX_CONFIG_FILE_CONTENT = { @@ -63,6 +64,9 @@ beforeEach(() => { // reset process.env variables resetProcessArgs(); + // reset git env tokens + resetEnvTokens(); + // create CLI arguments parser parser = new CLIArgsParser(); @@ -595,4 +599,59 @@ describe("cli runner", () => { } ); }); + + test("auth using GITLAB_TOKEN takes precedence over GIT_TOKEN env variable", async () => { + process.env[AuthTokenId.GIT_TOKEN] = "mygittoken"; + process.env[AuthTokenId.GITLAB_TOKEN] = "mygitlabtoken"; + addProcessArgs([ + "-tb", + "target", + "-pr", + "https://my.gitlab.host.com/superuser/backporting-example/-/merge_requests/2" + ]); + + await runner.execute(); + + expect(GitClientFactory.getOrCreate).toBeCalledTimes(1); + expect(GitClientFactory.getOrCreate).toBeCalledWith(GitClientType.GITLAB, "mygitlabtoken", "https://my.gitlab.host.com/api/v4"); + + // Not interested in all subsequent calls, already tested in other test cases + }); + + test("auth arg takes precedence over GITLAB_TOKEN", async () => { + process.env[AuthTokenId.GITLAB_TOKEN] = "mygitlabtoken"; + addProcessArgs([ + "-tb", + "target", + "-pr", + "https://my.gitlab.host.com/superuser/backporting-example/-/merge_requests/2", + "-a", + "mytoken" + ]); + + await runner.execute(); + + expect(GitClientFactory.getOrCreate).toBeCalledTimes(1); + expect(GitClientFactory.getOrCreate).toBeCalledWith(GitClientType.GITLAB, "mytoken", "https://my.gitlab.host.com/api/v4"); + + // Not interested in all subsequent calls, already tested in other test cases + }); + + test("ignore env variables related to other git platforms", async () => { + process.env[AuthTokenId.GITHUB_TOKEN] = "mygithubtoken"; + process.env[AuthTokenId.CODEBERG_TOKEN] = "mycodebergtoken"; + addProcessArgs([ + "-tb", + "target", + "-pr", + "https://my.gitlab.host.com/superuser/backporting-example/-/merge_requests/2" + ]); + + await runner.execute(); + + expect(GitClientFactory.getOrCreate).toBeCalledTimes(1); + expect(GitClientFactory.getOrCreate).toBeCalledWith(GitClientType.GITLAB, undefined, "https://my.gitlab.host.com/api/v4"); + + // Not interested in all subsequent calls, already tested in other test cases + }); }); \ No newline at end of file diff --git a/test/service/runner/gha-github-runner.test.ts b/test/service/runner/gha-github-runner.test.ts index 3e9fd73..7976a9d 100644 --- a/test/service/runner/gha-github-runner.test.ts +++ b/test/service/runner/gha-github-runner.test.ts @@ -3,7 +3,7 @@ import Runner from "@bp/service/runner/runner"; import GitCLIService from "@bp/service/git/git-cli"; import GitHubClient from "@bp/service/git/github/github-client"; import GHAArgsParser from "@bp/service/args/gha/gha-args-parser"; -import { createTestFile, removeTestFile, spyGetInput } from "../../support/utils"; +import { createTestFile, removeTestFile, resetEnvTokens, spyGetInput } from "../../support/utils"; import { mockGitHubClient } from "../../support/mock/git-client-mock-support"; import GitClientFactory from "@bp/service/git/git-client-factory"; import { GitClientType } from "@bp/service/git/git.types"; @@ -46,6 +46,9 @@ afterAll(() => { }); beforeEach(() => { + // reset git env tokens + resetEnvTokens(); + mockGitHubClient(); // create GHA arguments parser diff --git a/test/service/runner/gha-gitlab-runner.test.ts b/test/service/runner/gha-gitlab-runner.test.ts index 748ca15..5212da8 100644 --- a/test/service/runner/gha-gitlab-runner.test.ts +++ b/test/service/runner/gha-gitlab-runner.test.ts @@ -3,7 +3,7 @@ import Runner from "@bp/service/runner/runner"; import GitCLIService from "@bp/service/git/git-cli"; import GitLabClient from "@bp/service/git/gitlab/gitlab-client"; import GHAArgsParser from "@bp/service/args/gha/gha-args-parser"; -import { createTestFile, removeTestFile, spyGetInput } from "../../support/utils"; +import { createTestFile, removeTestFile, resetEnvTokens, spyGetInput } from "../../support/utils"; import { getAxiosMocked } from "../../support/mock/git-client-mock-support"; import { MERGED_SQUASHED_MR } from "../../support/mock/gitlab-data"; import GitClientFactory from "@bp/service/git/git-client-factory"; @@ -59,6 +59,9 @@ afterAll(() => { }); beforeEach(() => { + // reset git env tokens + resetEnvTokens(); + // create GHA arguments parser parser = new GHAArgsParser();