Skip to content

Commit

Permalink
Output json when ci=true (#300)
Browse files Browse the repository at this point in the history
  • Loading branch information
sorenlouv authored Feb 11, 2022
1 parent f51090d commit 831154d
Show file tree
Hide file tree
Showing 48 changed files with 820 additions and 793 deletions.
6 changes: 4 additions & 2 deletions src/backportRun.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import chalk from 'chalk';
import ora from 'ora';
import yargsParser from 'yargs-parser';
import { ConfigFileOptions } from './options/ConfigOptions';
import { getOptions, ValidConfigOptions } from './options/options';
Expand All @@ -12,6 +11,7 @@ import { consoleLog, initLogger, logger } from './services/logger';
import { Commit } from './services/sourceCommit/parseSourceCommit';
import { getCommits } from './ui/getCommits';
import { getTargetBranches } from './ui/getTargetBranches';
import { ora } from './ui/ora';

export type BackportResponse =
| {
Expand All @@ -23,6 +23,7 @@ export type BackportResponse =
status: 'failure';
commits: Commit[];
error: Error | HandledError;
errorMessage: string;
};

export async function backportRun(
Expand All @@ -36,7 +37,7 @@ export async function backportRun(
initLogger({ ci, logFilePath });

// don't show spinner for yargs commands that exit the process without stopping the spinner first
const spinner = ora();
const spinner = ora(ci);

if (!argv.help && !argv.version && !argv.v) {
spinner.start('Initializing...');
Expand Down Expand Up @@ -78,6 +79,7 @@ export async function backportRun(
status: 'failure',
commits,
error: e,
errorMessage: e.message,
};

if (options) {
Expand Down
11 changes: 10 additions & 1 deletion src/entrypoint.cli.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
#!/usr/bin/env node
import yargsParser from 'yargs-parser';
import { backportRun } from './backportRun';
import { ConfigFileOptions } from './entrypoint.module';
const processArgs = process.argv.slice(2);

// this is the entrypoint when running from command line
backportRun(processArgs);
backportRun(processArgs).then((backportResponse) => {
const argv = yargsParser(processArgs) as ConfigFileOptions;
const ci = argv.ci;
if (ci) {
// eslint-disable-next-line no-console
console.log(JSON.stringify(backportResponse));
}
});
2 changes: 1 addition & 1 deletion src/options/ConfigOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export type ConfigFileOptions = Options &
version: boolean;
v: boolean;

// only allowed in project config. Not allowed in CI and denoted in plural (historicalBranchLabelMappings) in options from Github
// only allowed in project config. Not allowed in CI mode
branchLabelMapping: Record<string, string>;

/**
Expand Down
63 changes: 29 additions & 34 deletions src/options/options.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,16 @@ describe('getOptions', () => {
});
});

it('reads options from remote config', async () => {
mockGithubConfigOptions({ hasRemoteConfig: true });
const options = await getOptions([], {});
expect(options.branchLabelMapping).toEqual({
'^v8.2.0$': 'option-from-remote',
});

expect(options.autoMergeMethod).toEqual('rebase');
});

it('should ensure that "backport" branch does not exist', async () => {
mockGithubConfigOptions({ hasBackportBranch: true });
await expect(getOptions([], {})).rejects.toThrowError(
Expand All @@ -158,12 +168,6 @@ describe('getOptions', () => {
mockGithubConfigOptions({
viewerLogin: 'john.diller',
defaultBranchRef: 'default-branch-from-github',
historicalMappings: [
{
committedDate: '2022-01-02T20:52:45.173Z',
branchLabelMapping: { foo: 'bar' },
},
],
});
const options = await getOptions([], {});

Expand All @@ -176,9 +180,6 @@ describe('getOptions', () => {
autoMerge: false,
autoMergeMethod: 'merge',
backportBinary: 'backport',
branchLabelMapping: {
foo: 'bar',
},
cherrypickRef: true,
ci: false,
commitPaths: [],
Expand All @@ -190,12 +191,6 @@ describe('getOptions', () => {
fork: true,
gitHostname: 'github.com',
githubApiBaseUrlV4: 'http://localhost/graphql',
historicalBranchLabelMappings: [
{
branchLabelMapping: { foo: 'bar' },
committedDate: '2022-01-02T20:52:45.173Z',
},
],
maxNumber: 10,
multipleBranches: true,
multipleCommits: false,
Expand Down Expand Up @@ -373,15 +368,12 @@ function mockGithubConfigOptions({
viewerLogin = 'DO_NOT_USE-sqren',
defaultBranchRef = 'DO_NOT_USE-default-branch-name',
hasBackportBranch,
historicalMappings = [],
hasRemoteConfig,
}: {
viewerLogin?: string;
defaultBranchRef?: string;
hasBackportBranch?: boolean;
historicalMappings?: Array<{
committedDate: string;
branchLabelMapping: Record<string, string>;
}>;
hasRemoteConfig?: boolean;
}) {
return mockGqlRequest<GithubConfigOptionsResponse>({
name: 'GithubConfigOptions',
Expand All @@ -396,23 +388,26 @@ function mockGithubConfigOptions({
defaultBranchRef: {
name: defaultBranchRef,
target: {
history: {
edges: historicalMappings.map(
({ committedDate, branchLabelMapping }) => {
return {
remoteConfig: {
committedDate,
file: {
object: {
text: JSON.stringify({
branchLabelMapping,
}),
remoteConfigHistory: {
edges: hasRemoteConfig
? [
{
remoteConfig: {
committedDate: '2020-08-15T00:00:00.000Z',
file: {
object: {
text: JSON.stringify({
autoMergeMethod: 'rebase',
branchLabelMapping: {
'^v8.2.0$': 'option-from-remote',
},
} as ConfigFileOptions),
},
},
},
},
};
}
),
]
: [],
},
},
},
Expand Down
1 change: 0 additions & 1 deletion src/runSequentially.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ describe('runSequentially', () => {
gitHostname: 'github.com',
githubApiBaseUrlV3: 'https://api.github.com',
githubApiBaseUrlV4: 'http://localhost/graphql', // Using localhost to avoid CORS issues when making requests (related to nock and jsdom)
historicalBranchLabelMappings: [],
mainline: undefined,
maxNumber: 10,
multipleBranches: false,
Expand Down
4 changes: 3 additions & 1 deletion src/services/HandledError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@ function getMessage(errorContext: ErrorContext | string): string {
export class HandledError extends Error {
errorContext?: ErrorContext;
constructor(errorContext: ErrorContext | string) {
super(getMessage(errorContext));
const message = getMessage(errorContext);
super(message);
Error.captureStackTrace(this, HandledError);
this.name = 'HandledError';
this.message = message;

if (typeof errorContext !== 'string') {
this.errorContext = errorContext;
Expand Down
9 changes: 5 additions & 4 deletions src/services/git.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { resolve as pathResolve } from 'path';
import { uniq, isEmpty } from 'lodash';
import ora from 'ora';
import { ValidConfigOptions } from '../options/options';
import { ora } from '../ui/ora';
import { filterNil } from '../utils/filterEmpty';
import { HandledError } from './HandledError';
import { execAsCallback, exec } from './child-process-promisified';
Expand Down Expand Up @@ -354,7 +354,7 @@ export async function setCommitAuthor(
options: ValidConfigOptions,
author: string
) {
const spinner = ora(`Changing author to "${author}"`).start();
const spinner = ora(options.ci, `Changing author to "${author}"`).start();
try {
const res = await exec(
`git commit --amend --no-edit --author "${author} <${author}@users.noreply.github.com>"`,
Expand All @@ -380,7 +380,7 @@ export async function createBackportBranch({
targetBranch: string;
backportBranch: string;
}) {
const spinner = ora('Pulling latest changes').start();
const spinner = ora(options.ci, 'Pulling latest changes').start();

try {
const res = await exec(
Expand Down Expand Up @@ -413,7 +413,7 @@ export async function deleteBackportBranch({
options: ValidConfigOptions;
backportBranch: string;
}) {
const spinner = ora().start();
const spinner = ora(options.ci).start();

await exec(
`git reset --hard && git checkout ${options.sourceBranch} && git branch -D ${backportBranch}`,
Expand All @@ -439,6 +439,7 @@ export async function pushBackportBranch({
}) {
const repoForkOwner = getRepoForkOwner(options);
const spinner = ora(
options.ci,
`Pushing branch "${repoForkOwner}:${backportBranch}"`
).start();

Expand Down
5 changes: 3 additions & 2 deletions src/services/github/v3/addAssigneesToPullRequest.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Octokit } from '@octokit/rest';
import ora from 'ora';
import { ValidConfigOptions } from '../../../options/options';
import { ora } from '../../../ui/ora';
import { logger } from '../../logger';

export async function addAssigneesToPullRequest(
Expand All @@ -10,6 +10,7 @@ export async function addAssigneesToPullRequest(
repoOwner,
accessToken,
autoAssign,
ci,
}: ValidConfigOptions,
pullNumber: number,
assignees: string[]
Expand All @@ -18,7 +19,7 @@ export async function addAssigneesToPullRequest(
? `Self-assigning to #${pullNumber}`
: `Adding assignees to #${pullNumber}: ${assignees.join(', ')}`;
logger.info(text);
const spinner = ora(text).start();
const spinner = ora(ci, text).start();

try {
const octokit = new Octokit({
Expand Down
12 changes: 9 additions & 3 deletions src/services/github/v3/addLabelsToPullRequest.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
import { Octokit } from '@octokit/rest';
import ora from 'ora';
import { ValidConfigOptions } from '../../../options/options';
import { ora } from '../../../ui/ora';
import { logger } from '../../logger';

export async function addLabelsToPullRequest(
{ githubApiBaseUrlV3, repoName, repoOwner, accessToken }: ValidConfigOptions,
{
githubApiBaseUrlV3,
repoName,
repoOwner,
accessToken,
ci,
}: ValidConfigOptions,
pullNumber: number,
labels: string[]
): Promise<void> {
const text = `Adding labels: ${labels.join(', ')}`;
logger.info(text);
const spinner = ora(text).start();
const spinner = ora(ci, text).start();

try {
const octokit = new Octokit({
Expand Down
12 changes: 9 additions & 3 deletions src/services/github/v3/addReviewersToPullRequest.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
import { Octokit } from '@octokit/rest';
import ora from 'ora';
import { ValidConfigOptions } from '../../../options/options';
import { ora } from '../../../ui/ora';
import { logger } from '../../logger';

export async function addReviewersToPullRequest(
{ githubApiBaseUrlV3, repoName, repoOwner, accessToken }: ValidConfigOptions,
{
githubApiBaseUrlV3,
repoName,
repoOwner,
accessToken,
ci,
}: ValidConfigOptions,
pullNumber: number,
reviewers: string[]
) {
const text = `Adding reviewers: ${reviewers}`;
logger.info(text);
const spinner = ora(text).start();
const spinner = ora(ci, text).start();

try {
const octokit = new Octokit({
Expand Down
4 changes: 2 additions & 2 deletions src/services/github/v3/createPullRequest.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Octokit } from '@octokit/rest';
import ora from 'ora';
import { ValidConfigOptions } from '../../../options/options';
import { ora } from '../../../ui/ora';
import { PACKAGE_VERSION } from '../../../utils/packageVersion';
import { HandledError } from '../../HandledError';
import { logger } from '../../logger';
Expand Down Expand Up @@ -35,7 +35,7 @@ export async function createPullRequest({
);

const { accessToken, githubApiBaseUrlV3 } = options;
const spinner = ora(`Creating pull request`).start();
const spinner = ora(options.ci, `Creating pull request`).start();

try {
const octokit = new Octokit({
Expand Down
3 changes: 2 additions & 1 deletion src/services/github/v4/FetchPullRequestId.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import gql from 'graphql-tag';
import { ValidConfigOptions } from '../../../options/options';
import { apiRequestV4 } from './apiRequestV4';

Expand All @@ -13,7 +14,7 @@ export async function fetchPullRequestId(
) {
const { accessToken, githubApiBaseUrlV4, repoName, repoOwner } = options;

const prQuery = /* GraphQL */ `
const prQuery = gql`
query PullRequestId(
$repoOwner: String!
$repoName: String!
Expand Down
Loading

0 comments on commit 831154d

Please sign in to comment.