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

refactor: outputData as a proper PWMetrics method #195

Merged
merged 2 commits into from
Oct 16, 2018
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
30 changes: 3 additions & 27 deletions bin/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@
'use strict';

/* eslint-disable no-logger */
const sysPath = require('path');
const fs = require('fs');
const os = require('os');
const yargs = require('yargs');

const PWMetrics = require('../lib/index');
Expand Down Expand Up @@ -95,34 +92,13 @@ options.url = cliFlags._[0] || options.url;
if (!options.url || !options.url.length)
throw new Error(getMessage('NO_URL'));

const writeToDisk = function(fileName, data) {
return new Promise((resolve, reject) => {
const path = sysPath.join(process.cwd(), fileName);
fs.writeFile(path, data, err => {
if (err) reject(err);
logger.log(getMessageWithPrefix('SUCCESS', 'SAVED_TO_JSON', path));
resolve();
});
});
};

const pwMetrics = new PWMetrics(options.url, options);
pwMetrics.start(data => {
if (options.flags.json) {
// serialize accordingly
const formattedData = JSON.stringify(data, null, 2) + os.EOL;
// output to file.
if (options.flags.outputPath !== 'stdout') {
writeToDisk(options.flags.outputPath, formattedData);
// output to stdout
} else if (formattedData) {
process.stdout.write(formattedData);
}
}
})
pwMetrics.start()
.then(() => {
process.exit(0);
}).catch(err => {
})
.catch(err => {
logger.error(err);
process.exit(1);
});
25 changes: 21 additions & 4 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,23 @@
declare var process: {
stdout: {
columns: string;
write: Function;
}
};

const opn = require('opn');
const os = require('os');
const path = require('path');


import {METRICS} from './metrics/metrics';
import {Logger} from './utils/logger';
import {LHRunner} from './lh-runner';
import {Sheets} from './sheets';
import {adaptMetricsData} from './metrics/metrics-adapter';
import {validateMetrics, normalizeExpectationMetrics, checkExpectations} from './expectations';
import {upload} from './upload';
import {writeToDisk} from './utils/fs';
import {getMessage, getMessageWithPrefix} from './utils/messages';
import {drawChart} from './chart/chart';

Expand Down Expand Up @@ -45,6 +49,7 @@ class PWMetrics {
chromeFlags: '',
showOutput: true,
failOnError: false,
outputPath: 'stdout',
};
runs: number;
sheets: SheetsConfig;
Expand Down Expand Up @@ -74,7 +79,7 @@ class PWMetrics {
this.logger = Logger.getInstance({showOutput: this.flags.showOutput});
}

async start(outputDataCallback) {
async start() {
const runs = Array.apply(null, {length: +this.runs}).map(Number.call, Number);
let metricsResults: MetricsResults[] = [];

Expand All @@ -100,9 +105,7 @@ class PWMetrics {
await sheets.appendResults(results.runs);
}

if (outputDataCallback) {
outputDataCallback(results);
}
await this.outputData(results);

if (this.flags.expectations) {
const resultsToCompare = this.runs > 1 ? results.median.timings : results[0].timings;
Expand Down Expand Up @@ -216,6 +219,20 @@ class PWMetrics {
opn(getTimelineViewerUrl(id));
}
}

outputData(data: PWMetricsResults) {
if (this.flags.json) {
// serialize accordingly
const formattedData = JSON.stringify(data, null, 2) + os.EOL;
// output to file.
if (this.flags.outputPath !== 'stdout') {
return writeToDisk(this.flags.outputPath, formattedData);
// output to stdout
} else if (formattedData) {
return Promise.resolve(process.stdout.write(formattedData));
}
}
}
}

module.exports = PWMetrics;
27 changes: 24 additions & 3 deletions lib/utils/fs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,16 @@
// Licensed under the Apache License, Version 2.0. See LICENSE

import * as path from 'path';
import * as fs from 'fs';
import * as promisify from 'micro-promisify';

function getConfigFromFile(fileName: string = 'package.json') {
import {getMessageWithPrefix} from './messages';
import {Logger} from './logger';

const logger = Logger.getInstance();


export function getConfigFromFile(fileName: string = 'package.json') {
let resolved: string;
try {
resolved = require.resolve(`./${fileName}`);
Expand All @@ -17,7 +25,20 @@ function getConfigFromFile(fileName: string = 'package.json') {
return config.pwmetrics || {};
else return config;
} else throw new Error(`Invalid config from ${fileName}`);

}

module.exports = { getConfigFromFile };
export function writeToDisk(fileName: string, data: string) {
GuillaumeAmat marked this conversation as resolved.
Show resolved Hide resolved
return new Promise(async (resolve, reject) => {
GuillaumeAmat marked this conversation as resolved.
Show resolved Hide resolved
const filePath = path.join(process.cwd(), fileName);

try {
await promisify(fs.writeFile)(filePath, data);
} catch (err) {
reject(err);
}

logger.log(getMessageWithPrefix('SUCCESS', 'SAVED_TO_JSON', filePath));
resolve();
});
}
1 change: 1 addition & 0 deletions types/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export interface FeatureFlags {
port?: number;
showOutput: Boolean;
failOnError: Boolean;
outputPath: string;
}

export interface MetricsResults {
Expand Down