Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(betterer 🐛): install typescript by default #520

Merged
merged 1 commit into from
Feb 22, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .betterer.results
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ exports[`no hack comments`] = {
"packages/cli/src/cli.ts:1074837834": [
[13, 0, 7, "RegExp match", "645651780"]
],
"packages/cli/src/init/update-package-json.ts:2842907794": [
"packages/cli/src/init/update-package-json.ts:887451963": [
[34, 4, 7, "RegExp match", "645651780"]
]
}`
Expand Down
20 changes: 10 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,16 +183,16 @@ betterer -c ./path/to/config -r ./path/to/results -w

#### Start options

| Name | Description | Default |
| ------------------------------ | --------------------------------------------------------------------------- | --------------------- |
| `-c`, `--config` [value] | Path to test definition file relative to CWD. Takes multiple values | `./.betterer.ts` |
| `-r`, `--results` [value] | Path to test results file relative to CWD | `./.betterer.results` |
| `-t`, `--tsconfig` [value] | Path to TypeScript config file relative to CWD | `null` |
| `-f`, `--filter` [value] | Select tests to run by RegExp. Takes multiple values | `[]` |
| `-s`, `--silent [true\|false]` | Disable all default reporters. Custom reporters still work normally | `false` |
| `-u`, `--update [true\|false]` | Force update the results file, even if things get worse | `false` |
| `--allow-update [true\|false]` | Allow updating via the `--update` flag | `true` |
| `-R`, `--reporter` [value] | npm package name or file path to a Betterer reporter. Takes multiple values | Default reporter |
| Name | Description | Default |
| -------------------------- | -------------------------------------------------------------------------------------------------- | --------------------- |
| `-c`, `--config` [value] | Path to test definition file relative to CWD. Takes multiple values | `./.betterer.ts` |
| `-r`, `--results` [value] | Path to test results file relative to CWD | `./.betterer.results` |
| `-t`, `--tsconfig` [value] | Path to TypeScript config file relative to CWD | `null` |
| `-f`, `--filter` [value] | Select tests to run by RegExp. Takes multiple values | `[]` |
| `-s`, `--silent` | When present, all default reporters will be disabled. Custom reporters will still work normally. | `false` |
| `-u`, `--update` | When present, the results file will be updated, even if things get worse | `false` |
| `--allow-update` | When set to false, the update message will not be shown and the `--update` option will be ignored. | `true` |
| `-R`, `--reporter` [value] | npm package name or file path to a Betterer reporter. Takes multiple values | Default reporter |

### CI

Expand Down
20 changes: 10 additions & 10 deletions packages/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,16 @@ betterer -c ./path/to/config -r ./path/to/results -w

#### Start options

| Name | Description | Default |
| ------------------------------ | --------------------------------------------------------------------------- | --------------------- |
| `-c`, `--config` [value] | Path to test definition file relative to CWD. Takes multiple values | `./.betterer.ts` |
| `-r`, `--results` [value] | Path to test results file relative to CWD | `./.betterer.results` |
| `-t`, `--tsconfig` [value] | Path to TypeScript config file relative to CWD | `null` |
| `-f`, `--filter` [value] | Select tests to run by RegExp. Takes multiple values | `[]` |
| `-s`, `--silent [true\|false]` | Disable all default reporters. Custom reporters still work normally | `false` |
| `-u`, `--update [true\|false]` | Force update the results file, even if things get worse | `false` |
| `--allow-update [true\|false]` | Allow updating via the `--update` flag | `true` |
| `-R`, `--reporter` [value] | npm package name or file path to a Betterer reporter. Takes multiple values | Default reporter |
| Name | Description | Default |
| -------------------------- | -------------------------------------------------------------------------------------------------- | --------------------- |
| `-c`, `--config` [value] | Path to test definition file relative to CWD. Takes multiple values | `./.betterer.ts` |
| `-r`, `--results` [value] | Path to test results file relative to CWD | `./.betterer.results` |
| `-t`, `--tsconfig` [value] | Path to TypeScript config file relative to CWD | `null` |
| `-f`, `--filter` [value] | Select tests to run by RegExp. Takes multiple values | `[]` |
| `-s`, `--silent` | When present, all default reporters will be disabled. Custom reporters will still work normally. | `false` |
| `-u`, `--update` | When present, the results file will be updated, even if things get worse | `false` |
| `--allow-update [false]` | When set to false, the update message will not be shown and the `--update` option will be ignored. | `true` |
| `-R`, `--reporter` [value] | npm package name or file path to a Betterer reporter. Takes multiple values | Default reporter |

### CI

Expand Down
13 changes: 11 additions & 2 deletions packages/cli/src/init.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@
import { render } from 'ink';
import React from 'react';

import { render } from 'ink';
import path from 'path';

import { Init } from './init/init';
import { initOptions } from './options';
import { BettererCLIArguments } from './types';

const BETTERER_TS = './.betterer.ts';
const TS_EXTENSION = '.ts';

/** @internal Definitely not stable! Please don't use! */
export async function initΔ(cwd: string, argv: BettererCLIArguments): Promise<void> {
const { config } = initOptions(argv);

const app = render(<Init config={config} cwd={cwd} />);
const finalConfig = config || BETTERER_TS;
const ext = path.extname(finalConfig);
const ts = ext === TS_EXTENSION;

const app = render(<Init config={finalConfig} cwd={cwd} ts={ts} />);
await app.waitUntilExit();
}
14 changes: 10 additions & 4 deletions packages/cli/src/init/create-test-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,16 @@ import { BettererError } from '@betterer/errors';
import { BettererLogger } from '@betterer/logger';
import { promises as fs } from 'fs';

const TEMPLATE = `export default {
const TEMPLATE_JS = `module.exports = {
// Add tests here ☀️
};`;
};
`;
const TEMPLATE_TS = `export default {
// Add tests here ☀️
};
`;

export async function run(logger: BettererLogger, configPath: string): Promise<void> {
export async function run(logger: BettererLogger, configPath: string, ts: boolean): Promise<void> {
await logger.progress(`creating "${configPath}" file...`);

let exists = false;
Expand All @@ -22,7 +27,8 @@ export async function run(logger: BettererLogger, configPath: string): Promise<v
}

try {
await fs.writeFile(configPath, TEMPLATE, 'utf8');
const template = ts ? TEMPLATE_TS : TEMPLATE_JS;
await fs.writeFile(configPath, template, 'utf8');
await logger.info(`created "${configPath}"!`);
} catch {
throw new BettererError(`could not read "${configPath}".`);
Expand Down
7 changes: 4 additions & 3 deletions packages/cli/src/init/init.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ const updatePackageJSON = workerRequire<WorkerModule<typeof import('./update-pac
export type InitProps = {
config: string;
cwd: string;
ts: boolean;
};

export const Init: FC<InitProps> = function Init({ cwd, config }) {
export const Init: FC<InitProps> = function Init({ cwd, config, ts }) {
return (
<BettererTasksLogger
name="Initialising Betterer"
Expand All @@ -20,14 +21,14 @@ export const Init: FC<InitProps> = function Init({ cwd, config }) {
{
name: 'Create test file',
run: async (logger) => {
await createTestFile.run(logger, path.resolve(cwd, config));
await createTestFile.run(logger, path.resolve(cwd, config), ts);
createTestFile.destroy();
}
},
{
name: 'Update package.json',
run: async (logger) => {
await updatePackageJSON.run(logger, cwd);
await updatePackageJSON.run(logger, cwd, ts);
updatePackageJSON.destroy();
}
}
Expand Down
11 changes: 10 additions & 1 deletion packages/cli/src/init/update-package-json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { promises as fs } from 'fs';

import { BettererPackageJSON } from '../types';

export async function run(logger: BettererLogger, cwd: string): Promise<void> {
export async function run(logger: BettererLogger, cwd: string, ts: boolean): Promise<void> {
await logger.progress('adding "betterer" to package.json file...');

let packageJSON;
Expand Down Expand Up @@ -41,6 +41,15 @@ export async function run(logger: BettererLogger, cwd: string): Promise<void> {
await logger.info('added "@betterer/cli" dependency to package.json file');
}

if (ts) {
if (packageJSON.devDependencies['typescript']) {
await logger.warn('"typescript" dependency already exists, moving on...');
} else {
packageJSON.devDependencies['typescript'] = `^4`;
await logger.info('added "typescript" dependency to package.json file');
}
}

try {
await fs.writeFile(packageJSONPath, `${JSON.stringify(packageJSON, null, 2)}\n`, 'utf-8');
} catch {
Expand Down
21 changes: 14 additions & 7 deletions packages/cli/src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ function setEnv<T extends BettererCLIEnvConfig>(argv: BettererCLIArguments): T {
}

function configPathOption(): void {
commander.option('-c, --config [value]', 'Path to test definition file relative to CWD', './.betterer.ts');
commander.option('-c, --config [value]', 'Path to test definition file relative to CWD');
}

function configPathsOption(): void {
Expand Down Expand Up @@ -98,20 +98,27 @@ function reportersOption(): void {
);
}

function handleBool(val: string) {
return val !== 'false';
function silentOption(): void {
commander.option(
'-s, --silent',
'When present, all default reporters will be disabled. Custom reporters will still work normally.'
);
}

function silentOption(): void {
commander.option('-s, --silent [true|false]', 'Disable all default reporters. Custom reporters still work normally.');
function defaultToTrue(val: string) {
return val !== 'false';
}

function allowUpdateOption(): void {
commander.option('--allow-update [true|false]', 'Whether to allow the `--update` option or not.', handleBool);
commander.option(
'--allow-update [true|false]',
'When set to false, the update message will not be shown and the `--update` option will be ignored.',
defaultToTrue
);
}

function updateOption(): void {
commander.option('-u, --update [true|false]', 'Force update the results file, even if things get worse', handleBool);
commander.option('-u, --update', 'When present, the results file will be updated, even if things get worse');
}

function argsToArray(value: string, previous: BettererCLIArguments = []): BettererCLIArguments {
Expand Down
15 changes: 15 additions & 0 deletions test/cli/__snapshots__/betterer-init.spec.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,19 @@ Array [
✅ Update package.json: done!
・ added \\"betterer\\" script to package.json file.
・ added \\"@betterer/cli\\" dependency to package.json file
・ added \\"typescript\\" dependency to package.json file
",
]
`;

exports[`betterer cli should initialise betterer in a repo with JS 1`] = `
Array [
"🎉 Initialising Betterer (0ms): 2 tasks done!
✅ Create test file: done!
・ created \\"<project>/fixtures/test-betterer-init-js/.betterer.js\\"!
✅ Update package.json: done!
・ added \\"betterer\\" script to package.json file.
・ added \\"@betterer/cli\\" dependency to package.json file
",
]
`;
Expand All @@ -20,13 +33,15 @@ Array [
✅ Update package.json: done!
・ added \\"betterer\\" script to package.json file.
・ added \\"@betterer/cli\\" dependency to package.json file
・ added \\"typescript\\" dependency to package.json file
",
"🎉 Initialising Betterer (0ms): 2 tasks done!
✅ Create test file: done!
・ \\"<project>/fixtures/test-betterer-init-multiple/.betterer.ts\\" already exists, moving on...
✅ Update package.json: done!
・ \\"betterer\\" script already exists, moving on...
・ \\"@betterer/cli\\" dependency already exists, moving on...
・ \\"typescript\\" dependency already exists, moving on...
",
]
`;
46 changes: 42 additions & 4 deletions test/cli/betterer-init.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import { BettererPackageJSON, initΔ } from '@betterer/cli';

import { createFixture } from '../fixture';

const ARGV = ['node', './bin/betterer'];
const ARGV = ['node', './bin/betterer', 'init'];

describe('betterer cli', () => {
it('should initialise betterer in a repo', async () => {
const { logs, paths, readFile, cleanup, resolve } = await createFixture(
const { cleanup, logs, paths, readFile, resolve } = await createFixture(
'test-betterer-init',
{
'package.json': `
Expand All @@ -31,18 +31,19 @@ describe('betterer cli', () => {

expect(packageJSON.scripts.betterer).toEqual('betterer');
expect(packageJSON.devDependencies['@betterer/cli']).toBeDefined();
expect(packageJSON.devDependencies['typescript']).toBeDefined();

const config = await readFile(configPath);

expect(config).toEqual('export default {\n // Add tests here ☀️\n};');
expect(config).toEqual('export default {\n // Add tests here ☀️\n};\n');

expect(logs).toMatchSnapshot();

await cleanup();
});

it('should work multiple times', async () => {
const { logs, paths, cleanup } = await createFixture(
const { cleanup, logs, paths } = await createFixture(
'test-betterer-init-multiple',
{
'package.json': `
Expand Down Expand Up @@ -72,4 +73,41 @@ describe('betterer cli', () => {

expect(logs).toMatchSnapshot();
});

it('should initialise betterer in a repo with JS', async () => {
const { cleanup, logs, paths, readFile, resolve } = await createFixture(
'test-betterer-init-js',
{
'package.json': `
{
"name": "betterer-test-betterer-init-js",
"version": "0.0.1"
}
`
},
{
logFilters: [/🌟 Initialising Betterer/]
}
);

const configPath = `${paths.config}.js`;
const fixturePath = paths.cwd;
const packageJSONPath = resolve('./package.json');

await initΔ(fixturePath, [...ARGV, '--config', configPath]);

const packageJSON = JSON.parse(await readFile(packageJSONPath)) as BettererPackageJSON;

expect(packageJSON.scripts.betterer).toEqual('betterer');
expect(packageJSON.devDependencies['@betterer/cli']).toBeDefined();
expect(packageJSON.devDependencies['typescript']).not.toBeDefined();

const config = await readFile(configPath);

expect(config).toEqual('module.exports = {\n // Add tests here ☀️\n};\n');

expect(logs).toMatchSnapshot();

await cleanup();
});
});