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

@ -57,9 +57,14 @@ This toold comes with some inputs that allow users to override the default behav
| Pull Request | -pr, --pull-request | Y | Original pull request url, the one that must be backported, e.g., https://github.com/lampajr/backporting/pull/1 | |
| Auth | -a, --auth | N | `GITHUB_TOKEN` or a `repo` scoped [Personal Access Token](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token) | "" |
| Folder | -f, --folder | N | Local folder where the repo will be checked out, e.g., /tmp/folder | {cwd}/bp |
| Git User | -gu, --git-user | N | Local git user name | "GitHub" |
| Git Email | -ge, --git-email | N | Local git user email | "noreply@github.com" |
| Title | --title | N | Backporting pull request title | "{original-pr-title}" |
| Body | --body | N | Backporting pull request body | "{original-pr-body}" |
| Body Prefix | --body-prefix | N | Prefix to the backporting pull request body | "Backport: {original-pr-link}" |
| Reviewers | --reviewers | N | Backporting pull request comma-separated reviewers list | [] |
| Assignees | --assignes | N | Backporting pull request comma-separated assignees list | [] |
| No Reviewers Inheritance | --no-inherit-reviewers | N | Considered only if reviewers is empty, if true keep reviewers as empty list, otherwise inherit from original pull request | false |
| Backport Branch Name | --bp-branch-name | N | Name of the backporting pull request branch | bp-{target-branch}-{sha} |
| Dry Run | -d, --dry-run | N | If enabled the tool does not push nor create anything remotely, use this to skip PR creation | false |

View file

@ -9,6 +9,14 @@ inputs:
description: "GITHUB_TOKEN or a `repo` scoped Personal Access Token (PAT)."
default: ${{ github.token }}
required: false
git-user:
description: "Local git user name."
default: "GitHub"
required: false
git-email:
description: "Local git user email."
default: "noreply@github.com"
required: false
pull-request:
description: "URL of the pull request to backport, e.g., https://github.com/lampajr/backporting/pull/1."
required: true
@ -27,6 +35,16 @@ inputs:
bp-branch-name:
description: "Backporting PR branch name. Default is auto-generated from commit."
required: false
reviewers:
description: "Comma separated list of reviewers for the backporting pull request."
required: false
assignees:
description: "Comma separated list of reviewers for the backporting pull request."
required: false
inherith-reviewers:
description: "If enabled and reviewers option is empty then inherit them from original pull request."
required: false
default: "true"
runs:
using: node16

77
dist/cli/index.js vendored
View file

