remove pretty printing from CLI

This commit is contained in:
Brendan Kenny 2017-03-07 17:36:38 -08:00 коммит произвёл Brendan Kenny
Родитель fe88c4ab83
Коммит 47eb040a68
4 изменённых файлов: 39 добавлений и 114 удалений

Просмотреть файл

@ -94,8 +94,11 @@ const cliFlags = yargs
'view'
], 'Output:')
.describe({
'output': 'Reporter for the results, supports multiple values',
'output-path': `The file path to output the results
'output': `Reporter for the results, supports multiple values`,
'output-path': `The file path to output the results. Use 'stdout' to write to stdout.
If using JSON output, default is stdout.
If using HTML output, default is a file in the working directory with a name based on the test URL and date.
If using multiple outputs, --output-path is ignored.
Example: --output-path=./lighthouse-results.html`,
'view': 'Open HTML report in your browser'
})
@ -124,8 +127,7 @@ Example: --output-path=./lighthouse-results.html`,
// default values
.default('chrome-flags', '')
.default('disable-cpu-throttling', true)
.default('output', Printer.GetValidOutputOptions()[Printer.OutputMode.none])
.default('output-path', 'stdout')
.default('output', Printer.GetValidOutputOptions()[Printer.OutputMode.html])
.default('port', 9222)
.default('max-wait-for-load', Driver.MAX_WAIT_FOR_FULLY_LOADED)
.check((argv: {listAllAudits?: boolean, listTraceCategories?: boolean, _: Array<any>}) => {
@ -169,6 +171,10 @@ if (cliFlags.verbose) {
}
log.setLevel(cliFlags.logLevel);
if (cliFlags.output === Printer.OutputMode[Printer.OutputMode.json] && !cliFlags.outputPath) {
cliFlags.outputPath = 'stdout';
}
/**
* If the requested port is 0, set it to a random, unused port.
*/
@ -278,17 +284,6 @@ function saveResults(results: Results,
promise = promise.then(_ => assetSaver.saveAssets(artifacts, results.audits, resolvedPath));
}
if (flags.output === Printer.OutputMode[Printer.OutputMode.none]) {
promise = promise
.then(_ => Printer.write(results, 'html', `${resolvedPath}.report.html`))
.then(_ => {
if (flags.view) return opn(`${resolvedPath}.report.html`, {wait: false});
log.warn('CLI', 'Report output no longer defaults to stdout. Use `--output=pretty` to re-enable.');
log.log('CLI', 'Protip: Run lighthouse with `--view` to immediately open the HTML report in your browser');
});
}
return promise.then(_ => {
if (Array.isArray(flags.output)) {
return flags.output.reduce((innerPromise, outputType) => {
@ -296,7 +291,18 @@ function saveResults(results: Results,
return innerPromise.then((_: Results) => Printer.write(results, outputType, outputPath));
}, Promise.resolve(results));
} else {
return Printer.write(results, flags.output, flags.outputPath);
const outputPath = flags.outputPath || `${resolvedPath}.report.${flags.output}`;
return Printer.write(results, flags.output, outputPath).then(results => {
if (flags.output === Printer.OutputMode[Printer.OutputMode.html]) {
if (flags.view) {
opn(`${resolvedPath}.report.html`, {wait: false});
} else {
log.log('CLI', 'Protip: Run lighthouse with `--view` to immediately open the HTML report in your browser');
}
}
return results;
});
}
});
}

Просмотреть файл

@ -19,12 +19,11 @@
/**
* An enumeration of acceptable output modes:
* 'pretty': Pretty print the results
* 'json': JSON formatted results
* 'html': An HTML report
*/
enum OutputMode { pretty, json, html, none };
type Mode = 'pretty' | 'json' | 'html' | 'none';
enum OutputMode { json, html };
type Mode = 'json' | 'html';
import {Results, AuditResult} from './types/types';
@ -46,24 +45,6 @@ function checkOutputPath(path: string): string {
return path;
}
function formatAggregationResultItem(score: boolean | number | string, suffix = '') {
if (typeof score === 'boolean') {
return score ? `${log.greenify(log.tick)}` : `${log.redify(log.cross)}`;
}
if (typeof score !== 'number') {
return `${log.purple}${score}${log.reset}`;
}
let colorChoice = log.red;
if (score > 45) {
colorChoice = log.yellow;
}
if (score > 75) {
colorChoice = log.green;
}
return `${colorChoice}${score}${suffix}${log.reset}`;
}
/**
* Creates the results output in a format based on the `mode`.
*/
@ -80,56 +61,7 @@ function createOutput(results: Results, outputMode: OutputMode): string {
return JSON.stringify(results, null, 2);
}
// No report (the new default)
if (outputMode === OutputMode.none) return '';
// Pretty printed CLI report.
const version = results.lighthouseVersion;
let output = `\n\n${log.bold}Lighthouse (${version}) results:${log.reset} ${results.url}\n\n`;
results.aggregations.forEach(aggregation => {
const total = aggregation.total ? ': ' + formatAggregationResultItem(Math.round(aggregation.total * 100), '%') : '';
output += `${log.whiteSmallSquare} ${log.bold}${aggregation.name}${log.reset}${total}\n\n`;
aggregation.score.forEach(item => {
const score = (item.overall * 100).toFixed(0);
if (item.name) {
output += `${log.bold}${item.name}${log.reset}: ${item.scored ? formatAggregationResultItem(score, '%') : ''}\n`;
}
item.subItems.forEach(subitem => {
let auditResult: AuditResult;
if (typeof subitem === 'string') {
auditResult = (<any>results).audits[subitem];
} else {
auditResult = subitem as AuditResult;
}
const formattedScore = auditResult.error ? `${log.redify('‽')}` :
`${formatAggregationResultItem(auditResult.score)}`;
let lineItem = ` ${log.doubleLightHorizontal} ${formattedScore} ${auditResult.description}`;
if (auditResult.displayValue) {
lineItem += ` (${log.bold}${auditResult.displayValue}${log.reset})`;
}
output += `${lineItem}\n`;
if (auditResult.debugString) {
output += ` ${auditResult.debugString}\n`;
}
if (auditResult.extendedInfo && auditResult.extendedInfo.value) {
const formatter =
Formatter.getByName(auditResult.extendedInfo.formatter).getFormatter('pretty');
output += `${formatter(auditResult.extendedInfo.value)}`;
}
});
output += '\n';
});
});
return output;
throw new Error('Invalid output mode: ' + outputMode);
}
/* istanbul ignore next */
@ -185,10 +117,8 @@ function write(results: Results, mode: Mode, path: string): Promise<Results> {
}
function GetValidOutputOptions():Array<Mode> {
return [OutputMode[OutputMode.pretty] as Mode,
OutputMode[OutputMode.json] as Mode,
OutputMode[OutputMode.html] as Mode,
OutputMode[OutputMode.none] as Mode];
return [OutputMode[OutputMode.json] as Mode,
OutputMode[OutputMode.html] as Mode];
}
export {

Просмотреть файл

@ -23,7 +23,6 @@ const Printer = require('../../printer.js');
const assert = require('assert');
const fs = require('fs');
const sampleResults = require('../../../lighthouse-core/test/results/sample.json');
const log = require('../../../lighthouse-core/lib/log');
describe('Printer', () => {
it('accepts valid output paths', () => {
@ -42,20 +41,6 @@ describe('Printer', () => {
assert.doesNotThrow(_ => JSON.parse(jsonOutput));
});
it('creates Pretty Printed results', () => {
const mode = Printer.OutputMode.pretty;
const prettyOutput = Printer.createOutput(sampleResults, mode);
// Just check there's no HTML / JSON there.
assert.throws(_ => JSON.parse(prettyOutput));
assert.equal(/<!doctype/gim.test(prettyOutput), false);
const hasScoreOnNonScoredItem = /Using modern offline features.*?(0%|NaN)/.test(prettyOutput);
const hasAggregationPresent = prettyOutput.includes('Using modern offline features');
assert.equal(hasScoreOnNonScoredItem, false, 'non-scored item was scored');
assert.equal(hasAggregationPresent, true, 'non-scored aggregation item is not there');
});
it('creates HTML for results', () => {
const mode = Printer.OutputMode.html;
const htmlOutput = Printer.createOutput(sampleResults, mode);
@ -84,11 +69,10 @@ describe('Printer', () => {
});
it('writes extended info', () => {
const mode = 'pretty';
const prettyOutput = Printer.createOutput(sampleResults, mode);
const output = new RegExp(log.heavyHorizontal + log.heavyHorizontal +
' \u2026dobetterweb/dbw_tester.css', 'i');
const mode = Printer.OutputMode.html;
const htmlOutput = Printer.createOutput(sampleResults, mode);
const outputCheck = new RegExp('\u2026dobetterweb/dbw_tester.css', 'i');
assert.ok(output.test(prettyOutput));
assert.ok(outputCheck.test(htmlOutput));
});
});

Просмотреть файл

@ -34,7 +34,7 @@ Kick off a run by passing `lighthouse` the URL to audit:
lighthouse https://airhorner.com/
```
Lighthouse will prettyprint a report to CLI. You can control the output format by passing flags.
By default, Lighthouse writes the report to an HTML file. You can control the output format by passing flags.
#### CLI options
@ -66,8 +66,13 @@ Configuration:
Output:
--output Reporter for the results, supports multiple values
[choices: "none", "pretty", "json", "html"] [default: "none"]
--output-path The file path to output the results
[choices: "json", "html"] [default: "html"]
--output-path The file path to output the results. Use 'stdout' to write to
stdout.
If using JSON output, default is stdout.
If using HTML output, default is a file in the working
directory with a name based on the test URL and date.
If using multiple outputs, --output-path is ignored.
Example: --output-path=./lighthouse-results.html [default: "stdout"]
Options: