Skip to content

Commit

Permalink
Add options: auto-assign and assignees (#205)
Browse files Browse the repository at this point in the history
  • Loading branch information
sorenlouv authored Jun 21, 2020
1 parent bb61438 commit 3b12066
Show file tree
Hide file tree
Showing 12 changed files with 157 additions and 13 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ See [configuration.md](https://github.com/sqren/backport/blob/master/docs/config
| --accesstoken | Github access token | | string |
| --all | Show commits from other than me | false | boolean |
| --author | Filter commits by author | _Current user_ | string |
| --assignees | Assign users to target pull request | | string |
| --auto-assign | Assign current user to target pull request | false | boolean |
| --branch | Target branch to backport to | | string |
| --dry-run | Perform backport without pushing to Github | false | boolean |
| --editor | Editor (eg. `code`) to open and solve conflicts | | string |
Expand Down
28 changes: 28 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,34 @@ Default: `false`

CLI: `--all`, `-a`

#### `assignees`

Add assignees to the target pull request

CLI: `--assignees <username>`, `-assign <username>`

Config:

```json
{
"assignees": ["sqren"]
}
```

#### `autoAssign`

Automatically add the current user as assignee to the target pull request

CLI: `--auto-assign`

Config:

```json
{
"autoAssign": true
}
```

#### `branchLabelMapping`

Pre-select target branch choices based on the source PR labels.
Expand Down
10 changes: 5 additions & 5 deletions src/options/cliArgs.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { getOptionsFromCliArgs } from './cliArgs';
import { OptionsFromConfigFiles } from './config/config';
import { getOptionsFromCliArgs, OptionsFromCliArgs } from './cliArgs';

describe('getOptionsFromCliArgs', () => {
it('should return correct options', () => {
const configOptions = {
const configOptions: Partial<OptionsFromCliArgs> = {
accessToken: 'myAccessToken',
all: false,
fork: true,
Expand Down Expand Up @@ -39,6 +38,7 @@ describe('getOptionsFromCliArgs', () => {
expect(res).toEqual({
accessToken: 'myAccessToken',
all: true,
assignees: [],
dryRun: false,
fork: true,
gitHostname: 'github.com',
Expand All @@ -62,7 +62,7 @@ describe('getOptionsFromCliArgs', () => {
});

it('should accept both camel-case and dashed-case and convert them to camel cased', () => {
const configOptions = {} as OptionsFromConfigFiles;
const configOptions: Partial<OptionsFromCliArgs> = {};
const argv = [
'--access-token',
'my access token',
Expand All @@ -79,7 +79,7 @@ describe('getOptionsFromCliArgs', () => {
});

it('should accept aliases (--pr) but only return the full name (--pullNumber) in the result', () => {
const configOptions = {} as OptionsFromConfigFiles;
const configOptions: Partial<OptionsFromCliArgs> = {};
const argv = ['--pr', '1337'];

const res = getOptionsFromCliArgs(configOptions, argv);
Expand Down
18 changes: 17 additions & 1 deletion src/options/cliArgs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,19 @@ export function getOptionsFromCliArgs(
type: 'string',
})

.option('assignees', {
default: (configOptions.assignees || []) as string[],
description: 'Add assignees to the target pull request',
alias: ['assignee', 'assign'],
type: 'array',
})

.option('autoAssign', {
default: (configOptions.autoAssign ?? false) as boolean,
description: 'Auto assign the target pull request to yourself',
type: 'boolean',
})

.option('dryRun', {
default: false,
description: 'Perform backport without pushing to Github',
Expand Down Expand Up @@ -266,11 +279,14 @@ export function getOptionsFromCliArgs(
).argv;

// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
const { $0, _, verify, multiple, ...rest } = cliArgs;
const { $0, _, verify, multiple, autoAssign, ...rest } = cliArgs;

return {
...rest,

// auto-assign the current user to the target pull request or the assignees specified
assignees: autoAssign ? [rest.username as string] : rest.assignees,

// `branchLabelMapping` is not available as cli argument
branchLabelMapping: configOptions.branchLabelMapping as BranchLabelMapping,

Expand Down
2 changes: 2 additions & 0 deletions src/options/options.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ describe('getOptions', () => {
accessToken: 'myAccessToken',
all: false,
author: 'sqren',
assignees: [],
dryRun: false,
fork: true,
gitHostname: 'github.com',
Expand Down Expand Up @@ -107,6 +108,7 @@ describe('validateRequiredOptions', () => {
accessToken: 'myAccessToken',
all: false,
author: undefined,
assignees: [],
branchLabelMapping: undefined,
dryRun: false,
editor: 'code',
Expand Down
1 change: 1 addition & 0 deletions src/runWithOptions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ describe('runWithOptions', () => {
accessToken: 'myAccessToken',
all: false,
author: 'sqren',
assignees: [],
branchLabelMapping: undefined,
dryRun: false,
editor: 'code',
Expand Down
35 changes: 35 additions & 0 deletions src/services/github/v3/addAssigneesToPullRequest.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import axios from 'axios';
import { BackportOptions } from '../../../options/options';
import { addAssigneesToPullRequest } from './addAssigneesToPullRequest';

describe('addAssigneesToPullRequest', () => {
it('should add assignees to PR', async () => {
const pullNumber = 216;
const assignees = ['sqren'];

const spy = jest
.spyOn(axios, 'request')
.mockResolvedValueOnce('some-response');

await addAssigneesToPullRequest(
{
githubApiBaseUrlV3: 'https://api.github.com',
repoName: 'backport-demo',
repoOwner: 'sqren',
accessToken: 'my-token',
username: 'sqren',
dryRun: false,
} as BackportOptions,
pullNumber,
assignees
);

expect(spy).toHaveBeenCalledWith({
method: 'post',
url:
'https://api.github.com/repos/sqren/backport-demo/issues/216/assignees',
auth: { username: 'sqren', password: 'my-token' },
data: { assignees: ['sqren'] },
});
});
});
46 changes: 46 additions & 0 deletions src/services/github/v3/addAssigneesToPullRequest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import ora from 'ora';
import { BackportOptions } from '../../../options/options';
import { logger } from '../../logger';
import { apiRequestV3 } from './apiRequestV3';

export async function addAssigneesToPullRequest(
{
githubApiBaseUrlV3,
repoName,
repoOwner,
accessToken,
username,
dryRun,
}: BackportOptions,
pullNumber: number,
assignees: string[]
): Promise<void> {
const isSelfAssigning = assignees.length === 1 && assignees[0] === username;

const text = isSelfAssigning
? `Self-assigning to #${pullNumber}`
: `Adding assignees to #${pullNumber}: ${assignees.join(', ')}`;
logger.info(text);
const spinner = ora(text).start();

try {
if (dryRun) {
spinner.succeed(`Dry run: ${text}`);
return;
}

await apiRequestV3({
method: 'post',
url: `${githubApiBaseUrlV3}/repos/${repoOwner}/${repoName}/issues/${pullNumber}/assignees`,
data: { assignees },
auth: {
username: username,
password: accessToken,
},
});
spinner.succeed();
} catch (e) {
spinner.fail();
logger.info(`Could not add assignees to PR ${pullNumber}`, e.stack);
}
}
2 changes: 1 addition & 1 deletion src/services/github/v3/createPullRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export async function createPullRequest(
const spinner = ora(`Creating pull request`).start();

if (dryRun) {
spinner.succeed();
spinner.succeed('Dry run: Creating pull request');
return { html_url: 'example_url', number: 1337 };
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ Array [
Object {
"accessToken": "myAccessToken",
"all": false,
"assignees": Array [],
"author": "sqren",
"branchLabelMapping": undefined,
"dryRun": false,
Expand Down
3 changes: 3 additions & 0 deletions src/ui/cherrypickAndCreatePullRequest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ describe('cherrypickAndCreateTargetPullRequest', () => {
.mockResolvedValue({ stdout: '', stderr: '' });

const options = {
assignees: [] as string[],
githubApiBaseUrlV3: 'https://api.github.com',
fork: true,
targetPRLabels: ['backport'],
Expand Down Expand Up @@ -142,6 +143,7 @@ describe('cherrypickAndCreateTargetPullRequest', () => {
describe('when commit does not have a pull request reference', () => {
beforeEach(async () => {
const options = {
assignees: [] as string[],
githubApiBaseUrlV3: 'https://api.github.com',
fork: true,
targetPRLabels: ['backport'],
Expand Down Expand Up @@ -202,6 +204,7 @@ describe('cherrypickAndCreateTargetPullRequest', () => {
const execSpy = setupExecSpy();

const options = {
assignees: [] as string[],
fork: true,
targetPRLabels: ['backport'],
prTitle: '[{targetBranch}] {commitMessages}',
Expand Down
22 changes: 16 additions & 6 deletions src/ui/cherrypickAndCreateTargetPullRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
getFilesWithConflicts,
} from '../services/git';
import { getShortSha } from '../services/github/commitFormatters';
import { addAssigneesToPullRequest } from '../services/github/v3/addAssigneesToPullRequest';
import { addLabelsToPullRequest } from '../services/github/v3/addLabelsToPullRequest';
import { createPullRequest } from '../services/github/v3/createPullRequest';
import { consoleLog } from '../services/logger';
Expand Down Expand Up @@ -53,18 +54,27 @@ export async function cherrypickAndCreateTargetPullRequest({
spinner.stop();

const payload = getPullRequestPayload(options, targetBranch, commits);
const pullRequest = await createPullRequest(options, payload);
const targetPullRequest = await createPullRequest(options, payload);

// add targetPRLabels
// add assignees to target pull request
if (options.assignees.length > 0) {
await addAssigneesToPullRequest(
options,
targetPullRequest.number,
options.assignees
);
}

// add labels to target pull request
if (options.targetPRLabels.length > 0) {
await addLabelsToPullRequest(
options,
pullRequest.number,
targetPullRequest.number,
options.targetPRLabels
);
}

// add sourcePRLabels
// add labels to source pull requests
if (options.sourcePRLabels.length > 0) {
const promises = commits.map((commit) => {
if (commit.pullNumber) {
Expand All @@ -78,7 +88,7 @@ export async function cherrypickAndCreateTargetPullRequest({
await Promise.all(promises);
}

consoleLog(`View pull request: ${pullRequest.html_url}`);
consoleLog(`View pull request: ${targetPullRequest.html_url}`);

// output PR summary in dry run mode
if (options.dryRun) {
Expand All @@ -88,7 +98,7 @@ export async function cherrypickAndCreateTargetPullRequest({
consoleLog(`Body: ${payload.body}\n`);
}

return pullRequest;
return targetPullRequest;
}

function getFeatureBranchName(targetBranch: string, commits: CommitSelected[]) {
Expand Down

0 comments on commit 3b12066

Please sign in to comment.