@ -30,20 +30,30 @@ runner.run();
Object.defineProperty(exports, "__esModule", ({ value: true }));
const commander_1 = __nccwpck_require__(4379);
const package_json_1 = __nccwpck_require__(6625);
function commaSeparatedList(value, _prev) {
// remove all whitespaces
const cleanedValue = value.trim();
return cleanedValue !== "" ? cleanedValue.replace(/\s/g, "").split(",") : [];
}
class CLIArgsParser {
getCommand() {
return new commander_1.Command(package_json_1.name)
.version(package_json_1.version)
.description(package_json_1.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() {
const opts = this.getCommand()
@ -55,10 +65,15 @@ class CLIArgsParser {
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,
};
}
}
@ -126,11 +141,14 @@ class PullRequestConfigsParser extends configs_parser_1.default {
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,
}
};
}
getDefaultFolder() {
@ -144,18 +162,22 @@ class PullRequestConfigsParser extends configs_parser_1.default {
* @returns {GitPullRequest}
*/
getDefaultBackportPullRequest(originalPullRequest, args) {
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,
@ -185,10 +207,10 @@ const fs_1 = __importDefault(__nccwpck_require__(7147));
* Command line git commands executor service
*/
class GitCLIService {
constructor(auth, author) {
constructor(auth, gitData) {
this.logger = logger_service_factory_1.default.getLogger();
this.auth = auth;
this.author = author;
this.gitData = gitData;
}
/**
* Return a pre-configured SimpleGit instance able to execute commands from current
@ -198,15 +220,15 @@ class GitCLIService {
*/
git(cwd) {
const gitConfig = { ...(cwd ? { baseDir: cwd } : {}) };
return (0, simple_git_1.default)(gitConfig).addConfig("user.name", this.author).addConfig("user.email", "noreply@github.com");
return (0, simple_git_1.default)(gitConfig).addConfig("user.name", this.gitData.user).addConfig("user.email", this.gitData.email);
}
/**
* Update the provided remote URL by adding the auth token if not empty
* @param remoteURL remote link, e.g., https://github.com/lampajr/backporting-example.git
*/
remoteWithAuth(remoteURL) {
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
return remoteURL;
@ -375,6 +397,7 @@ class GitHubMapper {
merged: pr.merged ?? false,
mergedBy: pr.merged_by?.login,
reviewers: pr.requested_reviewers.filter(r => "login" in r).map((r => r?.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],
@ -446,13 +469,26 @@ class GitHubService {
owner: backport.owner,
repo: backport.repo,
pull_number: data.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.number,
assignees: backport.assignees,
});
}
catch (error) {
this.logger.error(`Error setting assignees: ${error}`);
}
}
}
// UTILS
/**
@ -657,7 +693,7 @@ class Runner {
const originalPR = configs.originalPullRequest;
const backportPR = configs.backportPullRequest;
// start local git operations
const git = new git_cli_1.default(configs.auth, configs.author);
const git = new git_cli_1.default(configs.auth, configs.git);
// 4. clone the repository
await git.clone(configs.originalPullRequest.targetRepo.cloneUrl, configs.folder, configs.targetBranch);
// 5. create new branch from target one and checkout
@ -679,7 +715,8 @@ class Runner {
base: configs.targetBranch,
title: backportPR.title,
body: backportPR.body,
reviewers: backportPR.reviewers
reviewers: backportPR.reviewers,
assignees: backportPR.assignees,
};
if (!configs.dryRun) {
// 8. push the new branch to origin

86
dist/gha/index.js vendored
View file

@ -35,21 +35,39 @@ class GHAArgsParser {
* @param key input key
* @returns the value or undefined
*/
_getOrUndefined(key) {
getOrUndefined(key) {
const value = (0, core_1.getInput)(key);
return value !== "" ? value : undefined;
}
getOrDefault(key, defaultValue) {
const value = (0, core_1.getInput)(key);
return value !== "" ? value : defaultValue;
}
getAsCommaSeparatedList(key) {
// trim the value
const value = ((0, core_1.getInput)(key) ?? "").trim();
return value !== "" ? value.replace(/\s/g, "").split(",") : [];
}
getAsBooleanOrDefault(key, defaultValue) {
const value = (0, core_1.getInput)(key).trim();
return value !== "" ? value.toLowerCase() === "true" : defaultValue;
}
parse() {
return {
dryRun: (0, core_1.getInput)("dry-run") === "true",
auth: (0, core_1.getInput)("auth") ? (0, core_1.getInput)("auth") : "",
dryRun: this.getAsBooleanOrDefault("dry-run", false),
auth: (0, core_1.getInput)("auth"),
pullRequest: (0, core_1.getInput)("pull-request"),
targetBranch: (0, core_1.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),
};
}
}
@ -117,11 +135,14 @@ class PullRequestConfigsParser extends configs_parser_1.default {
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,
}
};
}
getDefaultFolder() {
@ -135,18 +156,22 @@ class PullRequestConfigsParser extends configs_parser_1.default {
* @returns {GitPullRequest}
*/
getDefaultBackportPullRequest(originalPullRequest, args) {
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,
@ -176,10 +201,10 @@ const fs_1 = __importDefault(__nccwpck_require__(7147));
* Command line git commands executor service
*/
class GitCLIService {
constructor(auth, author) {
constructor(auth, gitData) {
this.logger = logger_service_factory_1.default.getLogger();
this.auth = auth;
this.author = author;
this.gitData = gitData;
}
/**
* Return a pre-configured SimpleGit instance able to execute commands from current
@ -189,15 +214,15 @@ class GitCLIService {
*/
git(cwd) {
const gitConfig = { ...(cwd ? { baseDir: cwd } : {}) };
return (0, simple_git_1.default)(gitConfig).addConfig("user.name", this.author).addConfig("user.email", "noreply@github.com");
return (0, simple_git_1.default)(gitConfig).addConfig("user.name", this.gitData.user).addConfig("user.email", this.gitData.email);
}
/**
* Update the provided remote URL by adding the auth token if not empty
* @param remoteURL remote link, e.g., https://github.com/lampajr/backporting-example.git
*/
remoteWithAuth(remoteURL) {
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
return remoteURL;
@ -366,6 +391,7 @@ class GitHubMapper {
merged: pr.merged ?? false,
mergedBy: pr.merged_by?.login,
reviewers: pr.requested_reviewers.filter(r => "login" in r).map((r => r?.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],
@ -437,13 +463,26 @@ class GitHubService {
owner: backport.owner,
repo: backport.repo,
pull_number: data.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.number,
assignees: backport.assignees,
});
}
catch (error) {
this.logger.error(`Error setting assignees: ${error}`);
}
}
}
// UTILS
/**
@ -648,7 +687,7 @@ class Runner {
const originalPR = configs.originalPullRequest;
const backportPR = configs.backportPullRequest;
// start local git operations
const git = new git_cli_1.default(configs.auth, configs.author);
const git = new git_cli_1.default(configs.auth, configs.git);
// 4. clone the repository
await git.clone(configs.originalPullRequest.targetRepo.cloneUrl, configs.folder, configs.targetBranch);
// 5. create new branch from target one and checkout
@ -670,7 +709,8 @@ class Runner {
base: configs.targetBranch,
title: backportPR.title,
body: backportPR.body,
reviewers: backportPR.reviewers
reviewers: backportPR.reviewers,
assignees: backportPR.assignees,
};
if (!configs.dryRun) {
// 8. push the new branch to origin

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) {

View file

@ -1,6 +1,6 @@
import { Args } from "@bp/service/args/args.types";
import CLIArgsParser from "@bp/service/args/cli/cli-args-parser";
import { addProcessArgs, resetProcessArgs } from "../../../support/utils";
import { addProcessArgs, resetProcessArgs, expectArrayEqual } from "../../../support/utils";
describe("cli args parser", () => {
let parser: CLIArgsParser;
@ -24,7 +24,8 @@ describe("cli args parser", () => {
const args: Args = parser.parse();
expect(args.dryRun).toEqual(false);
expect(args.auth).toEqual("");
expect(args.author).toEqual(undefined);
expect(args.gitUser).toEqual("GitHub");
expect(args.gitEmail).toEqual("noreply@github.com");
expect(args.folder).toEqual(undefined);
expect(args.targetBranch).toEqual("target");
expect(args.pullRequest).toEqual("https://localhost/whatever/pulls/1");
@ -32,6 +33,9 @@ describe("cli args parser", () => {
expect(args.body).toEqual(undefined);
expect(args.bodyPrefix).toEqual(undefined);
expect(args.bpBranchName).toEqual(undefined);
expect(args.reviewers).toEqual([]);
expect(args.assignees).toEqual([]);
expect(args.inheritReviewers).toEqual(true);
});
test("valid execution [default, long]", () => {
@ -45,7 +49,8 @@ describe("cli args parser", () => {
const args: Args = parser.parse();
expect(args.dryRun).toEqual(false);
expect(args.auth).toEqual("");
expect(args.author).toEqual(undefined);
expect(args.gitUser).toEqual("GitHub");
expect(args.gitEmail).toEqual("noreply@github.com");
expect(args.folder).toEqual(undefined);
expect(args.targetBranch).toEqual("target");
expect(args.pullRequest).toEqual("https://localhost/whatever/pulls/1");
@ -53,6 +58,9 @@ describe("cli args parser", () => {
expect(args.body).toEqual(undefined);
expect(args.bodyPrefix).toEqual(undefined);
expect(args.bpBranchName).toEqual(undefined);
expect(args.reviewers).toEqual([]);
expect(args.assignees).toEqual([]);
expect(args.inheritReviewers).toEqual(true);
});
test("valid execution [override, short]", () => {
@ -63,13 +71,18 @@ describe("cli args parser", () => {
"-tb",
"target",
"-pr",
"https://localhost/whatever/pulls/1"
"https://localhost/whatever/pulls/1",
"-gu",
"Me",
"-ge",
"me@email.com",
]);
const args: Args = parser.parse();
expect(args.dryRun).toEqual(true);
expect(args.auth).toEqual("bearer-token");
expect(args.author).toEqual(undefined);
expect(args.gitUser).toEqual("Me");
expect(args.gitEmail).toEqual("me@email.com");
expect(args.folder).toEqual(undefined);
expect(args.targetBranch).toEqual("target");
expect(args.pullRequest).toEqual("https://localhost/whatever/pulls/1");
@ -77,6 +90,9 @@ describe("cli args parser", () => {
expect(args.body).toEqual(undefined);
expect(args.bodyPrefix).toEqual(undefined);
expect(args.bpBranchName).toEqual(undefined);
expect(args.reviewers).toEqual([]);
expect(args.assignees).toEqual([]);
expect(args.inheritReviewers).toEqual(true);
});
test("valid execution [override, long]", () => {
@ -88,6 +104,10 @@ describe("cli args parser", () => {
"target",
"--pull-request",
"https://localhost/whatever/pulls/1",
"--git-user",
"Me",
"--git-email",
"me@email.com",
"--title",
"New Title",
"--body",
@ -96,12 +116,18 @@ describe("cli args parser", () => {
"New Body Prefix",
"--bp-branch-name",
"bp_branch_name",
"--reviewers",
"al , john, jack",
"--assignees",
" pippo,pluto, paperino",
"--no-inherit-reviewers",
]);
const args: Args = parser.parse();
expect(args.dryRun).toEqual(true);
expect(args.auth).toEqual("bearer-token");
expect(args.author).toEqual(undefined);
expect(args.gitUser).toEqual("Me");
expect(args.gitEmail).toEqual("me@email.com");
expect(args.folder).toEqual(undefined);
expect(args.targetBranch).toEqual("target");
expect(args.pullRequest).toEqual("https://localhost/whatever/pulls/1");
@ -109,6 +135,9 @@ describe("cli args parser", () => {
expect(args.body).toEqual("New Body");
expect(args.bodyPrefix).toEqual("New Body Prefix");
expect(args.bpBranchName).toEqual("bp_branch_name");
expectArrayEqual(["al", "john", "jack"], args.reviewers!);
expectArrayEqual(["pippo", "pluto", "paperino"], args.assignees!);
expect(args.inheritReviewers).toEqual(false);
});
});

View file

@ -1,6 +1,6 @@
import { Args } from "@bp/service/args/args.types";
import GHAArgsParser from "@bp/service/args/gha/gha-args-parser";
import { spyGetInput } from "../../../support/utils";
import { spyGetInput, expectArrayEqual } from "../../../support/utils";
describe("gha args parser", () => {
let parser: GHAArgsParser;
@ -14,6 +14,33 @@ describe("gha args parser", () => {
jest.clearAllMocks();
});
test("getOrDefault", () => {
spyGetInput({
"present": "value"
});
expect(parser.getOrDefault("not-present", "default")).toStrictEqual("default");
expect(parser.getOrDefault("present", "default")).toStrictEqual("value");
});
test("getOrUndefined", () => {
spyGetInput({
"present": "value",
"empty": "",
});
expect(parser.getOrUndefined("empty")).toStrictEqual(undefined);
expect(parser.getOrUndefined("present")).toStrictEqual("value");
});
test("getAsCommaSeparatedList", () => {
spyGetInput({
"present": "value1, value2 , value3",
"empty": "",
"blank": " ",
});
expectArrayEqual(parser.getAsCommaSeparatedList("present")!, ["value1", "value2", "value3"]);
expect(parser.getAsCommaSeparatedList("empty")).toStrictEqual([]);
expect(parser.getAsCommaSeparatedList("blank")).toStrictEqual([]);
});
test("valid execution [default]", () => {
spyGetInput({
@ -24,14 +51,16 @@ describe("gha args parser", () => {
const args: Args = parser.parse();
expect(args.dryRun).toEqual(false);
expect(args.auth).toEqual("");
expect(args.author).toEqual(undefined);
expect(args.gitUser).toEqual("GitHub");
expect(args.gitEmail).toEqual("noreply@github.com");
expect(args.folder).toEqual(undefined);
expect(args.targetBranch).toEqual("target");
expect(args.pullRequest).toEqual("https://localhost/whatever/pulls/1");
expect(args.title).toEqual(undefined);
expect(args.body).toEqual(undefined);
expect(args.bodyPrefix).toEqual(undefined);
expect(args.bpBranchName).toEqual(undefined);
expect(args.reviewers).toEqual([]);
expect(args.assignees).toEqual([]);
expect(args.inheritReviewers).toEqual(true);
});
test("valid execution [override]", () => {
@ -40,16 +69,22 @@ describe("gha args parser", () => {
"auth": "bearer-token",
"target-branch": "target",
"pull-request": "https://localhost/whatever/pulls/1",
"git-user": "Me",
"git-email": "me@email.com",
"title": "New Title",
"body": "New Body",
"body-prefix": "New Body Prefix",
"bp-branch-name": "bp_branch_name",
"reviewers": "al , john, jack",
"assignees": " pippo,pluto, paperino",
"no-inherit-reviewers": "true",
});
const args: Args = parser.parse();
expect(args.dryRun).toEqual(true);
expect(args.auth).toEqual("bearer-token");
expect(args.author).toEqual(undefined);
expect(args.gitUser).toEqual("Me");
expect(args.gitEmail).toEqual("me@email.com");
expect(args.folder).toEqual(undefined);
expect(args.targetBranch).toEqual("target");
expect(args.pullRequest).toEqual("https://localhost/whatever/pulls/1");
@ -57,6 +92,9 @@ describe("gha args parser", () => {
expect(args.body).toEqual("New Body");
expect(args.bodyPrefix).toEqual("New Body Prefix");
expect(args.bpBranchName).toEqual("bp_branch_name");
expectArrayEqual(["al", "john", "jack"], args.reviewers!);
expectArrayEqual(["pippo", "pluto", "paperino"], args.assignees!);
expect(args.inheritReviewers).toEqual(false);
});
});

View file

@ -33,13 +33,21 @@ describe("pull request config parser", () => {
dryRun: false,
auth: "",
pullRequest: mergedPRUrl,
targetBranch: "prod"
targetBranch: "prod",
gitUser: "GitHub",
gitEmail: "noreply@github.com",
reviewers: [],
assignees: [],
inheritReviewers: true,
};
const configs: Configs = await parser.parseAndValidate(args);
expect(configs.dryRun).toEqual(false);
expect(configs.author).toEqual("gh-user");
expect(configs.git).toEqual({
user: "GitHub",
email: "noreply@github.com"
});
expect(configs.auth).toEqual("");
expect(configs.targetBranch).toEqual("prod");
expect(configs.folder).toEqual(process.cwd() + "/bp");
@ -54,6 +62,7 @@ describe("pull request config parser", () => {
title: "PR Title",
body: "Please review and merge",
reviewers: ["requested-gh-user", "gh-user"],
assignees: [],
targetRepo: {
owner: "owner",
project: "reponame",
@ -68,12 +77,13 @@ describe("pull request config parser", () => {
commits: ["28f63db774185f4ec4b57cd9aaeb12dbfb4c9ecc"]
});
expect(configs.backportPullRequest).toEqual({
author: "gh-user",
author: "GitHub",
url: undefined,
htmlUrl: undefined,
title: "[prod] PR Title",
body: "**Backport:** https://github.com/owner/reponame/pull/2368\r\n\r\nPlease review and merge\r\n\r\nPowered by [BPer](https://github.com/lampajr/backporting).",
reviewers: ["gh-user", "that-s-a-user"],
assignees: [],
targetRepo: {
owner: "owner",
project: "reponame",
@ -96,7 +106,12 @@ describe("pull request config parser", () => {
auth: "whatever",
pullRequest: mergedPRUrl,
targetBranch: "prod",
folder: "/tmp/test"
folder: "/tmp/test",
gitUser: "GitHub",
gitEmail: "noreply@github.com",
reviewers: [],
assignees: [],
inheritReviewers: true,
};
const configs: Configs = await parser.parseAndValidate(args);
@ -105,6 +120,10 @@ describe("pull request config parser", () => {
expect(configs.auth).toEqual("whatever");
expect(configs.targetBranch).toEqual("prod");
expect(configs.folder).toEqual("/tmp/test");
expect(configs.git).toEqual({
user: "GitHub",
email: "noreply@github.com"
});
});
test("override author", async () => {
@ -113,7 +132,11 @@ describe("pull request config parser", () => {
auth: "whatever",
pullRequest: mergedPRUrl,
targetBranch: "prod",
author: "another-user"
gitUser: "GitHub",
gitEmail: "noreply@github.com",
reviewers: [],
assignees: [],
inheritReviewers: true,
};
const configs: Configs = await parser.parseAndValidate(args);
@ -121,7 +144,10 @@ describe("pull request config parser", () => {
expect(configs.dryRun).toEqual(true);
expect(configs.auth).toEqual("whatever");
expect(configs.targetBranch).toEqual("prod");
expect(configs.author).toEqual("another-user");
expect(configs.git).toEqual({
user: "GitHub",
email: "noreply@github.com"
});
});
test("still open pull request", async () => {
@ -129,7 +155,12 @@ describe("pull request config parser", () => {
dryRun: true,
auth: "whatever",
pullRequest: openPRUrl,
targetBranch: "prod"
targetBranch: "prod",
gitUser: "GitHub",
gitEmail: "noreply@github.com",
reviewers: [],
assignees: [],
inheritReviewers: true,
};
const configs: Configs = await parser.parseAndValidate(args);
@ -137,7 +168,10 @@ describe("pull request config parser", () => {
expect(configs.dryRun).toEqual(true);
expect(configs.auth).toEqual("whatever");
expect(configs.targetBranch).toEqual("prod");
expect(configs.author).toEqual("gh-user");
expect(configs.git).toEqual({
user: "GitHub",
email: "noreply@github.com"
});
expect(configs.originalPullRequest).toEqual({
number: 4444,
author: "gh-user",
@ -149,6 +183,7 @@ describe("pull request config parser", () => {
title: "PR Title",
body: "Please review and merge",
reviewers: ["gh-user"],
assignees: [],
targetRepo: {
owner: "owner",
project: "reponame",
@ -171,27 +206,41 @@ describe("pull request config parser", () => {
dryRun: true,
auth: "whatever",
pullRequest: notMergedPRUrl,
targetBranch: "prod"
targetBranch: "prod",
gitUser: "GitHub",
gitEmail: "noreply@github.com",
reviewers: [],
assignees: [],
inheritReviewers: true,
};
expect(async () => await parser.parseAndValidate(args)).rejects.toThrow("Provided pull request is closed and not merged!");
});
test("override backport pr data", async () => {
test("override backport pr data inherting reviewers", async () => {
const args: Args = {
dryRun: false,
auth: "",
pullRequest: mergedPRUrl,
targetBranch: "prod",
gitUser: "Me",
gitEmail: "me@email.com",
title: "New Title",
body: "New Body",
bodyPrefix: "New Body Prefix -",
reviewers: [],
assignees: [],
inheritReviewers: true,
};
const configs: Configs = await parser.parseAndValidate(args);
expect(configs.dryRun).toEqual(false);
expect(configs.author).toEqual("gh-user");
expect(configs.git).toEqual({
user: "Me",
email: "me@email.com"
});
expect(configs.auth).toEqual("");
expect(configs.targetBranch).toEqual("prod");
expect(configs.folder).toEqual(process.cwd() + "/bp");
@ -206,6 +255,7 @@ describe("pull request config parser", () => {
title: "PR Title",
body: "Please review and merge",
reviewers: ["requested-gh-user", "gh-user"],
assignees: [],
targetRepo: {
owner: "owner",
project: "reponame",
@ -221,12 +271,165 @@ describe("pull request config parser", () => {
commits: ["28f63db774185f4ec4b57cd9aaeb12dbfb4c9ecc"],
});
expect(configs.backportPullRequest).toEqual({
author: "gh-user",
author: "Me",
url: undefined,
htmlUrl: undefined,
title: "New Title",
body: "New Body Prefix -New Body",
reviewers: ["gh-user", "that-s-a-user"],
assignees: [],
targetRepo: {
owner: "owner",
project: "reponame",
cloneUrl: "https://github.com/owner/reponame.git"
},
sourceRepo: {
owner: "owner",
project: "reponame",
cloneUrl: "https://github.com/owner/reponame.git"
},
bpBranchName: undefined,
nCommits: 0,
commits: []
});
});
test("override backport pr reviewers and assignees", async () => {
const args: Args = {
dryRun: false,
auth: "",
pullRequest: mergedPRUrl,
targetBranch: "prod",
gitUser: "Me",
gitEmail: "me@email.com",
title: "New Title",
body: "New Body",
bodyPrefix: "New Body Prefix -",
reviewers: ["user1", "user2"],
assignees: ["user3", "user4"],
inheritReviewers: true, // not taken into account
};
const configs: Configs = await parser.parseAndValidate(args);
expect(configs.dryRun).toEqual(false);
expect(configs.git).toEqual({
user: "Me",
email: "me@email.com"
});
expect(configs.auth).toEqual("");
expect(configs.targetBranch).toEqual("prod");
expect(configs.folder).toEqual(process.cwd() + "/bp");
expect(configs.originalPullRequest).toEqual({
number: 2368,
author: "gh-user",
url: "https://api.github.com/repos/owner/reponame/pulls/2368",
htmlUrl: "https://github.com/owner/reponame/pull/2368",
state: "closed",
merged: true,
mergedBy: "that-s-a-user",
title: "PR Title",
body: "Please review and merge",
reviewers: ["requested-gh-user", "gh-user"],
assignees: [],
targetRepo: {
owner: "owner",
project: "reponame",
cloneUrl: "https://github.com/owner/reponame.git"
},
sourceRepo: {
owner: "fork",
project: "reponame",
cloneUrl: "https://github.com/fork/reponame.git"
},
bpBranchName: undefined,
nCommits: 2,
commits: ["28f63db774185f4ec4b57cd9aaeb12dbfb4c9ecc"],
});
expect(configs.backportPullRequest).toEqual({
author: "Me",
url: undefined,
htmlUrl: undefined,
title: "New Title",
body: "New Body Prefix -New Body",
reviewers: ["user1", "user2"],
assignees: ["user3", "user4"],
targetRepo: {
owner: "owner",
project: "reponame",
cloneUrl: "https://github.com/owner/reponame.git"
},
sourceRepo: {
owner: "owner",
project: "reponame",
cloneUrl: "https://github.com/owner/reponame.git"
},
bpBranchName: undefined,
nCommits: 0,
commits: []
});
});
test("override backport pr empty reviewers", async () => {
const args: Args = {
dryRun: false,
auth: "",
pullRequest: mergedPRUrl,
targetBranch: "prod",
gitUser: "Me",
gitEmail: "me@email.com",
title: "New Title",
body: "New Body",
bodyPrefix: "New Body Prefix -",
reviewers: [],
assignees: ["user3", "user4"],
inheritReviewers: false,
};
const configs: Configs = await parser.parseAndValidate(args);
expect(configs.dryRun).toEqual(false);
expect(configs.git).toEqual({
user: "Me",
email: "me@email.com"
});
expect(configs.auth).toEqual("");
expect(configs.targetBranch).toEqual("prod");
expect(configs.folder).toEqual(process.cwd() + "/bp");
expect(configs.originalPullRequest).toEqual({
number: 2368,
author: "gh-user",
url: "https://api.github.com/repos/owner/reponame/pulls/2368",
htmlUrl: "https://github.com/owner/reponame/pull/2368",
state: "closed",
merged: true,
mergedBy: "that-s-a-user",
title: "PR Title",
body: "Please review and merge",
reviewers: ["requested-gh-user", "gh-user"],
assignees: [],
targetRepo: {
owner: "owner",
project: "reponame",
cloneUrl: "https://github.com/owner/reponame.git"
},
sourceRepo: {
owner: "fork",
project: "reponame",
cloneUrl: "https://github.com/fork/reponame.git"
},
bpBranchName: undefined,
nCommits: 2,
commits: ["28f63db774185f4ec4b57cd9aaeb12dbfb4c9ecc"],
});
expect(configs.backportPullRequest).toEqual({
author: "Me",
url: undefined,
htmlUrl: undefined,
title: "New Title",
body: "New Body Prefix -New Body",
reviewers: [],
assignees: ["user3", "user4"],
targetRepo: {
owner: "owner",
project: "reponame",

View file

@ -69,7 +69,10 @@ afterAll(async () => {
beforeEach(() => {
// create a fresh instance of git before each test
git = new GitCLIService("", "author");
git = new GitCLIService("", {
user: "user",
email: "user@email.com"
});
});
describe("git cli service", () => {

View file

@ -188,7 +188,8 @@ describe("cli runner", () => {
base: "target",
title: "[target] PR Title",
body: expect.stringContaining("**Backport:** https://github.com/owner/reponame/pull/2368"),
reviewers: ["gh-user", "that-s-a-user"]
reviewers: ["gh-user", "that-s-a-user"],
assignees: [],
}
);
});
@ -227,7 +228,8 @@ describe("cli runner", () => {
base: "target",
title: "[target] PR Title",
body: expect.stringContaining("**Backport:** https://github.com/owner/reponame/pull/8632"),
reviewers: ["gh-user", "that-s-a-user"]
reviewers: ["gh-user", "that-s-a-user"],
assignees: [],
}
);
});
@ -278,7 +280,8 @@ describe("cli runner", () => {
base: "target",
title: "[target] PR Title",
body: expect.stringContaining("**Backport:** https://github.com/owner/reponame/pull/4444"),
reviewers: ["gh-user", "that-s-a-user"]
reviewers: ["gh-user", "that-s-a-user"],
assignees: [],
}
);
});
@ -297,6 +300,10 @@ describe("cli runner", () => {
"New Body Prefix - ",
"--bp-branch-name",
"bp_branch_name",
"--reviewers",
"user1,user2",
"--assignees",
"user3,user4"
]);
await runner.execute();
@ -326,7 +333,60 @@ describe("cli runner", () => {
base: "target",
title: "New Title",
body: "New Body Prefix - New Body",
reviewers: ["gh-user", "that-s-a-user"]
reviewers: ["user1", "user2"],
assignees: ["user3", "user4"],
}
);
});
test("set empty reviewers", async () => {
addProcessArgs([
"-tb",
"target",
"-pr",
"https://github.com/owner/reponame/pull/2368",
"--title",
"New Title",
"--body",
"New Body",
"--body-prefix",
"New Body Prefix - ",
"--bp-branch-name",
"bp_branch_name",
"--no-inherit-reviewers",
"--assignees",
"user3,user4",
]);
await runner.execute();
const cwd = process.cwd() + "/bp";
expect(GitCLIService.prototype.clone).toBeCalledTimes(1);
expect(GitCLIService.prototype.clone).toBeCalledWith("https://github.com/owner/reponame.git", cwd, "target");
expect(GitCLIService.prototype.createLocalBranch).toBeCalledTimes(1);
expect(GitCLIService.prototype.createLocalBranch).toBeCalledWith(cwd, "bp_branch_name");
expect(GitCLIService.prototype.fetch).toBeCalledTimes(1);
expect(GitCLIService.prototype.fetch).toBeCalledWith(cwd, "pull/2368/head:pr/2368");
expect(GitCLIService.prototype.cherryPick).toBeCalledTimes(1);
expect(GitCLIService.prototype.cherryPick).toBeCalledWith(cwd, "28f63db774185f4ec4b57cd9aaeb12dbfb4c9ecc");
expect(GitCLIService.prototype.push).toBeCalledTimes(1);
expect(GitCLIService.prototype.push).toBeCalledWith(cwd, "bp_branch_name");
expect(GitHubService.prototype.createPullRequest).toBeCalledTimes(1);
expect(GitHubService.prototype.createPullRequest).toBeCalledWith({
owner: "owner",
repo: "reponame",
head: "bp_branch_name",
base: "target",
title: "New Title",
body: "New Body Prefix - New Body",
reviewers: [],
assignees: ["user3", "user4"],
}
);
});

View file

@ -87,7 +87,8 @@ describe("gha runner", () => {
base: "target",
title: "[target] PR Title",
body: expect.stringContaining("**Backport:** https://github.com/owner/reponame/pull/2368"),
reviewers: ["gh-user", "that-s-a-user"]
reviewers: ["gh-user", "that-s-a-user"],
assignees: [],
}
);
});
@ -134,7 +135,8 @@ describe("gha runner", () => {
base: "target",
title: "[target] PR Title",
body: expect.stringContaining("**Backport:** https://github.com/owner/reponame/pull/4444"),
reviewers: ["gh-user", "that-s-a-user"]
reviewers: ["gh-user", "that-s-a-user"],
assignees: [],
}
);
});
@ -147,6 +149,8 @@ describe("gha runner", () => {
"body": "New Body",
"body-prefix": "New Body Prefix - ",
"bp-branch-name": "bp_branch_name",
"reviewers": "user1, user2",
"assignees": "user3, user4",
});
await runner.execute();
@ -176,7 +180,54 @@ describe("gha runner", () => {
base: "target",
title: "New Title",
body: "New Body Prefix - New Body",
reviewers: ["gh-user", "that-s-a-user"]
reviewers: ["user1", "user2"],
assignees: ["user3", "user4"],
}
);
});
test("set empty reviewers", async () => {
spyGetInput({
"target-branch": "target",
"pull-request": "https://github.com/owner/reponame/pull/2368",
"title": "New Title",
"body": "New Body",
"body-prefix": "New Body Prefix - ",
"bp-branch-name": "bp_branch_name",
"reviewers": "",
"assignees": "user3, user4",
"no-inherit-reviewers": "true",
});
await runner.execute();
const cwd = process.cwd() + "/bp";
expect(GitCLIService.prototype.clone).toBeCalledTimes(1);
expect(GitCLIService.prototype.clone).toBeCalledWith("https://github.com/owner/reponame.git", cwd, "target");
expect(GitCLIService.prototype.createLocalBranch).toBeCalledTimes(1);
expect(GitCLIService.prototype.createLocalBranch).toBeCalledWith(cwd, "bp_branch_name");
expect(GitCLIService.prototype.fetch).toBeCalledTimes(1);
expect(GitCLIService.prototype.fetch).toBeCalledWith(cwd, "pull/2368/head:pr/2368");
expect(GitCLIService.prototype.cherryPick).toBeCalledTimes(1);
expect(GitCLIService.prototype.cherryPick).toBeCalledWith(cwd, "28f63db774185f4ec4b57cd9aaeb12dbfb4c9ecc");
expect(GitCLIService.prototype.push).toBeCalledTimes(1);
expect(GitCLIService.prototype.push).toBeCalledWith(cwd, "bp_branch_name");
expect(GitHubService.prototype.createPullRequest).toBeCalledTimes(1);
expect(GitHubService.prototype.createPullRequest).toBeCalledWith({
owner: "owner",
repo: "reponame",
head: "bp_branch_name",
base: "target",
title: "New Title",
body: "New Body Prefix - New Body",
reviewers: [],
assignees: ["user3", "user4"],
}
);
});

View file

@ -12,6 +12,16 @@ export const resetProcessArgs = () => {
export const spyGetInput = (obj: any) => {
const mock = jest.spyOn(core, "getInput");
mock.mockImplementation((name: string) : string => {
return obj[name];
return obj[name] ?? "";
});
};
/**
* Check array equality performing sort on both sides.
* DO NOT USE this if ordering matters
* @param actual
* @param expected
*/
export const expectArrayEqual = (actual: unknown[], expected: unknown[]) => {
expect(actual.sort()).toEqual(expected.sort());
};