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

Standardize flags #424

Merged
merged 1 commit into from
May 19, 2020
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
12 changes: 5 additions & 7 deletions packages/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,15 +58,13 @@ ARGUMENTS
PATHS The paths that checkup will operate on. If no paths are provided, checkup will run on the entire directory beginning at --cwd

OPTIONS
-c, --config=config Use this configuration, overriding .checkuprc.* if present
-f, --force
-h, --help show CLI help
-o, --reportOutputPath=reportOutputPath [default: .]
-d, --cwd=cwd [default: .] [defaultL .] The path referring to the root directory that Checkup will run in
-r, --reporter=stdout|json|pdf [default: stdout]
-s, --silent
-t, --task=task
-v, --version show CLI version
-c, --config=config Use this configuration, overriding .checkuprc.* if present
-d, --cwd=cwd [default: .] [default: .] The path referring to the root directory that Checkup will run in
-t, --task=task
-f, --format=stdout|json|html [default: stdout]
-o, --outputFile=outputFile [default: .]
```

_See code: [src/commands/run.ts](https://github.com/checkupjs/checkup/blob/v0.0.0/src/commands/run.ts)_
Expand Down
21 changes: 10 additions & 11 deletions packages/cli/__tests__/commands/run-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as path from 'path';

import { CheckupProject, createTmpDir, stdout } from '@checkup/test-helpers';

import { join } from 'path';
import { runCommand } from '../__utils__/run-command';

const TEST_TIMEOUT = 100000;
Expand Down Expand Up @@ -41,20 +42,20 @@ describe('@checkup/cli', () => {
);

it('should output checkup result in JSON', async () => {
await runCommand(['run', '--reporter', 'json', '--cwd', project.baseDir]);
await runCommand(['run', '--format', 'json', '--cwd', project.baseDir]);

expect(stdout()).toMatchSnapshot();
});

it(
'should output an html file in the current directory if the html reporter option is provided',
'should output an html file in the current directory if the html format option is provided',
async () => {
await runCommand(['run', '--reporter', 'html', '--cwd', project.baseDir]);
await runCommand(['run', '--format', 'html', '--cwd', project.baseDir]);

let outputPath = stdout().trim();

expect(outputPath).toMatch(
/^(.*)\/checkup-report-(\d{4})-(\d{2})-(\d{2})-(\d{2})-(\d{2})-(\d{2})\.html/
/^(.*)\/checkup-report-(\d{4})-(\d{2})-(\d{2})-(\d{2})_(\d{2})_(\d{2})\.html/
);
expect(fs.existsSync(outputPath)).toEqual(true);

Expand All @@ -64,25 +65,23 @@ describe('@checkup/cli', () => {
);

it(
'should output an html file in a custom directory if the html reporter and reporterOutputPath options are provided',
'should output an html file in a custom directory if the html format and outputFile options are provided',
async () => {
let tmp = createTmpDir();

await runCommand([
'run',
'--reporter',
'--format',
'html',
`--reportOutputPath`,
tmp,
`--outputFile`,
join(tmp, 'my-checkup-file.html'),
'--cwd',
project.baseDir,
]);

let outputPath = stdout().trim();

expect(outputPath).toMatch(
/^(.*)\/checkup-report-(\d{4})-(\d{2})-(\d{2})-(\d{2})-(\d{2})-(\d{2})\.html/
);
expect(outputPath).toMatch(/^(.*)\/my-checkup-file.html/);
expect(fs.existsSync(outputPath)).toEqual(true);

fs.unlinkSync(outputPath);
Expand Down
44 changes: 41 additions & 3 deletions packages/cli/__tests__/reporters-test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import { Category, Priority, TaskResult } from '@checkup/core';
import { Category, OutputFormat, Priority, TaskResult } from '@checkup/core';
import {
DEFAULT_OUTPUT_FILENAME,
_transformHTMLResults,
_transformJsonResults,
getOutputPath,
} from '../src/reporters';

import { MetaTaskResult } from '../src/types';
import MockMetaTaskResult from './__utils__/mock-meta-task-result';
import MockTaskResult from './__utils__/mock-task-result';
import MockPieChartTaskResult from './__utils__/mock-pie-chart-task-result';
import { _transformJsonResults, _transformHTMLResults } from '../src/reporters';
import MockTaskResult from './__utils__/mock-task-result';
import { join } from 'path';

let metaTaskResults: MetaTaskResult[];
let pluginTaskResults: TaskResult[];
Expand Down Expand Up @@ -255,3 +261,35 @@ describe('_transformHTMLResults', () => {
expect(transformed).toMatchSnapshot();
});
});

describe('getOutputPath', () => {
it('throws if output format is stdout', () => {
expect(() => {
getOutputPath(OutputFormat.stdout, '');
}).toThrow('The `stdout` format cannot be used to generate an output file path');
});

[OutputFormat.json, OutputFormat.html].forEach((format) => {
it(`returns same path when absolute path provided for ${format}`, () => {
expect(getOutputPath(format, `/some-file.${format}`)).toEqual(`/some-file.${format}`);
});

it(`returns resolved path when path provided for ${format}`, () => {
expect(getOutputPath(format, `some-file.${format}`, __dirname)).toEqual(
join(__dirname, `some-file.${format}`)
);
});

it(`returns default file format if no outputFile provided for ${format}`, () => {
expect(getOutputPath(format, '', __dirname)).toEqual(
join(__dirname, `${DEFAULT_OUTPUT_FILENAME}.${format}`)
);
});

it(`returns default output path format if {default} token provided for ${format}`, () => {
expect(getOutputPath(format, `{default}.${format}`, __dirname)).toEqual(
join(__dirname, `${DEFAULT_OUTPUT_FILENAME}.${format}`)
);
});
});
});
33 changes: 17 additions & 16 deletions packages/cli/src/commands/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import * as path from 'path';
import {
CheckupConfig,
CheckupConfigService,
ReporterType,
OutputFormat,
RunArgs,
RunFlags,
TaskContext,
Expand All @@ -24,8 +24,8 @@ import { MetaTaskResult } from '../types';
import OutdatedDependenciesTask from '../tasks/outdated-dependencies-task';
import ProjectMetaTask from '../tasks/project-meta-task';
import TaskList from '../task-list';
import { getReporter } from '../reporters';
import TodosTask from '../tasks/todos-task';
import { getReporter } from '../reporters';

export default class RunCommand extends Command {
static description = 'Provides health check information about your project';
Expand All @@ -41,28 +41,29 @@ export default class RunCommand extends Command {
];

static flags = {
version: flags.version({ char: 'v' }),
help: flags.help({ char: 'h' }),
config: flags.string({
char: 'c',
description: 'Use this configuration, overriding .checkuprc.* if present',
}),
cwd: flags.string({
default: '.',
char: 'd',
description: 'The path referring to the root directory that Checkup will run in',
}),
version: flags.version({ char: 'v' }),
help: flags.help({ char: 'h' }),
force: flags.boolean({ char: 'f' }),
silent: flags.boolean({ char: 's' }),
reporter: flags.string({
char: 'r',
options: [...Object.values(ReporterType)],

task: flags.string({ char: 't' }),
format: flags.string({
char: 'f',
options: [...Object.values(OutputFormat)],
default: 'stdout',
description: `The output format, one of ${[...Object.values(OutputFormat)].join(', ')}`,
}),
reportOutputPath: flags.string({
outputFile: flags.string({
char: 'o',
default: '.',
}),
task: flags.string({ char: 't' }),
config: flags.string({
char: 'c',
description: 'Use this configuration, overriding .checkuprc.* if present',
default: '',
description: 'Specify file to write report to',
}),
};

Expand Down
15 changes: 4 additions & 11 deletions packages/cli/src/helpers/ui-report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import * as Handlebars from 'handlebars';
import * as fs from 'fs';
import * as path from 'path';

import { readFileSync } from 'fs-extra';
import { ReportComponentType, UIReportData } from '@checkup/core';

import { pathToFileURL } from 'url';
import { printToPDF } from './print-to-pdf';
import { readFileSync } from 'fs-extra';

import tmp = require('tmp');

Expand All @@ -19,17 +20,9 @@ export async function generateHTMLReport(
): Promise<string> {
let reportHTML = generateHTML(resultsForPdf);

if (!fs.existsSync(resultOutputPath)) {
fs.mkdirSync(resultOutputPath, { recursive: true });
}

let htmlPath = path.join(
resultOutputPath,
`checkup-report-${date.format(new Date(), 'YYYY-MM-DD-HH-mm-ss')}.html`
);
fs.writeFileSync(htmlPath, reportHTML);
fs.writeFileSync(resultOutputPath, reportHTML);

return path.resolve(htmlPath);
return resultOutputPath;
}

export async function generatePDFReport(
Expand Down
70 changes: 53 additions & 17 deletions packages/cli/src/reporters.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
import {
Category,
OutputFormat,
Priority,
ReportComponentType,
ReporterType,
RunFlags,
TaskResult,
UIReportData,
UIResultData,
ui,
} from '@checkup/core';
import { MetaTaskResult, OutputPosition } from './types';
import { dirname, isAbsolute, resolve } from 'path';
import { existsSync, mkdirpSync, writeJsonSync } from 'fs-extra';

import { generateHTMLReport } from './helpers/ui-report';

const date = require('date-and-time');

export const TODAY = date.format(new Date(), 'YYYY-MM-DD-HH_mm_ss');
export const DEFAULT_OUTPUT_FILENAME = `checkup-report-${TODAY}`;

export function _transformHTMLResults(
metaTaskResults: MetaTaskResult[],
pluginTaskResults: TaskResult[]
Expand Down Expand Up @@ -69,33 +76,62 @@ export function _transformJsonResults(
return transformedResult;
}

export function getOutputPath(format: OutputFormat, outputFile: string, cwd: string = '') {
if (format === OutputFormat.stdout) {
throw new Error('The `stdout` format cannot be used to generate an output file path');
}

if (/{default}/.test(outputFile)) {
outputFile = outputFile.replace('{default}', DEFAULT_OUTPUT_FILENAME);
}

let outputPath = isAbsolute(outputFile)
? outputFile
: resolve(cwd, outputFile || `${DEFAULT_OUTPUT_FILENAME}.${format}`);

let dir = dirname(outputPath);

if (!existsSync(dir)) {
mkdirpSync(dir);
}

return outputPath;
}

export function getReporter(
flags: RunFlags,
metaTaskResults: MetaTaskResult[],
pluginTaskResults: TaskResult[]
) {
switch (flags.reporter) {
case ReporterType.stdout:
switch (flags.format) {
case OutputFormat.stdout:
return async () => {
if (!flags.silent) {
metaTaskResults
.filter((taskResult) => taskResult.outputPosition === OutputPosition.Header)
.forEach((taskResult) => taskResult.toConsole());
pluginTaskResults.forEach((taskResult) => taskResult.toConsole());
metaTaskResults
.filter((taskResult) => taskResult.outputPosition === OutputPosition.Footer)
.forEach((taskResult) => taskResult.toConsole());
}
metaTaskResults
.filter((taskResult) => taskResult.outputPosition === OutputPosition.Header)
.forEach((taskResult) => taskResult.toConsole());
pluginTaskResults.forEach((taskResult) => taskResult.toConsole());
metaTaskResults
.filter((taskResult) => taskResult.outputPosition === OutputPosition.Footer)
.forEach((taskResult) => taskResult.toConsole());
};
case ReporterType.json:
case OutputFormat.json:
return async () => {
let resultJson = _transformJsonResults(metaTaskResults, pluginTaskResults);
ui.styledJSON(resultJson);

if (flags.outputFile) {
let outputPath = getOutputPath(OutputFormat.json, flags.outputFile, flags.cwd);
writeJsonSync(outputPath, resultJson);
} else {
ui.styledJSON(resultJson);
}
};
case ReporterType.html:
case OutputFormat.html:
return async () => {
let resultsForPdf = _transformHTMLResults(metaTaskResults, pluginTaskResults);
let reportPath = await generateHTMLReport(flags.reportOutputPath, resultsForPdf);
let resultsForHtml = _transformHTMLResults(metaTaskResults, pluginTaskResults);
let reportPath = await generateHTMLReport(
getOutputPath(OutputFormat.html, flags.outputFile, flags.cwd),
resultsForHtml
);

ui.log(reportPath);
};
Expand Down
8 changes: 3 additions & 5 deletions packages/core/__tests__/base-task-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,11 @@ import { getRegisteredParsers } from '../src/parsers/registered-parsers';
const DEFAULT_FLAGS = {
version: undefined,
help: undefined,
force: false,
silent: false,
reporter: 'stdout',
reportOutputPath: '.',
config: undefined,
cwd: '.',
task: undefined,
config: undefined,
format: 'stdout',
outputFile: '',
};

const DEFAULT_CONFIG = {
Expand Down
8 changes: 3 additions & 5 deletions packages/core/src/types/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,9 @@ export type RunArgs = {
export type RunFlags = {
version: void;
help: void;
force: boolean;
silent: boolean;
reporter: string;
reportOutputPath: string;
config: string | undefined;
cwd: string;
task: string | undefined;
config: string | undefined;
format: string;
outputFile: string;
};
2 changes: 1 addition & 1 deletion packages/core/src/types/tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ export const enum Grade {
F = 'F',
}

export enum ReporterType {
export enum OutputFormat {
stdout = 'stdout',
json = 'json',
html = 'html',
Expand Down
Loading