feat: override local git user config

This commit is contained in:
Andrea Lamparelli 2023-06-22 14:33:59 +02:00
parent 22bec0c537
commit ee692c3db4
16 changed files with 182 additions and 73 deletions

View file

@ -57,6 +57,8 @@ 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 | | | 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) | "" | | 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 | | 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}" | | Title | --title | N | Backporting pull request title | "{original-pr-title}" |
| Body | --body | N | Backporting pull request body | "{original-pr-body}" | | 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}" | | Body Prefix | --body-prefix | N | Prefix to the backporting pull request body | "Backport: {original-pr-link}" |

View file

@ -9,6 +9,14 @@ inputs:
description: "GITHUB_TOKEN or a `repo` scoped Personal Access Token (PAT)." description: "GITHUB_TOKEN or a `repo` scoped Personal Access Token (PAT)."
default: ${{ github.token }} default: ${{ github.token }}
required: false 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: pull-request:
description: "URL of the pull request to backport, e.g., https://github.com/lampajr/backporting/pull/1." description: "URL of the pull request to backport, e.g., https://github.com/lampajr/backporting/pull/1."
required: true required: true

35
dist/cli/index.js vendored
View file

@ -36,14 +36,16 @@ class CLIArgsParser {
.version(package_json_1.version) .version(package_json_1.version)
.description(package_json_1.description) .description(package_json_1.description)
.requiredOption("-tb, --target-branch <branch>", "branch where changes must be backported to.") .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("-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("-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("-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("--title <bp-title>", "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 <bp-body>", "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("--body-prefix <bp-body-prefix>", "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("--bp-branch-name <bp-branch-name>", "backport pr branch name, default auto-generated by the commit.", undefined);
} }
parse() { parse() {
const opts = this.getCommand() const opts = this.getCommand()
@ -55,6 +57,8 @@ class CLIArgsParser {
pullRequest: opts.pullRequest, pullRequest: opts.pullRequest,
targetBranch: opts.targetBranch, targetBranch: opts.targetBranch,
folder: opts.folder, folder: opts.folder,
gitUser: opts.gitUser,
gitEmail: opts.gitEmail,
title: opts.title, title: opts.title,
body: opts.body, body: opts.body,
bodyPrefix: opts.bodyPrefix, bodyPrefix: opts.bodyPrefix,
@ -126,11 +130,14 @@ class PullRequestConfigsParser extends configs_parser_1.default {
return { return {
dryRun: args.dryRun, dryRun: args.dryRun,
auth: args.auth, auth: args.auth,
author: args.author ?? pr.author,
folder: `${folder.startsWith("/") ? "" : process.cwd() + "/"}${args.folder ?? this.getDefaultFolder()}`, folder: `${folder.startsWith("/") ? "" : process.cwd() + "/"}${args.folder ?? this.getDefaultFolder()}`,
targetBranch: args.targetBranch, targetBranch: args.targetBranch,
originalPullRequest: pr, originalPullRequest: pr,
backportPullRequest: this.getDefaultBackportPullRequest(pr, args) backportPullRequest: this.getDefaultBackportPullRequest(pr, args),
git: {
user: args.gitUser,
email: args.gitEmail,
}
}; };
} }
getDefaultFolder() { getDefaultFolder() {
@ -152,7 +159,7 @@ class PullRequestConfigsParser extends configs_parser_1.default {
const bodyPrefix = args.bodyPrefix ?? `**Backport:** ${originalPullRequest.htmlUrl}\r\n\r\n`; 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).`; const body = args.body ?? `${originalPullRequest.body}\r\n\r\nPowered by [BPer](https://github.com/lampajr/backporting).`;
return { return {
author: originalPullRequest.author, author: args.gitUser,
title: args.title ?? `[${args.targetBranch}] ${originalPullRequest.title}`, title: args.title ?? `[${args.targetBranch}] ${originalPullRequest.title}`,
body: `${bodyPrefix}${body}`, body: `${bodyPrefix}${body}`,
reviewers: [...new Set(reviewers)], reviewers: [...new Set(reviewers)],
@ -185,10 +192,10 @@ const fs_1 = __importDefault(__nccwpck_require__(7147));
* Command line git commands executor service * Command line git commands executor service
*/ */
class GitCLIService { class GitCLIService {
constructor(auth, author) { constructor(auth, gitData) {
this.logger = logger_service_factory_1.default.getLogger(); this.logger = logger_service_factory_1.default.getLogger();
this.auth = auth; this.auth = auth;
this.author = author; this.gitData = gitData;
} }
/** /**
* Return a pre-configured SimpleGit instance able to execute commands from current * Return a pre-configured SimpleGit instance able to execute commands from current
@ -198,15 +205,15 @@ class GitCLIService {
*/ */
git(cwd) { git(cwd) {
const gitConfig = { ...(cwd ? { baseDir: 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 * 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 * @param remoteURL remote link, e.g., https://github.com/lampajr/backporting-example.git
*/ */
remoteWithAuth(remoteURL) { remoteWithAuth(remoteURL) {
if (this.auth && this.author) { if (this.auth && this.gitData.user) {
return remoteURL.replace("://", `://${this.author}:${this.auth}@`); return remoteURL.replace("://", `://${this.gitData.user}:${this.auth}@`);
} }
// return remote as it is // return remote as it is
return remoteURL; return remoteURL;
@ -657,7 +664,7 @@ class Runner {
const originalPR = configs.originalPullRequest; const originalPR = configs.originalPullRequest;
const backportPR = configs.backportPullRequest; const backportPR = configs.backportPullRequest;
// start local git operations // 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 // 4. clone the repository
await git.clone(configs.originalPullRequest.targetRepo.cloneUrl, configs.folder, configs.targetBranch); await git.clone(configs.originalPullRequest.targetRepo.cloneUrl, configs.folder, configs.targetBranch);
// 5. create new branch from target one and checkout // 5. create new branch from target one and checkout

39
dist/gha/index.js vendored
View file

@ -35,21 +35,27 @@ class GHAArgsParser {
* @param key input key * @param key input key
* @returns the value or undefined * @returns the value or undefined
*/ */
_getOrUndefined(key) { getOrUndefined(key) {
const value = (0, core_1.getInput)(key); const value = (0, core_1.getInput)(key);
return value !== "" ? value : undefined; return value !== "" ? value : undefined;
} }
getOrDefault(key, defaultValue) {
const value = (0, core_1.getInput)(key);
return (value !== undefined && value !== "") ? value : defaultValue;
}
parse() { parse() {
return { return {
dryRun: (0, core_1.getInput)("dry-run") === "true", dryRun: (0, core_1.getInput)("dry-run") === "true",
auth: (0, core_1.getInput)("auth") ? (0, core_1.getInput)("auth") : "", auth: (0, core_1.getInput)("auth") ? (0, core_1.getInput)("auth") : "",
pullRequest: (0, core_1.getInput)("pull-request"), pullRequest: (0, core_1.getInput)("pull-request"),
targetBranch: (0, core_1.getInput)("target-branch"), targetBranch: (0, core_1.getInput)("target-branch"),
folder: this._getOrUndefined("folder"), folder: this.getOrUndefined("folder"),
title: this._getOrUndefined("title"), gitUser: this.getOrDefault("git-user", "GitHub"),
body: this._getOrUndefined("body"), gitEmail: this.getOrDefault("git-email", "noreply@github.com"),
bodyPrefix: this._getOrUndefined("body-prefix"), title: this.getOrUndefined("title"),
bpBranchName: this._getOrUndefined("bp-branch-name"), body: this.getOrUndefined("body"),
bodyPrefix: this.getOrUndefined("body-prefix"),
bpBranchName: this.getOrUndefined("bp-branch-name"),
}; };
} }
} }
@ -117,11 +123,14 @@ class PullRequestConfigsParser extends configs_parser_1.default {
return { return {
dryRun: args.dryRun, dryRun: args.dryRun,
auth: args.auth, auth: args.auth,
author: args.author ?? pr.author,
folder: `${folder.startsWith("/") ? "" : process.cwd() + "/"}${args.folder ?? this.getDefaultFolder()}`, folder: `${folder.startsWith("/") ? "" : process.cwd() + "/"}${args.folder ?? this.getDefaultFolder()}`,
targetBranch: args.targetBranch, targetBranch: args.targetBranch,
originalPullRequest: pr, originalPullRequest: pr,
backportPullRequest: this.getDefaultBackportPullRequest(pr, args) backportPullRequest: this.getDefaultBackportPullRequest(pr, args),
git: {
user: args.gitUser,
email: args.gitEmail,
}
}; };
} }
getDefaultFolder() { getDefaultFolder() {
@ -143,7 +152,7 @@ class PullRequestConfigsParser extends configs_parser_1.default {
const bodyPrefix = args.bodyPrefix ?? `**Backport:** ${originalPullRequest.htmlUrl}\r\n\r\n`; 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).`; const body = args.body ?? `${originalPullRequest.body}\r\n\r\nPowered by [BPer](https://github.com/lampajr/backporting).`;
return { return {
author: originalPullRequest.author, author: args.gitUser,
title: args.title ?? `[${args.targetBranch}] ${originalPullRequest.title}`, title: args.title ?? `[${args.targetBranch}] ${originalPullRequest.title}`,
body: `${bodyPrefix}${body}`, body: `${bodyPrefix}${body}`,
reviewers: [...new Set(reviewers)], reviewers: [...new Set(reviewers)],
@ -176,10 +185,10 @@ const fs_1 = __importDefault(__nccwpck_require__(7147));
* Command line git commands executor service * Command line git commands executor service
*/ */
class GitCLIService { class GitCLIService {
constructor(auth, author) { constructor(auth, gitData) {
this.logger = logger_service_factory_1.default.getLogger(); this.logger = logger_service_factory_1.default.getLogger();
this.auth = auth; this.auth = auth;
this.author = author; this.gitData = gitData;
} }
/** /**
* Return a pre-configured SimpleGit instance able to execute commands from current * Return a pre-configured SimpleGit instance able to execute commands from current
@ -189,15 +198,15 @@ class GitCLIService {
*/ */
git(cwd) { git(cwd) {
const gitConfig = { ...(cwd ? { baseDir: 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 * 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 * @param remoteURL remote link, e.g., https://github.com/lampajr/backporting-example.git
*/ */
remoteWithAuth(remoteURL) { remoteWithAuth(remoteURL) {
if (this.auth && this.author) { if (this.auth && this.gitData.user) {
return remoteURL.replace("://", `://${this.author}:${this.auth}@`); return remoteURL.replace("://", `://${this.gitData.user}:${this.auth}@`);
} }
// return remote as it is // return remote as it is
return remoteURL; return remoteURL;
@ -648,7 +657,7 @@ class Runner {
const originalPR = configs.originalPullRequest; const originalPR = configs.originalPullRequest;
const backportPR = configs.backportPullRequest; const backportPR = configs.backportPullRequest;
// start local git operations // 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 // 4. clone the repository
await git.clone(configs.originalPullRequest.targetRepo.cloneUrl, configs.folder, configs.targetBranch); await git.clone(configs.originalPullRequest.targetRepo.cloneUrl, configs.folder, configs.targetBranch);
// 5. create new branch from target one and checkout // 5. create new branch from target one and checkout

View file

@ -7,7 +7,8 @@ export interface Args {
targetBranch: string, // branch on the target repo where the change should be backported to targetBranch: string, // branch on the target repo where the change should be backported to
pullRequest: string, // url of the pull request to backport pullRequest: string, // url of the pull request to backport
folder?: string, // local folder where the repositories should be cloned 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 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 body?: string, // backport pr title, default original pr body prefixed by bodyPrefix
bodyPrefix?: string, // backport pr body prefix, default `backport <original-pr-link>` bodyPrefix?: string, // backport pr body prefix, default `backport <original-pr-link>`

View file

@ -11,14 +11,16 @@ export default class CLIArgsParser implements ArgsParser {
.version(version) .version(version)
.description(description) .description(description)
.requiredOption("-tb, --target-branch <branch>", "branch where changes must be backported to.") .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("-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("-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("-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("--title <bp-title>", "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 <bp-body>", "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("--body-prefix <bp-body-prefix>", "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("--bp-branch-name <bp-branch-name>", "backport pr branch name, default auto-generated by the commit.", undefined);
} }
parse(): Args { parse(): Args {
@ -32,6 +34,8 @@ export default class CLIArgsParser implements ArgsParser {
pullRequest: opts.pullRequest, pullRequest: opts.pullRequest,
targetBranch: opts.targetBranch, targetBranch: opts.targetBranch,
folder: opts.folder, folder: opts.folder,
gitUser: opts.gitUser,
gitEmail: opts.gitEmail,
title: opts.title, title: opts.title,
body: opts.body, body: opts.body,
bodyPrefix: opts.bodyPrefix, bodyPrefix: opts.bodyPrefix,

View file

@ -9,22 +9,29 @@ export default class GHAArgsParser implements ArgsParser {
* @param key input key * @param key input key
* @returns the value or undefined * @returns the value or undefined
*/ */
private _getOrUndefined(key: string): string | undefined { public getOrUndefined(key: string): string | undefined {
const value = getInput(key); const value = getInput(key);
return value !== "" ? value : undefined; return value !== "" ? value : undefined;
} }
public getOrDefault(key: string, defaultValue: string): string {
const value = getInput(key);
return (value !== undefined && value !== "") ? value : defaultValue;
}
parse(): Args { parse(): Args {
return { return {
dryRun: getInput("dry-run") === "true", dryRun: getInput("dry-run") === "true",
auth: getInput("auth") ? getInput("auth") : "", auth: getInput("auth") ? getInput("auth") : "",
pullRequest: getInput("pull-request"), pullRequest: getInput("pull-request"),
targetBranch: getInput("target-branch"), targetBranch: getInput("target-branch"),
folder: this._getOrUndefined("folder"), folder: this.getOrUndefined("folder"),
title: this._getOrUndefined("title"), gitUser: this.getOrDefault("git-user", "GitHub"),
body: this._getOrUndefined("body"), gitEmail: this.getOrDefault("git-email", "noreply@github.com"),
bodyPrefix: this._getOrUndefined("body-prefix"), title: this.getOrUndefined("title"),
bpBranchName: this._getOrUndefined("bp-branch-name"), body: this.getOrUndefined("body"),
bodyPrefix: this.getOrUndefined("body-prefix"),
bpBranchName: this.getOrUndefined("bp-branch-name"),
}; };
} }

View file

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

View file

@ -21,11 +21,14 @@ export default class PullRequestConfigsParser extends ConfigsParser {
return { return {
dryRun: args.dryRun, dryRun: args.dryRun,
auth: args.auth, auth: args.auth,
author: args.author ?? pr.author,
folder: `${folder.startsWith("/") ? "" : process.cwd() + "/"}${args.folder ?? this.getDefaultFolder()}`, folder: `${folder.startsWith("/") ? "" : process.cwd() + "/"}${args.folder ?? this.getDefaultFolder()}`,
targetBranch: args.targetBranch, targetBranch: args.targetBranch,
originalPullRequest: pr, originalPullRequest: pr,
backportPullRequest: this.getDefaultBackportPullRequest(pr, args) backportPullRequest: this.getDefaultBackportPullRequest(pr, args),
git: {
user: args.gitUser,
email: args.gitEmail,
}
}; };
} }
@ -51,7 +54,7 @@ export default class PullRequestConfigsParser extends ConfigsParser {
const body = args.body ?? `${originalPullRequest.body}\r\n\r\nPowered by [BPer](https://github.com/lampajr/backporting).`; const body = args.body ?? `${originalPullRequest.body}\r\n\r\nPowered by [BPer](https://github.com/lampajr/backporting).`;
return { return {
author: originalPullRequest.author, author: args.gitUser,
title: args.title ?? `[${args.targetBranch}] ${originalPullRequest.title}`, title: args.title ?? `[${args.targetBranch}] ${originalPullRequest.title}`,
body: `${bodyPrefix}${body}`, body: `${bodyPrefix}${body}`,
reviewers: [...new Set(reviewers)], reviewers: [...new Set(reviewers)],

View file

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

View file

@ -80,7 +80,7 @@ export default class Runner {
const backportPR: GitPullRequest = configs.backportPullRequest; const backportPR: GitPullRequest = configs.backportPullRequest;
// start local git operations // 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 // 4. clone the repository
await git.clone(configs.originalPullRequest.targetRepo.cloneUrl, configs.folder, configs.targetBranch); await git.clone(configs.originalPullRequest.targetRepo.cloneUrl, configs.folder, configs.targetBranch);

View file

@ -24,7 +24,8 @@ describe("cli args parser", () => {
const args: Args = parser.parse(); const args: Args = parser.parse();
expect(args.dryRun).toEqual(false); expect(args.dryRun).toEqual(false);
expect(args.auth).toEqual(""); 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.folder).toEqual(undefined);
expect(args.targetBranch).toEqual("target"); expect(args.targetBranch).toEqual("target");
expect(args.pullRequest).toEqual("https://localhost/whatever/pulls/1"); expect(args.pullRequest).toEqual("https://localhost/whatever/pulls/1");
@ -45,7 +46,8 @@ describe("cli args parser", () => {
const args: Args = parser.parse(); const args: Args = parser.parse();
expect(args.dryRun).toEqual(false); expect(args.dryRun).toEqual(false);
expect(args.auth).toEqual(""); 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.folder).toEqual(undefined);
expect(args.targetBranch).toEqual("target"); expect(args.targetBranch).toEqual("target");
expect(args.pullRequest).toEqual("https://localhost/whatever/pulls/1"); expect(args.pullRequest).toEqual("https://localhost/whatever/pulls/1");
@ -63,13 +65,18 @@ describe("cli args parser", () => {
"-tb", "-tb",
"target", "target",
"-pr", "-pr",
"https://localhost/whatever/pulls/1" "https://localhost/whatever/pulls/1",
"-gu",
"Me",
"-ge",
"me@email.com",
]); ]);
const args: Args = parser.parse(); const args: Args = parser.parse();
expect(args.dryRun).toEqual(true); expect(args.dryRun).toEqual(true);
expect(args.auth).toEqual("bearer-token"); 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.folder).toEqual(undefined);
expect(args.targetBranch).toEqual("target"); expect(args.targetBranch).toEqual("target");
expect(args.pullRequest).toEqual("https://localhost/whatever/pulls/1"); expect(args.pullRequest).toEqual("https://localhost/whatever/pulls/1");
@ -88,6 +95,10 @@ describe("cli args parser", () => {
"target", "target",
"--pull-request", "--pull-request",
"https://localhost/whatever/pulls/1", "https://localhost/whatever/pulls/1",
"--git-user",
"Me",
"--git-email",
"me@email.com",
"--title", "--title",
"New Title", "New Title",
"--body", "--body",
@ -101,7 +112,8 @@ describe("cli args parser", () => {
const args: Args = parser.parse(); const args: Args = parser.parse();
expect(args.dryRun).toEqual(true); expect(args.dryRun).toEqual(true);
expect(args.auth).toEqual("bearer-token"); 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.folder).toEqual(undefined);
expect(args.targetBranch).toEqual("target"); expect(args.targetBranch).toEqual("target");
expect(args.pullRequest).toEqual("https://localhost/whatever/pulls/1"); expect(args.pullRequest).toEqual("https://localhost/whatever/pulls/1");

View file

@ -14,6 +14,22 @@ describe("gha args parser", () => {
jest.clearAllMocks(); 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("valid execution [default]", () => { test("valid execution [default]", () => {
spyGetInput({ spyGetInput({
@ -24,7 +40,8 @@ describe("gha args parser", () => {
const args: Args = parser.parse(); const args: Args = parser.parse();
expect(args.dryRun).toEqual(false); expect(args.dryRun).toEqual(false);
expect(args.auth).toEqual(""); 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.folder).toEqual(undefined);
expect(args.targetBranch).toEqual("target"); expect(args.targetBranch).toEqual("target");
expect(args.pullRequest).toEqual("https://localhost/whatever/pulls/1"); expect(args.pullRequest).toEqual("https://localhost/whatever/pulls/1");
@ -40,6 +57,8 @@ describe("gha args parser", () => {
"auth": "bearer-token", "auth": "bearer-token",
"target-branch": "target", "target-branch": "target",
"pull-request": "https://localhost/whatever/pulls/1", "pull-request": "https://localhost/whatever/pulls/1",
"git-user": "Me",
"git-email": "me@email.com",
"title": "New Title", "title": "New Title",
"body": "New Body", "body": "New Body",
"body-prefix": "New Body Prefix", "body-prefix": "New Body Prefix",
@ -49,7 +68,8 @@ describe("gha args parser", () => {
const args: Args = parser.parse(); const args: Args = parser.parse();
expect(args.dryRun).toEqual(true); expect(args.dryRun).toEqual(true);
expect(args.auth).toEqual("bearer-token"); 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.folder).toEqual(undefined);
expect(args.targetBranch).toEqual("target"); expect(args.targetBranch).toEqual("target");
expect(args.pullRequest).toEqual("https://localhost/whatever/pulls/1"); expect(args.pullRequest).toEqual("https://localhost/whatever/pulls/1");

View file

@ -33,13 +33,18 @@ describe("pull request config parser", () => {
dryRun: false, dryRun: false,
auth: "", auth: "",
pullRequest: mergedPRUrl, pullRequest: mergedPRUrl,
targetBranch: "prod" targetBranch: "prod",
gitUser: "GitHub",
gitEmail: "noreply@github.com"
}; };
const configs: Configs = await parser.parseAndValidate(args); const configs: Configs = await parser.parseAndValidate(args);
expect(configs.dryRun).toEqual(false); 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.auth).toEqual("");
expect(configs.targetBranch).toEqual("prod"); expect(configs.targetBranch).toEqual("prod");
expect(configs.folder).toEqual(process.cwd() + "/bp"); expect(configs.folder).toEqual(process.cwd() + "/bp");
@ -68,7 +73,7 @@ describe("pull request config parser", () => {
commits: ["28f63db774185f4ec4b57cd9aaeb12dbfb4c9ecc"] commits: ["28f63db774185f4ec4b57cd9aaeb12dbfb4c9ecc"]
}); });
expect(configs.backportPullRequest).toEqual({ expect(configs.backportPullRequest).toEqual({
author: "gh-user", author: "GitHub",
url: undefined, url: undefined,
htmlUrl: undefined, htmlUrl: undefined,
title: "[prod] PR Title", title: "[prod] PR Title",
@ -96,7 +101,9 @@ describe("pull request config parser", () => {
auth: "whatever", auth: "whatever",
pullRequest: mergedPRUrl, pullRequest: mergedPRUrl,
targetBranch: "prod", targetBranch: "prod",
folder: "/tmp/test" folder: "/tmp/test",
gitUser: "GitHub",
gitEmail: "noreply@github.com"
}; };
const configs: Configs = await parser.parseAndValidate(args); const configs: Configs = await parser.parseAndValidate(args);
@ -105,6 +112,10 @@ describe("pull request config parser", () => {
expect(configs.auth).toEqual("whatever"); expect(configs.auth).toEqual("whatever");
expect(configs.targetBranch).toEqual("prod"); expect(configs.targetBranch).toEqual("prod");
expect(configs.folder).toEqual("/tmp/test"); expect(configs.folder).toEqual("/tmp/test");
expect(configs.git).toEqual({
user: "GitHub",
email: "noreply@github.com"
});
}); });
test("override author", async () => { test("override author", async () => {
@ -113,7 +124,8 @@ describe("pull request config parser", () => {
auth: "whatever", auth: "whatever",
pullRequest: mergedPRUrl, pullRequest: mergedPRUrl,
targetBranch: "prod", targetBranch: "prod",
author: "another-user" gitUser: "GitHub",
gitEmail: "noreply@github.com"
}; };
const configs: Configs = await parser.parseAndValidate(args); const configs: Configs = await parser.parseAndValidate(args);
@ -121,7 +133,10 @@ describe("pull request config parser", () => {
expect(configs.dryRun).toEqual(true); expect(configs.dryRun).toEqual(true);
expect(configs.auth).toEqual("whatever"); expect(configs.auth).toEqual("whatever");
expect(configs.targetBranch).toEqual("prod"); 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 () => { test("still open pull request", async () => {
@ -129,7 +144,9 @@ describe("pull request config parser", () => {
dryRun: true, dryRun: true,
auth: "whatever", auth: "whatever",
pullRequest: openPRUrl, pullRequest: openPRUrl,
targetBranch: "prod" targetBranch: "prod",
gitUser: "GitHub",
gitEmail: "noreply@github.com"
}; };
const configs: Configs = await parser.parseAndValidate(args); const configs: Configs = await parser.parseAndValidate(args);
@ -137,7 +154,10 @@ describe("pull request config parser", () => {
expect(configs.dryRun).toEqual(true); expect(configs.dryRun).toEqual(true);
expect(configs.auth).toEqual("whatever"); expect(configs.auth).toEqual("whatever");
expect(configs.targetBranch).toEqual("prod"); 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({ expect(configs.originalPullRequest).toEqual({
number: 4444, number: 4444,
author: "gh-user", author: "gh-user",
@ -171,7 +191,9 @@ describe("pull request config parser", () => {
dryRun: true, dryRun: true,
auth: "whatever", auth: "whatever",
pullRequest: notMergedPRUrl, pullRequest: notMergedPRUrl,
targetBranch: "prod" targetBranch: "prod",
gitUser: "GitHub",
gitEmail: "noreply@github.com"
}; };
expect(async () => await parser.parseAndValidate(args)).rejects.toThrow("Provided pull request is closed and not merged!"); expect(async () => await parser.parseAndValidate(args)).rejects.toThrow("Provided pull request is closed and not merged!");
@ -183,6 +205,8 @@ describe("pull request config parser", () => {
auth: "", auth: "",
pullRequest: mergedPRUrl, pullRequest: mergedPRUrl,
targetBranch: "prod", targetBranch: "prod",
gitUser: "Me",
gitEmail: "me@email.com",
title: "New Title", title: "New Title",
body: "New Body", body: "New Body",
bodyPrefix: "New Body Prefix -", bodyPrefix: "New Body Prefix -",
@ -191,7 +215,10 @@ describe("pull request config parser", () => {
const configs: Configs = await parser.parseAndValidate(args); const configs: Configs = await parser.parseAndValidate(args);
expect(configs.dryRun).toEqual(false); 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.auth).toEqual("");
expect(configs.targetBranch).toEqual("prod"); expect(configs.targetBranch).toEqual("prod");
expect(configs.folder).toEqual(process.cwd() + "/bp"); expect(configs.folder).toEqual(process.cwd() + "/bp");
@ -221,7 +248,7 @@ describe("pull request config parser", () => {
commits: ["28f63db774185f4ec4b57cd9aaeb12dbfb4c9ecc"], commits: ["28f63db774185f4ec4b57cd9aaeb12dbfb4c9ecc"],
}); });
expect(configs.backportPullRequest).toEqual({ expect(configs.backportPullRequest).toEqual({
author: "gh-user", author: "Me",
url: undefined, url: undefined,
htmlUrl: undefined, htmlUrl: undefined,
title: "New Title", title: "New Title",

View file

@ -69,7 +69,10 @@ afterAll(async () => {
beforeEach(() => { beforeEach(() => {
// create a fresh instance of git before each test // 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", () => { describe("git cli service", () => {

View file

@ -12,6 +12,6 @@ export const resetProcessArgs = () => {
export const spyGetInput = (obj: any) => { export const spyGetInput = (obj: any) => {
const mock = jest.spyOn(core, "getInput"); const mock = jest.spyOn(core, "getInput");
mock.mockImplementation((name: string) : string => { mock.mockImplementation((name: string) : string => {
return obj[name]; return obj[name] ?? "";
}); });
}; };