feat: config file as option (#42)

Fix https://github.com/lampajr/backporting/issues/37

This enhancement required a huge refactoring where all arguments
defaults have been centralized in one single place ArgsParser#parse
This commit is contained in:
Andrea Lamparelli 2023-07-05 22:11:23 +02:00 committed by GitHub
parent a88adeec35
commit 5ead31f606
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
27 changed files with 1465 additions and 219 deletions

View file

@ -4,7 +4,38 @@ import { Args } from "@bp/service/args/args.types";
* Abstract arguments parser interface in charge to parse inputs and
* produce a common Args object
*/
export default interface ArgsParser {
export default abstract class ArgsParser {
parse(): Args;
abstract readArgs(): Args;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private getOrDefault(parsedValue: any, defaultValue?: any) {
return parsedValue === undefined ? defaultValue : parsedValue;
}
public parse(): Args {
const args = this.readArgs();
// validate and fill with defaults
if (!args.pullRequest || !args.targetBranch) {
throw new Error("Missing option: pull request and target branch must be provided");
}
return {
pullRequest: args.pullRequest,
targetBranch: args.targetBranch,
dryRun: this.getOrDefault(args.dryRun, false),
auth: this.getOrDefault(args.auth),
folder: this.getOrDefault(args.folder),
gitUser: this.getOrDefault(args.gitUser),
gitEmail: this.getOrDefault(args.gitEmail),
title: this.getOrDefault(args.title),
body: this.getOrDefault(args.body),
bodyPrefix: this.getOrDefault(args.bodyPrefix),
bpBranchName: this.getOrDefault(args.bpBranchName),
reviewers: this.getOrDefault(args.reviewers, []),
assignees: this.getOrDefault(args.assignees, []),
inheritReviewers: this.getOrDefault(args.inheritReviewers, true),
};
}
}

View file

@ -0,0 +1,22 @@
import { Args } from "@bp/service/args/args.types";
import * as fs from "fs";
/**
* Parse the input configuation string as json object and
* return it as Args
* @param configFileContent
* @returns {Args}
*/
export function parseArgs(configFileContent: string): Args {
return JSON.parse(configFileContent) as Args;
}
/**
* Read a configuration file in json format anf parse it as {Args}
* @param pathToFile Full path name of the config file, e.g., /tmp/dir/config-file.json
* @returns {Args}
*/
export function readConfigFile(pathToFile: string): Args {
const asString: string = fs.readFileSync(pathToFile, "utf-8");
return parseArgs(asString);
}

View file

@ -2,18 +2,18 @@
* Input arguments
*/
export interface Args {
dryRun: boolean, // if enabled do not push anything remotely
auth: string, // git service auth, like github token
targetBranch: string, // branch on the target repo where the change should be backported to
pullRequest: string, // url of the pull request to backport
dryRun?: boolean, // if enabled do not push anything remotely
auth?: string, // git service auth, like github token
folder?: string, // local folder where the repositories should be cloned
gitUser: string, // local git user, default 'GitHub'
gitEmail: string, // local git email, default 'noreply@github.com'
gitUser?: string, // local git user, default 'GitHub'
gitEmail?: string, // local git email, default 'noreply@github.com'
title?: string, // backport pr title, default original pr title prefixed by target branch
body?: string, // backport pr title, default original pr body prefixed by bodyPrefix
bodyPrefix?: string, // backport pr body prefix, default `backport <original-pr-link>`
bpBranchName?: string, // backport pr branch name, default computed from commit
reviewers?: string[], // backport pr reviewers
assignees?: string[], // backport pr assignees
inheritReviewers: boolean, // if true and reviewers == [] then inherit reviewers from original pr
inheritReviewers?: boolean, // if true and reviewers == [] then inherit reviewers from original pr
}

View file

@ -2,6 +2,7 @@ import ArgsParser from "@bp/service/args/args-parser";
import { Args } from "@bp/service/args/args.types";
import { Command } from "commander";
import { name, version, description } from "@bp/../package.json";
import { readConfigFile } from "@bp/service/args/args-utils";
function commaSeparatedList(value: string, _prev: unknown): string[] {
// remove all whitespaces
@ -9,49 +10,58 @@ function commaSeparatedList(value: string, _prev: unknown): string[] {
return cleanedValue !== "" ? cleanedValue.replace(/\s/g, "").split(",") : [];
}
export default class CLIArgsParser implements ArgsParser {
export default class CLIArgsParser extends ArgsParser {
private getCommand(): Command {
return new Command(name)
.version(version)
.description(description)
.requiredOption("-tb, --target-branch <branch>", "branch where changes must be backported to.")
.requiredOption("-pr, --pull-request <pr-url>", "pull request url, e.g., https://github.com/lampajr/backporting/pull/1.")
.option("-d, --dry-run", "if enabled the tool does not create any pull request nor push anything remotely", false)
.option("-a, --auth <auth>", "git service authentication string, e.g., github token.", "")
.option("-gu, --git-user <git-user>", "local git user name, default is 'GitHub'.", "GitHub")
.option("-ge, --git-email <git-email>", "local git user email, default is 'noreply@github.com'.", "noreply@github.com")
.option("-f, --folder <folder>", "local folder where the repo will be checked out, e.g., /tmp/folder.", undefined)
.option("--title <bp-title>", "backport pr title, default original pr title prefixed by target branch.", undefined)
.option("--body <bp-body>", "backport pr title, default original pr body prefixed by bodyPrefix.", undefined)
.option("--body-prefix <bp-body-prefix>", "backport pr body prefix, default `backport <original-pr-link>`.", undefined)
.option("--bp-branch-name <bp-branch-name>", "backport pr branch name, default auto-generated by the commit.", undefined)
.option("--reviewers <reviewers>", "comma separated list of reviewers for the backporting pull request.", commaSeparatedList, [])
.option("--assignees <assignees>", "comma separated list of assignees for the backporting pull request.", commaSeparatedList, [])
.option("--no-inherit-reviewers", "if provided and reviewers option is empty then inherit them from original pull request", true);
.option("-tb, --target-branch <branch>", "branch where changes must be backported to.")
.option("-pr, --pull-request <pr-url>", "pull request url, e.g., https://github.com/lampajr/backporting/pull/1.")
.option("-d, --dry-run", "if enabled the tool does not create any pull request nor push anything remotely")
.option("-a, --auth <auth>", "git service authentication string, e.g., github token.")
.option("-gu, --git-user <git-user>", "local git user name, default is 'GitHub'.")
.option("-ge, --git-email <git-email>", "local git user email, default is 'noreply@github.com'.")
.option("-f, --folder <folder>", "local folder where the repo will be checked out, e.g., /tmp/folder.")
.option("--title <bp-title>", "backport pr title, default original pr title prefixed by target branch.")
.option("--body <bp-body>", "backport pr title, default original pr body prefixed by bodyPrefix.")
.option("--body-prefix <bp-body-prefix>", "backport pr body prefix, default `backport <original-pr-link>`.")
.option("--bp-branch-name <bp-branch-name>", "backport pr branch name, default auto-generated by the commit.")
.option("--reviewers <reviewers>", "comma separated list of reviewers for the backporting pull request.", commaSeparatedList)
.option("--assignees <assignees>", "comma separated list of assignees for the backporting pull request.", commaSeparatedList)
.option("--no-inherit-reviewers", "if provided and reviewers option is empty then inherit them from original pull request")
.option("-cf, --config-file <config-file>", "configuration file containing all valid options, the json must match Args interface.");
}
parse(): Args {
readArgs(): Args {
const opts = this.getCommand()
.parse()
.opts();
return {
dryRun: opts.dryRun,
auth: opts.auth,
pullRequest: opts.pullRequest,
targetBranch: opts.targetBranch,
folder: opts.folder,
gitUser: opts.gitUser,
gitEmail: opts.gitEmail,
title: opts.title,
body: opts.body,
bodyPrefix: opts.bodyPrefix,
bpBranchName: opts.bpBranchName,
reviewers: opts.reviewers,
assignees: opts.assignees,
inheritReviewers: opts.inheritReviewers,
};
let args: Args;
if (opts.configFile) {
// if config file is set ignore all other options
args = readConfigFile(opts.configFile);
} else {
args = {
dryRun: opts.dryRun,
auth: opts.auth,
pullRequest: opts.pullRequest,
targetBranch: opts.targetBranch,
folder: opts.folder,
gitUser: opts.gitUser,
gitEmail: opts.gitEmail,
title: opts.title,
body: opts.body,
bodyPrefix: opts.bodyPrefix,
bpBranchName: opts.bpBranchName,
reviewers: opts.reviewers,
assignees: opts.assignees,
inheritReviewers: opts.inheritReviewers,
};
}
return args;
}
}

View file

@ -1,8 +1,9 @@
import ArgsParser from "@bp/service/args/args-parser";
import { Args } from "@bp/service/args/args.types";
import { getInput } from "@actions/core";
import { readConfigFile } from "@bp/service/args/args-utils";
export default class GHAArgsParser implements ArgsParser {
export default class GHAArgsParser extends ArgsParser {
/**
* Return the input only if it is not a blank or null string, otherwise returns undefined
@ -14,39 +15,43 @@ export default class GHAArgsParser implements ArgsParser {
return value !== "" ? value : undefined;
}
public getOrDefault(key: string, defaultValue: string): string {
const value = getInput(key);
return value !== "" ? value : defaultValue;
}
public getAsCommaSeparatedList(key: string): string[] {
public getAsCommaSeparatedList(key: string): string[] | undefined {
// trim the value
const value: string = (getInput(key) ?? "").trim();
return value !== "" ? value.replace(/\s/g, "").split(",") : [];
return value !== "" ? value.replace(/\s/g, "").split(",") : undefined;
}
public getAsBooleanOrDefault(key: string, defaultValue: boolean): boolean {
private getAsBooleanOrDefault(key: string): boolean | undefined {
const value = getInput(key).trim();
return value !== "" ? value.toLowerCase() === "true" : defaultValue;
return value !== "" ? value.toLowerCase() === "true" : undefined;
}
parse(): Args {
return {
dryRun: this.getAsBooleanOrDefault("dry-run", false),
auth: getInput("auth"),
pullRequest: getInput("pull-request"),
targetBranch: getInput("target-branch"),
folder: this.getOrUndefined("folder"),
gitUser: this.getOrDefault("git-user", "GitHub"),
gitEmail: this.getOrDefault("git-email", "noreply@github.com"),
title: this.getOrUndefined("title"),
body: this.getOrUndefined("body"),
bodyPrefix: this.getOrUndefined("body-prefix"),
bpBranchName: this.getOrUndefined("bp-branch-name"),
reviewers: this.getAsCommaSeparatedList("reviewers"),
assignees: this.getAsCommaSeparatedList("assignees"),
inheritReviewers: !this.getAsBooleanOrDefault("no-inherit-reviewers", false),
};
readArgs(): Args {
const configFile = this.getOrUndefined("config-file");
let args: Args;
if (configFile) {
args = readConfigFile(configFile);
} else {
args = {
dryRun: this.getAsBooleanOrDefault("dry-run"),
auth: this.getOrUndefined("auth"),
pullRequest: getInput("pull-request"),
targetBranch: getInput("target-branch"),
folder: this.getOrUndefined("folder"),
gitUser: this.getOrUndefined("git-user"),
gitEmail: this.getOrUndefined("git-email"),
title: this.getOrUndefined("title"),
body: this.getOrUndefined("body"),
bodyPrefix: this.getOrUndefined("body-prefix"),
bpBranchName: this.getOrUndefined("bp-branch-name"),
reviewers: this.getAsCommaSeparatedList("reviewers"),
assignees: this.getAsCommaSeparatedList("assignees"),
inheritReviewers: !this.getAsBooleanOrDefault("no-inherit-reviewers"),
};
}
return args;
}
}

View file

@ -12,7 +12,7 @@ export interface LocalGit {
*/
export interface Configs {
dryRun: boolean,
auth: string,
auth?: string,
git: LocalGit,
folder: string,
targetBranch: string,

View file

@ -7,17 +7,17 @@ import { GitPullRequest } from "@bp/service/git/git.types";
export default class PullRequestConfigsParser extends ConfigsParser {
private gitService: GitClient;
private gitClient: GitClient;
constructor() {
super();
this.gitService = GitClientFactory.getClient();
this.gitClient = GitClientFactory.getClient();
}
public async parse(args: Args): Promise<Configs> {
let pr: GitPullRequest;
try {
pr = await this.gitService.getPullRequestFromUrl(args.pullRequest);
pr = await this.gitClient.getPullRequestFromUrl(args.pullRequest);
} catch(error) {
this.logger.error("Something went wrong retrieving pull request");
throw error;
@ -26,15 +26,15 @@ export default class PullRequestConfigsParser extends ConfigsParser {
const folder: string = args.folder ?? this.getDefaultFolder();
return {
dryRun: args.dryRun,
dryRun: args.dryRun!,
auth: args.auth,
folder: `${folder.startsWith("/") ? "" : process.cwd() + "/"}${args.folder ?? this.getDefaultFolder()}`,
targetBranch: args.targetBranch,
originalPullRequest: pr,
backportPullRequest: this.getDefaultBackportPullRequest(pr, args),
git: {
user: args.gitUser,
email: args.gitEmail,
user: args.gitUser ?? this.gitClient.getDefaultGitUser(),
email: args.gitEmail ?? this.gitClient.getDefaultGitEmail(),
}
};
}
@ -64,7 +64,7 @@ export default class PullRequestConfigsParser extends ConfigsParser {
const body = args.body ?? `${originalPullRequest.body}`;
return {
author: args.gitUser,
author: args.gitUser ?? this.gitClient.getDefaultGitUser(),
title: args.title ?? `[${args.targetBranch}] ${originalPullRequest.title}`,
body: `${bodyPrefix}${body}`,
reviewers: [...new Set(reviewers)],

View file

@ -10,10 +10,10 @@ import { LocalGit } from "@bp/service/configs/configs.types";
export default class GitCLIService {
private readonly logger: LoggerService;
private readonly auth: string;
private readonly auth: string | undefined;
private readonly gitData: LocalGit;
constructor(auth: string, gitData: LocalGit) {
constructor(auth: string | undefined, gitData: LocalGit) {
this.logger = LoggerServiceFactory.getLogger();
this.auth = auth;
this.gitData = gitData;

View file

@ -26,7 +26,7 @@ export default class GitClientFactory {
* @param type git management service type
* @param authToken authentication token, like github/gitlab token
*/
public static getOrCreate(type: GitClientType, authToken: string, apiUrl: string): GitClient {
public static getOrCreate(type: GitClientType, authToken: string | undefined, apiUrl: string): GitClient {
if (GitClientFactory.instance) {
GitClientFactory.logger.warn("Git service already initialized!");

View file

@ -7,6 +7,10 @@ import { BackportPullRequest, GitPullRequest } from "@bp/service/git/git.types";
export default interface GitClient {
// READ
getDefaultGitUser(): string;
getDefaultGitEmail(): string;
/**
* Get a pull request object from the underneath git service

View file

@ -14,7 +14,7 @@ export default class GitHubClient implements GitClient {
private octokit: Octokit;
private mapper: GitHubMapper;
constructor(token: string, apiUrl: string) {
constructor(token: string | undefined, apiUrl: string) {
this.apiUrl = apiUrl;
this.logger = LoggerServiceFactory.getLogger();
this.octokit = OctokitFactory.getOctokit(token, this.apiUrl);
@ -23,6 +23,14 @@ export default class GitHubClient implements GitClient {
// READ
getDefaultGitUser(): string {
return "GitHub";
}
getDefaultGitEmail(): string {
return "noreply@github.com";
}
async getPullRequest(owner: string, repo: string, prNumber: number): Promise<GitPullRequest> {
this.logger.info(`Getting pull request ${owner}/${repo}/${prNumber}.`);
const { data } = await this.octokit.rest.pulls.get({

View file

@ -10,7 +10,7 @@ export default class OctokitFactory {
private static logger: LoggerService = LoggerServiceFactory.getLogger();
private static octokit?: Octokit;
public static getOctokit(token: string, apiUrl: string): Octokit {
public static getOctokit(token: string | undefined, apiUrl: string): Octokit {
if (!OctokitFactory.octokit) {
OctokitFactory.logger.info("Creating octokit instance.");
OctokitFactory.octokit = new Octokit({

View file

@ -14,13 +14,13 @@ export default class GitLabClient implements GitClient {
private readonly mapper: GitLabMapper;
private readonly client: Axios;
constructor(token: string, apiUrl: string, rejectUnauthorized = false) {
constructor(token: string | undefined, apiUrl: string, rejectUnauthorized = false) {
this.logger = LoggerServiceFactory.getLogger();
this.apiUrl = apiUrl;
this.client = axios.create({
baseURL: this.apiUrl,
headers: {
Authorization: `Bearer ${token}`,
Authorization: token ? `Bearer ${token}` : "",
"User-Agent": "lampajr/backporting",
},
httpsAgent: new https.Agent({
@ -30,6 +30,14 @@ export default class GitLabClient implements GitClient {
this.mapper = new GitLabMapper(this.client);
}
getDefaultGitUser(): string {
return "Gitlab";
}
getDefaultGitEmail(): string {
return "noreply@gitlab.com";
}
// READ
// example: <host>/api/v4/projects/alampare%2Fbackporting-example/merge_requests/1