Skip to content

Commit

Permalink
feat: override backporting pr fields (#38)
Browse files Browse the repository at this point in the history
* feat: override local git user config

* feat(issue-32): override reviewers and assignees
  • Loading branch information
lampajr committed Jun 22, 2023
1 parent 22bec0c commit a32e8cd
Show file tree
Hide file tree
Showing 21 changed files with 671 additions and 107 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |

Expand Down
18 changes: 18 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
77 changes: 57 additions & 20 deletions dist/cli/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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,
};
}
}
Expand Down Expand Up @@ -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() {
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand All @@ -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;
Expand Down Expand Up @@ -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],
Expand Down Expand Up @@ -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
/**
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down

0 comments on commit a32e8cd

Please sign in to comment.