feat: override backporting pr fields (#38)

* feat: override local git user config

* feat(issue-32): override reviewers and assignees
This commit is contained in:
Andrea Lamparelli 2023-06-22 17:44:14 +02:00 committed by GitHub
parent 22bec0c537
commit a32e8cd34c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
21 changed files with 671 additions and 107 deletions

View file

@ -7,9 +7,13 @@ export interface Args {
targetBranch: string, // branch on the target repo where the change should be backported to
pullRequest: string, // url of the pull request to backport
folder?: string, // local folder where the repositories should be cloned
author?: string, // backport pr author, default taken from pr
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
}

View file

@ -3,6 +3,11 @@ import { Args } from "@bp/service/args/args.types";
import { Command } from "commander";
import { name, version, description } from "@bp/../package.json";
function commaSeparatedList(value: string, _prev: unknown): string[] {
// remove all whitespaces
const cleanedValue: string = value.trim();
return cleanedValue !== "" ? cleanedValue.replace(/\s/g, "").split(",") : [];
}
export default class CLIArgsParser implements ArgsParser {
@ -11,14 +16,19 @@ export default class CLIArgsParser implements ArgsParser {
.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.")
.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 <folder>", "backport pr title, default original pr title prefixed by target branch.", undefined)
.option("--body <folder>", "backport pr title, default original pr body prefixed by bodyPrefix.", undefined)
.option("--body-prefix <folder>", "backport pr body prefix, default `backport <original-pr-link>`.", undefined)
.option("--bp-branch-name <folder>", "backport pr branch name, default auto-generated by the commit.", 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);
}
parse(): Args {
@ -32,10 +42,15 @@ export default class CLIArgsParser implements ArgsParser {
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,
};
}

View file

@ -9,22 +9,43 @@ export default class GHAArgsParser implements ArgsParser {
* @param key input key
* @returns the value or undefined
*/
private _getOrUndefined(key: string): string | undefined {
public getOrUndefined(key: string): string | undefined {
const value = getInput(key);
return value !== "" ? value : undefined;
}
public getOrDefault(key: string, defaultValue: string): string {
const value = getInput(key);
return value !== "" ? value : defaultValue;
}
public getAsCommaSeparatedList(key: string): string[] {
// trim the value
const value: string = (getInput(key) ?? "").trim();
return value !== "" ? value.replace(/\s/g, "").split(",") : [];
}
public getAsBooleanOrDefault(key: string, defaultValue: boolean): boolean {
const value = getInput(key).trim();
return value !== "" ? value.toLowerCase() === "true" : defaultValue;
}
parse(): Args {
return {
dryRun: getInput("dry-run") === "true",
auth: getInput("auth") ? getInput("auth") : "",
dryRun: this.getAsBooleanOrDefault("dry-run", false),
auth: getInput("auth"),
pullRequest: getInput("pull-request"),
targetBranch: getInput("target-branch"),
folder: this._getOrUndefined("folder"),
title: this._getOrUndefined("title"),
body: this._getOrUndefined("body"),
bodyPrefix: this._getOrUndefined("body-prefix"),
bpBranchName: this._getOrUndefined("bp-branch-name"),
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),
};
}

View file

@ -2,16 +2,21 @@
import { GitPullRequest } from "@bp/service/git/git.types";
export interface LocalGit {
user: string, // local git user
email: string, // local git email
}
/**
* Internal configuration object
*/
export interface Configs {
dryRun: boolean,
auth: string,
author: string, // author of the backport pr
git: LocalGit,
folder: string,
targetBranch: string,
originalPullRequest: GitPullRequest,
backportPullRequest: GitPullRequest
backportPullRequest: GitPullRequest,
}

View file

@ -21,11 +21,14 @@ export default class PullRequestConfigsParser extends ConfigsParser {
return {
dryRun: args.dryRun,
auth: args.auth,
author: args.author ?? pr.author,
folder: `${folder.startsWith("/") ? "" : process.cwd() + "/"}${args.folder ?? this.getDefaultFolder()}`,
targetBranch: args.targetBranch,
originalPullRequest: pr,
backportPullRequest: this.getDefaultBackportPullRequest(pr, args)
backportPullRequest: this.getDefaultBackportPullRequest(pr, args),
git: {
user: args.gitUser,
email: args.gitEmail,
}
};
}
@ -41,20 +44,24 @@ export default class PullRequestConfigsParser extends ConfigsParser {
* @returns {GitPullRequest}
*/
private getDefaultBackportPullRequest(originalPullRequest: GitPullRequest, args: Args): GitPullRequest {
const reviewers = [];
reviewers.push(originalPullRequest.author);
if (originalPullRequest.mergedBy) {
reviewers.push(originalPullRequest.mergedBy);
const reviewers = args.reviewers ?? [];
if (reviewers.length == 0 && args.inheritReviewers) {
// inherit only if args.reviewers is empty and args.inheritReviewers set to true
reviewers.push(originalPullRequest.author);
if (originalPullRequest.mergedBy) {
reviewers.push(originalPullRequest.mergedBy);
}
}
const bodyPrefix = args.bodyPrefix ?? `**Backport:** ${originalPullRequest.htmlUrl}\r\n\r\n`;
const body = args.body ?? `${originalPullRequest.body}\r\n\r\nPowered by [BPer](https://github.com/lampajr/backporting).`;
return {
author: originalPullRequest.author,
author: args.gitUser,
title: args.title ?? `[${args.targetBranch}] ${originalPullRequest.title}`,
body: `${bodyPrefix}${body}`,
reviewers: [...new Set(reviewers)],
assignees: [...new Set(args.assignees)],
targetRepo: originalPullRequest.targetRepo,
sourceRepo: originalPullRequest.targetRepo,
branchName: args.bpBranchName,

View file

@ -2,6 +2,7 @@ import LoggerService from "@bp/service/logger/logger-service";
import LoggerServiceFactory from "@bp/service/logger/logger-service-factory";
import simpleGit, { SimpleGit } from "simple-git";
import fs from "fs";
import { LocalGit } from "@bp/service/configs/configs.types";
/**
* Command line git commands executor service
@ -10,12 +11,12 @@ export default class GitCLIService {
private readonly logger: LoggerService;
private readonly auth: string;
private readonly author: string;
private readonly gitData: LocalGit;
constructor(auth: string, author: string) {
constructor(auth: string, gitData: LocalGit) {
this.logger = LoggerServiceFactory.getLogger();
this.auth = auth;
this.author = author;
this.gitData = gitData;
}
/**
@ -26,7 +27,7 @@ export default class GitCLIService {
*/
private git(cwd?: string): SimpleGit {
const gitConfig = { ...(cwd ? { baseDir: cwd } : {})};
return simpleGit(gitConfig).addConfig("user.name", this.author).addConfig("user.email", "noreply@github.com");
return simpleGit(gitConfig).addConfig("user.name", this.gitData.user).addConfig("user.email", this.gitData.email);
}
/**
@ -34,8 +35,8 @@ export default class GitCLIService {
* @param remoteURL remote link, e.g., https://github.com/lampajr/backporting-example.git
*/
private remoteWithAuth(remoteURL: string): string {
if (this.auth && this.author) {
return remoteURL.replace("://", `://${this.author}:${this.auth}@`);
if (this.auth && this.gitData.user) {
return remoteURL.replace("://", `://${this.gitData.user}:${this.auth}@`);
}
// return remote as it is

View file

@ -9,6 +9,7 @@ export interface GitPullRequest {
title: string,
body: string,
reviewers: string[],
assignees: string[],
targetRepo: GitRepository,
sourceRepo: GitRepository,
nCommits: number, // number of commits in the pr
@ -30,6 +31,7 @@ export interface BackportPullRequest {
title: string, // pr title
body: string, // pr body
reviewers: string[], // pr list of reviewers
assignees: string[], // pr list of assignees
branchName?: string,
}

View file

@ -15,6 +15,7 @@ export default class GitHubMapper {
merged: pr.merged ?? false,
mergedBy: pr.merged_by?.login,
reviewers: pr.requested_reviewers.filter(r => "login" in r).map((r => (r as User)?.login)),
assignees: pr.assignees.filter(r => "login" in r).map(r => r.login),
sourceRepo: {
owner: pr.head.repo.full_name.split("/")[0],
project: pr.head.repo.full_name.split("/")[1],

View file

@ -58,12 +58,25 @@ export default class GitHubService implements GitService {
owner: backport.owner,
repo: backport.repo,
pull_number: (data as PullRequest).number,
reviewers: backport.reviewers
reviewers: backport.reviewers,
});
} catch (error) {
this.logger.error(`Error requesting reviewers: ${error}`);
}
}
if (backport.assignees.length > 0) {
try {
await this.octokit.issues.addAssignees({
owner: backport.owner,
repo: backport.repo,
issue_number: (data as PullRequest).number,
assignees: backport.assignees,
});
} catch (error) {
this.logger.error(`Error setting assignees: ${error}`);
}
}
}
// UTILS

View file

@ -80,7 +80,7 @@ export default class Runner {
const backportPR: GitPullRequest = configs.backportPullRequest;
// start local git operations
const git: GitCLIService = new GitCLIService(configs.auth, configs.author);
const git: GitCLIService = new GitCLIService(configs.auth, configs.git);
// 4. clone the repository
await git.clone(configs.originalPullRequest.targetRepo.cloneUrl, configs.folder, configs.targetBranch);
@ -107,7 +107,8 @@ export default class Runner {
base: configs.targetBranch,
title: backportPR.title,
body: backportPR.body,
reviewers: backportPR.reviewers
reviewers: backportPR.reviewers,
assignees: backportPR.assignees,
};
if (!configs.dryRun) {