Skip to content

Commit

Permalink
[cli] Move bin.ts core into -cli/run.ts (#2602)
Browse files Browse the repository at this point in the history
  • Loading branch information
paulirish committed Jun 28, 2017
1 parent 5d75194 commit f870d5e
Show file tree
Hide file tree
Showing 5 changed files with 198 additions and 141 deletions.
145 changes: 8 additions & 137 deletions lighthouse-cli/bin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,31 +5,23 @@
*/
'use strict';

const _RUNTIME_ERROR_CODE = 1;
const _PROTOCOL_TIMEOUT_EXIT_CODE = 67;
import * as path from 'path';

const assetSaver = require('../lighthouse-core/lib/asset-saver.js');
const getFilenamePrefix = require('../lighthouse-core/lib/file-namer.js').getFilenamePrefix;
import {launch, LaunchedChrome} from '../chrome-launcher/chrome-launcher';
import * as Commands from './commands/commands';
import {getFlags, Flags} from './cli-flags';
const lighthouse = require('../lighthouse-core');
import * as Printer from './printer';
import {getFlags} from './cli-flags';
import {runLighthouse} from './run';

const log = require('lighthouse-logger');
import * as path from 'path';
const perfOnlyConfig = require('../lighthouse-core/config/perf.json');
const performanceXServer = require('./performance-experiment/server');
import * as Printer from './printer';
import {Results} from './types/types';
const pkg = require('../package.json');

// accept noop modules for these, so the real dependency is optional.
import {opn, updateNotifier} from './shim-modules';
import {updateNotifier} from './shim-modules';

updateNotifier({pkg}).notify(); // Tell user if there's a newer version of LH.

interface LighthouseError extends Error {
code?: string
}
// Tell user if there's a newer version of LH.
updateNotifier({pkg}).notify();

const cliFlags = getFlags();

Expand Down Expand Up @@ -67,127 +59,6 @@ if (cliFlags.output === Printer.OutputMode[Printer.OutputMode.json] && !cliFlags
cliFlags.outputPath = 'stdout';
}

/**
* Attempts to connect to an instance of Chrome with an open remote-debugging
* port. If none is found and the `skipAutolaunch` flag is not true, launches
* a debuggable instance.
*/
async function getDebuggableChrome(flags: Flags) {
return await launch(
{port: flags.port, chromeFlags: flags.chromeFlags.split(' '), logLevel: cliFlags.logLevel});
}

function showConnectionError() {
console.error('Unable to connect to Chrome');
console.error(
'If you\'re using lighthouse with --skip-autolaunch, ' +
'make sure you\'re running some other Chrome with a debugger.');
process.exit(_RUNTIME_ERROR_CODE);
}

function showRuntimeError(err: LighthouseError) {
console.error('Runtime error encountered:', err);
if (err.stack) {
console.error(err.stack);
}
process.exit(_RUNTIME_ERROR_CODE);
}

function showProtocolTimeoutError() {
console.error('Debugger protocol timed out while connecting to Chrome.');
process.exit(_PROTOCOL_TIMEOUT_EXIT_CODE);
}

function showPageLoadError() {
console.error('Unable to load the page. Please verify the url you are trying to review.');
process.exit(_RUNTIME_ERROR_CODE);
}

function handleError(err: LighthouseError) {
if (err.code === 'PAGE_LOAD_ERROR') {
showPageLoadError();
} else if (err.code === 'ECONNREFUSED') {
showConnectionError();
} else if (err.code === 'CRI_TIMEOUT') {
showProtocolTimeoutError();
} else {
showRuntimeError(err);
}
}

function saveResults(results: Results, artifacts: Object, flags: Flags) {
let promise = Promise.resolve(results);
const cwd = process.cwd();
// Use the output path as the prefix for all generated files.
// If no output path is set, generate a file prefix using the URL and date.
const configuredPath = !flags.outputPath || flags.outputPath === 'stdout' ?
getFilenamePrefix(results) :
flags.outputPath.replace(/\.\w{2,4}$/, '');
const resolvedPath = path.resolve(cwd, configuredPath);

if (flags.saveArtifacts) {
assetSaver.saveArtifacts(artifacts, resolvedPath);
}

if (flags.saveAssets) {
promise = promise.then(_ => assetSaver.saveAssets(artifacts, results.audits, resolvedPath));
}

const typeToExtension = (type: string) => type === 'domhtml' ? 'dom.html' : type;
return promise.then(_ => {
if (Array.isArray(flags.output)) {
return flags.output.reduce((innerPromise, outputType) => {
const outputPath = `${resolvedPath}.report.${typeToExtension(outputType)}`;
return innerPromise.then((_: Results) => Printer.write(results, outputType, outputPath));
}, Promise.resolve(results));
} else {
const outputPath =
flags.outputPath || `${resolvedPath}.report.${typeToExtension(flags.output)}`;
return Printer.write(results, flags.output, outputPath).then(results => {
if (flags.output === Printer.OutputMode[Printer.OutputMode.html] ||
flags.output === Printer.OutputMode[Printer.OutputMode.domhtml]) {
if (flags.view) {
opn(outputPath, {wait: false});
} else {
log.log(
'CLI',
'Protip: Run lighthouse with `--view` to immediately open the HTML report in your browser');
}
}

return results;
});
}
});
}

export async function runLighthouse(
url: string, flags: Flags, config: Object|null): Promise<{}|void> {
let launchedChrome: LaunchedChrome|undefined;

try {
launchedChrome = await getDebuggableChrome(flags);
flags.port = launchedChrome.port;
const results = await lighthouse(url, flags, config);

const artifacts = results.artifacts;
delete results.artifacts;

await saveResults(results, artifacts!, flags);
if (flags.interactive) {
await performanceXServer.hostExperiment({url, flags, config}, results);
}

return await launchedChrome.kill();
} catch (err) {
if (typeof launchedChrome !== 'undefined') {
await launchedChrome!.kill();
}

return handleError(err);
}
}

export function run() {
return runLighthouse(url, cliFlags, config);
}
8 changes: 5 additions & 3 deletions lighthouse-cli/cli-flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@ import {GetValidOutputOptions, OutputMode} from './printer';
export interface Flags {
skipAutolaunch: boolean, port: number, selectChrome: boolean, chromeFlags: string, output: any,
outputPath: string, interactive: boolean, saveArtifacts: boolean, saveAssets: boolean,
view: boolean, maxWaitForLoad: number
view: boolean, maxWaitForLoad: number, logLevel: string
}

export function getFlags() {
return yargs.help('help')
export function getFlags(manualArgv?: string) {
const y = manualArgv ? yargs(manualArgv) : yargs;

return y.help('help')
.version(() => pkg.version)
.showHelpOnFail(false, 'Specify --help for available options')

Expand Down
2 changes: 1 addition & 1 deletion lighthouse-cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"scripts": {
"build": "tsc",
"dev": "tsc -w",
"test": "mocha --reporter dot test/**/*-test.js",
"test": "mocha --reporter dot test/**/*-test.js --timeout 15000",
"coverage": "nyc yarn test && nyc report --reporter=text-lcov > lcov.info",
"test-formatting": "./test/check-formatting.sh",
"format": "clang-format -i -style=file *.ts **/*.ts"
Expand Down
149 changes: 149 additions & 0 deletions lighthouse-cli/run.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
/**
* @license Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';

import * as path from 'path';

import * as Printer from './printer';
import {Results} from './types/types';
import {Flags} from './cli-flags';
import {launch, LaunchedChrome} from '../chrome-launcher/chrome-launcher';
const lighthouse = require('../lighthouse-core');
const log = require('lighthouse-logger');
const getFilenamePrefix = require('../lighthouse-core/lib/file-namer.js').getFilenamePrefix;
const assetSaver = require('../lighthouse-core/lib/asset-saver.js');
const performanceXServer = require('./performance-experiment/server');

// accept noop modules for these, so the real dependency is optional.
import {opn} from './shim-modules';

const _RUNTIME_ERROR_CODE = 1;
const _PROTOCOL_TIMEOUT_EXIT_CODE = 67;

interface LighthouseError extends Error {
code?: string
}

/**
* Attempts to connect to an instance of Chrome with an open remote-debugging
* port. If none is found and the `skipAutolaunch` flag is not true, launches
* a debuggable instance.
*/
async function getDebuggableChrome(flags: Flags) {
return await launch(
{port: flags.port, chromeFlags: flags.chromeFlags.split(' '), logLevel: flags.logLevel});
}

function showConnectionError() {
console.error('Unable to connect to Chrome');
console.error(
'If you\'re using lighthouse with --skip-autolaunch, ' +
'make sure you\'re running some other Chrome with a debugger.');
process.exit(_RUNTIME_ERROR_CODE);
}

function showRuntimeError(err: LighthouseError) {
console.error('Runtime error encountered:', err);
if (err.stack) {
console.error(err.stack);
}
process.exit(_RUNTIME_ERROR_CODE);
}

function showProtocolTimeoutError() {
console.error('Debugger protocol timed out while connecting to Chrome.');
process.exit(_PROTOCOL_TIMEOUT_EXIT_CODE);
}

function showPageLoadError() {
console.error('Unable to load the page. Please verify the url you are trying to review.');
process.exit(_RUNTIME_ERROR_CODE);
}

function handleError(err: LighthouseError) {
if (err.code === 'PAGE_LOAD_ERROR') {
showPageLoadError();
} else if (err.code === 'ECONNREFUSED') {
showConnectionError();
} else if (err.code === 'CRI_TIMEOUT') {
showProtocolTimeoutError();
} else {
showRuntimeError(err);
}
}

export function saveResults(results: Results, artifacts: Object, flags: Flags) {
let promise = Promise.resolve(results);
const cwd = process.cwd();
// Use the output path as the prefix for all generated files.
// If no output path is set, generate a file prefix using the URL and date.
const configuredPath = !flags.outputPath || flags.outputPath === 'stdout' ?
getFilenamePrefix(results) :
flags.outputPath.replace(/\.\w{2,4}$/, '');
const resolvedPath = path.resolve(cwd, configuredPath);

if (flags.saveArtifacts) {
assetSaver.saveArtifacts(artifacts, resolvedPath);
}

if (flags.saveAssets) {
promise = promise.then(_ => assetSaver.saveAssets(artifacts, results.audits, resolvedPath));
}

const typeToExtension = (type: string) => type === 'domhtml' ? 'dom.html' : type;
return promise.then(_ => {
if (Array.isArray(flags.output)) {
return flags.output.reduce((innerPromise, outputType) => {
const outputPath = `${resolvedPath}.report.${typeToExtension(outputType)}`;
return innerPromise.then((_: Results) => Printer.write(results, outputType, outputPath));
}, Promise.resolve(results));
} else {
const outputPath =
flags.outputPath || `${resolvedPath}.report.${typeToExtension(flags.output)}`;
return Printer.write(results, flags.output, outputPath).then(results => {
if (flags.output === Printer.OutputMode[Printer.OutputMode.html] ||
flags.output === Printer.OutputMode[Printer.OutputMode.domhtml]) {
if (flags.view) {
opn(outputPath, {wait: false});
} else {
log.log(
'CLI',
'Protip: Run lighthouse with `--view` to immediately open the HTML report in your browser');
}
}

return results;
});
}
});
}

export async function runLighthouse(
url: string, flags: Flags, config: Object|null): Promise<{}|void> {
let launchedChrome: LaunchedChrome|undefined;

try {
launchedChrome = await getDebuggableChrome(flags);
flags.port = launchedChrome.port;
const results = await lighthouse(url, flags, config);

const artifacts = results.artifacts;
delete results.artifacts;

await saveResults(results, artifacts!, flags);
if (flags.interactive) {
await performanceXServer.hostExperiment({url, flags, config}, results);
}

return await launchedChrome.kill();
} catch (err) {
if (typeof launchedChrome !== 'undefined') {
await launchedChrome!.kill();
}

return handleError(err);
}
}
35 changes: 35 additions & 0 deletions lighthouse-cli/test/cli/run-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* @license Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';

/* eslint-env mocha */
const assert = require('assert');
const path = require('path');
const fs = require('fs');

const run = require('../../run');
const fastConfig = {
'extends': 'lighthouse:default',
'settings': {
'onlyAudits': ['viewport']
}
};

const getFlags = require('../../cli-flags').getFlags;

describe('CLI run', function() {
it('runLighthouse completes a LH round trip', () => {
const url = 'chrome://version';
const filename = path.join(process.cwd(), 'run.ts.results.json');
const flags = getFlags(`--output=json --output-path=${filename} ${url}`);
return run.runLighthouse(url, flags, fastConfig).then(_ => {
assert.ok(fs.existsSync(filename));
const results = JSON.parse(fs.readFileSync(filename, 'utf-8'));
assert.equal(results.audits.viewport.rawValue, false);
fs.unlinkSync(filename);
});
});
});

0 comments on commit f870d5e

Please sign in to comment.