Skip to content

Commit

Permalink
fix(gh-96): fix git token parsing (#98)
Browse files Browse the repository at this point in the history
  • Loading branch information
lampajr committed Feb 23, 2024
1 parent 2c5c546 commit c57fca6
Show file tree
Hide file tree
Showing 14 changed files with 324 additions and 342 deletions.
113 changes: 63 additions & 50 deletions dist/cli/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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";
/**
Expand Down Expand Up @@ -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;


/***/ }),
Expand Down Expand Up @@ -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
Expand All @@ -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;
Expand Down
113 changes: 63 additions & 50 deletions dist/gha/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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";
/**
Expand Down Expand Up @@ -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;


/***/ }),
Expand Down Expand Up @@ -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
Expand All @@ -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;
Expand Down
41 changes: 1 addition & 40 deletions src/service/configs/configs-parser.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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 !== ""];
}
}

0 comments on commit c57fca6

Please sign in to comment.