Skip to content

Commit

Permalink
fix “Initializing” spinner, improve logging and add yargs test (#177)
Browse files Browse the repository at this point in the history
  • Loading branch information
sorenlouv authored Apr 12, 2020
1 parent db70e88 commit d19f526
Show file tree
Hide file tree
Showing 21 changed files with 797 additions and 106 deletions.
7 changes: 5 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,12 @@ node_js:
cache: yarn
before_script:
- yarn
- git config --global user.email "[email protected]"
- git config --global user.name "Travis Backport"
script:
- yarn lint
- yarn cover
- yarn tsc
- yarn lint # lint ts and eslint
- yarn jest --coverage # run tests and publish coverage
after_success:
- npm install -g coveralls
- cat coverage/lcov.info | coveralls
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module.exports = {
snapshotSerializers: ['jest-snapshot-serializer-ansi'],
setupFiles: ['./src/test/automatic-mocks.ts'],
setupFiles: ['./src/test/setupFiles/automatic-mocks.ts'],
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,12 @@
},
"license": "MIT",
"scripts": {
"cover": "jest --coverage",
"format": "prettier \"./{src,test}/**/*.ts\" --write",
"format": "prettier \"./{src,test}/**/*.{ts,js,json}\" --write",
"lint": "tsc --project ./src/test/tsconfig.json && eslint './**/*.{ts,js}'",
"postinstall": "test -f ./dist/scripts/runPostinstall.js && node ./dist/scripts/runPostinstall.js || echo 'Dist folder missing'",
"prepublishOnly": "tsc",
"publish-dry-run": "tar -tf $(npm pack)",
"test": "jest --config ./jest.config.js",
"test": "jest",
"start": "ts-node --transpile-only ./src/index.ts"
},
"lint-staged": {
Expand Down Expand Up @@ -104,6 +103,7 @@
"lint-staged": "^10.1.2",
"lodash": "^4.17.15",
"prettier": "^2.0.4",
"strip-ansi": "^6.0.0",
"ts-jest": "^25.3.1",
"ts-node": "^8.8.2",
"typescript": "^3.8.3"
Expand Down
8 changes: 4 additions & 4 deletions src/options/config/globalConfig.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import makeDir from 'make-dir';
import * as fs from '../../services/fs-promisified';
import { PromiseReturnType } from '../../types/PromiseReturnType';
import { getGlobalConfig, maybeCreateGlobalConfig } from './globalConfig';
import { getGlobalConfig, createGlobalConfigIfNotExist } from './globalConfig';

describe('config', () => {
afterEach(() => jest.clearAllMocks());
Expand Down Expand Up @@ -49,10 +49,10 @@ describe('config', () => {
});
});

describe('maybeCreateGlobalConfig', () => {
describe('createGlobalConfigIfNotExist', () => {
it('should create config and succeed', async () => {
jest.spyOn(fs, 'writeFile').mockResolvedValueOnce(undefined);
const didCreate = await maybeCreateGlobalConfig(
const didCreate = await createGlobalConfigIfNotExist(
'/path/to/globalConfig',
'myConfigTemplate'
);
Expand All @@ -71,7 +71,7 @@ describe('config', () => {
(err as any).code = 'EEXIST';
jest.spyOn(fs, 'writeFile').mockRejectedValueOnce(err);

const didCreate = await maybeCreateGlobalConfig(
const didCreate = await createGlobalConfigIfNotExist(
'myPath',
'myConfigTemplate'
);
Expand Down
8 changes: 4 additions & 4 deletions src/options/config/globalConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@ import { chmod, writeFile } from '../../services/fs-promisified';
import { readConfigFile } from './readConfigFile';

export async function getGlobalConfig() {
await maybeCreateGlobalConfigAndFolder();
await createGlobalConfigAndFolderIfNotExist();
const globalConfigPath = getGlobalConfigPath();
return readConfigFile(globalConfigPath);
}

export async function maybeCreateGlobalConfigAndFolder() {
export async function createGlobalConfigAndFolderIfNotExist() {
const reposPath = getReposPath();
const globalConfigPath = getGlobalConfigPath();
const configTemplate = await getConfigTemplate();
await makeDir(reposPath);
const didCreate = await maybeCreateGlobalConfig(
const didCreate = await createGlobalConfigIfNotExist(
globalConfigPath,
configTemplate
);
Expand All @@ -26,7 +26,7 @@ function ensureCorrectPermissions(globalConfigPath: string) {
return chmod(globalConfigPath, '600');
}

export async function maybeCreateGlobalConfig(
export async function createGlobalConfigIfNotExist(
globalConfigPath: string,
configTemplate: string
) {
Expand Down
5 changes: 0 additions & 5 deletions src/runWithArgs.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import chalk from 'chalk';
import ora from 'ora';
import { getOptions } from './options/options';
import { runWithOptions } from './runWithOptions';
import { HandledError } from './services/HandledError';
Expand All @@ -9,14 +8,10 @@ import { initLogger, consoleLog } from './services/logger';
export async function runWithArgs(args: string[]) {
const logger = initLogger();

const spinner = ora().start('Initializing');
try {
const options = await getOptions(args);
spinner.stop();
await runWithOptions(options);
} catch (e) {
spinner.stop();

if (e instanceof HandledError) {
consoleLog(e.message);
} else {
Expand Down
12 changes: 6 additions & 6 deletions src/scripts/postinstall.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,25 @@ describe('postinstall', () => {
});

it("should create global config if it doesn't exist", async () => {
const maybeCreateGlobalConfigAndFolderSpy = jest
.spyOn(globalConfig, 'maybeCreateGlobalConfigAndFolder')
const createGlobalConfigAndFolderIfNotExistSpy = jest
.spyOn(globalConfig, 'createGlobalConfigAndFolderIfNotExist')
.mockResolvedValueOnce(true);

await postinstall();
expect(maybeCreateGlobalConfigAndFolderSpy).toBeCalledTimes(1);
expect(createGlobalConfigAndFolderIfNotExistSpy).toBeCalledTimes(1);
expect(logger.consoleLog).toBeCalledWith(
'Global config successfully created in /myHomeDir/.backport/config.json'
);
});

it('should not create global config if it already exists', async () => {
const consoleSpy = jest.spyOn(console, 'log');
const maybeCreateGlobalConfigAndFolderSpy = jest
.spyOn(globalConfig, 'maybeCreateGlobalConfigAndFolder')
const createGlobalConfigAndFolderIfNotExistSpy = jest
.spyOn(globalConfig, 'createGlobalConfigAndFolderIfNotExist')
.mockResolvedValueOnce(false);

await postinstall();
expect(maybeCreateGlobalConfigAndFolderSpy).toBeCalledTimes(1);
expect(createGlobalConfigAndFolderIfNotExistSpy).toBeCalledTimes(1);
expect(consoleSpy).toBeCalledTimes(0);
});
});
4 changes: 2 additions & 2 deletions src/scripts/postinstall.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { maybeCreateGlobalConfigAndFolder } from '../options/config/globalConfig';
import { createGlobalConfigAndFolderIfNotExist } from '../options/config/globalConfig';
import { getGlobalConfigPath } from '../services/env';
import { consoleLog } from '../services/logger';

export async function postinstall() {
try {
const didCreate = await maybeCreateGlobalConfigAndFolder();
const didCreate = await createGlobalConfigAndFolderIfNotExist();
if (didCreate) {
const GLOBAL_CONFIG_PATH = getGlobalConfigPath();
consoleLog(`Global config successfully created in ${GLOBAL_CONFIG_PATH}`);
Expand Down
2 changes: 1 addition & 1 deletion src/services/github/v3/apiRequestV3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export async function apiRequestV3<T>(config: AxiosRequestConfig) {
e.response?.status
})`
);
logger.info('Response headers:', e.response?.headers);
logger.debug('Response headers:', e.response?.headers);
logger.info('Response data:', e.response?.data);

throw handleGithubV3Error(e);
Expand Down
6 changes: 3 additions & 3 deletions src/services/github/v4/apiRequestV4.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,15 +54,15 @@ export async function apiRequestV4<DataResponse>({
logger.verbose('Query:', query);
logger.verbose('Variables:', variables);
logger.debug('Response headers:', response.headers);
logger.verbose('Response data', response.data);
logger.verbose('Response data:', response.data);

return response.data.data;
} catch (e) {
logger.info(`POST ${githubApiBaseUrlV4} (status: ${e.response?.status})`);
logger.info('Query:', query);
logger.info('Variables:', variables);
logger.info('Response headers:', e.response?.headers);
logger.info('Response data', e.response?.data);
logger.debug('Response headers:', e.response?.headers);
logger.info('Response data:', e.response?.data);

if (handleError) {
throw handleGithubV4Error(e);
Expand Down
31 changes: 17 additions & 14 deletions src/services/github/v4/fetchCommitsByAuthor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,11 +125,13 @@ export async function fetchCommitsByAuthor(
const commitMessage = edge.node.message;
const sha = edge.node.oid;

const associatedPullRequest = getAssociatedPullRequest(
const associatedPullRequest = isAssociatedPullRequest({
pullRequestEdge,
options,
sha
);
sha,
})
? pullRequestEdge
: undefined;

const existingBackports = getExistingBackportPRs(
commitMessage,
Expand Down Expand Up @@ -163,19 +165,20 @@ function getPullNumberFromMessage(firstMessageLine: string) {
}
}

function getAssociatedPullRequest(
pullRequestEdge: PullRequestEdge | undefined,
options: BackportOptions,
sha: string
) {
const isAssociated =
function isAssociatedPullRequest({
pullRequestEdge,
options,
sha,
}: {
pullRequestEdge: PullRequestEdge | undefined;
options: BackportOptions;
sha: string;
}) {
return (
pullRequestEdge?.node.repository.name === options.repoName &&
pullRequestEdge?.node.repository.owner.login === options.repoOwner &&
pullRequestEdge?.node.mergeCommit.oid === sha;

if (isAssociated) {
return pullRequestEdge;
}
pullRequestEdge?.node.mergeCommit.oid === sha
);
}

export function getExistingBackportPRs(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { AxiosError } from 'axios';
import ora from 'ora';
import { validateRequiredOptions } from '../../../options/options';
import { HandledError } from '../../HandledError';
import {
Expand Down Expand Up @@ -41,6 +42,7 @@ export async function getDefaultRepoBranchAndPerformStartupChecks({
`;

let res: DataResponse;
const spinner = ora().start('Initializing...');
try {
res = await apiRequestV4<DataResponse>({
githubApiBaseUrlV4,
Expand All @@ -52,16 +54,17 @@ export async function getDefaultRepoBranchAndPerformStartupChecks({
},
handleError: false,
});
spinner.stop();
} catch (e) {
spinner.stop();
const error = e as AxiosError<GithubV4Response<null>>;

if (error.response) {
throwOnInvalidAccessToken({
errorResponse: error.response,
repoName,
repoOwner,
});
}
throwOnInvalidAccessToken({
error,
repoName,
repoOwner,
});

throw handleGithubV4Error(error);
}

Expand Down
Loading

0 comments on commit d19f526

Please sign in to comment.