From 4a69ab03efeaaf454ccef97a217c61185452831d Mon Sep 17 00:00:00 2001 From: Guillaume AMAT Date: Fri, 12 Oct 2018 23:30:42 +0200 Subject: [PATCH 1/2] refactor: outputData as a proper PWMetrics method --- bin/cli.js | 30 +++--------------------------- lib/index.ts | 25 +++++++++++++++++++++---- lib/utils/fs.ts | 25 ++++++++++++++++++++++--- types/types.ts | 1 + 4 files changed, 47 insertions(+), 34 deletions(-) diff --git a/bin/cli.js b/bin/cli.js index e5e7200..b0285f0 100755 --- a/bin/cli.js +++ b/bin/cli.js @@ -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'); @@ -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); }); diff --git a/lib/index.ts b/lib/index.ts index b4de422..f218f8d 100644 --- a/lib/index.ts +++ b/lib/index.ts @@ -4,12 +4,15 @@ 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'; @@ -17,6 +20,7 @@ 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'; @@ -45,6 +49,7 @@ class PWMetrics { chromeFlags: '', showOutput: true, failOnError: false, + outputPath: 'stdout', }; runs: number; sheets: SheetsConfig; @@ -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[] = []; @@ -100,9 +105,7 @@ class PWMetrics { await sheets.appendResults(results.runs); } - if (outputDataCallback) { - outputDataCallback(results); - } + this.outputData(results); if (this.flags.expectations) { const resultsToCompare = this.runs > 1 ? results.median.timings : results[0].timings; @@ -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') { + writeToDisk(this.flags.outputPath, formattedData); + // output to stdout + } else if (formattedData) { + process.stdout.write(formattedData); + } + } + } } module.exports = PWMetrics; diff --git a/lib/utils/fs.ts b/lib/utils/fs.ts index cd3bb0e..60c9a06 100644 --- a/lib/utils/fs.ts +++ b/lib/utils/fs.ts @@ -2,8 +2,14 @@ // Licensed under the Apache License, Version 2.0. See LICENSE import * as path from 'path'; +import * as fs from 'fs'; +import {getMessageWithPrefix} from './messages'; +import {Logger} from './logger'; -function getConfigFromFile(fileName: string = 'package.json') { +const logger = Logger.getInstance(); + + +export function getConfigFromFile(fileName: string = 'package.json') { let resolved: string; try { resolved = require.resolve(`./${fileName}`); @@ -17,7 +23,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) { + return new Promise((resolve, reject) => { + const filePath = path.join(process.cwd(), fileName); + + try { + fs.writeFileSync(filePath, data); + } catch (err) { + reject(err); + } + + logger.log(getMessageWithPrefix('SUCCESS', 'SAVED_TO_JSON', filePath)); + resolve(); + }); +} diff --git a/types/types.ts b/types/types.ts index 192e6e3..ef8b9d4 100644 --- a/types/types.ts +++ b/types/types.ts @@ -29,6 +29,7 @@ export interface FeatureFlags { port?: number; showOutput: Boolean; failOnError: Boolean; + outputPath: string; } export interface MetricsResults { From 3572028e03c5724494ad9d165c9becd411c9c3f4 Mon Sep 17 00:00:00 2001 From: Guillaume AMAT Date: Sun, 14 Oct 2018 22:12:00 +0200 Subject: [PATCH 2/2] feat: use micro-promisify in writeToDisk --- lib/index.ts | 6 +++--- lib/utils/fs.ts | 6 ++++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/lib/index.ts b/lib/index.ts index f218f8d..7acf5ea 100644 --- a/lib/index.ts +++ b/lib/index.ts @@ -105,7 +105,7 @@ class PWMetrics { await sheets.appendResults(results.runs); } - this.outputData(results); + await this.outputData(results); if (this.flags.expectations) { const resultsToCompare = this.runs > 1 ? results.median.timings : results[0].timings; @@ -226,10 +226,10 @@ class PWMetrics { const formattedData = JSON.stringify(data, null, 2) + os.EOL; // output to file. if (this.flags.outputPath !== 'stdout') { - writeToDisk(this.flags.outputPath, formattedData); + return writeToDisk(this.flags.outputPath, formattedData); // output to stdout } else if (formattedData) { - process.stdout.write(formattedData); + return Promise.resolve(process.stdout.write(formattedData)); } } } diff --git a/lib/utils/fs.ts b/lib/utils/fs.ts index 60c9a06..acb8b06 100644 --- a/lib/utils/fs.ts +++ b/lib/utils/fs.ts @@ -3,6 +3,8 @@ import * as path from 'path'; import * as fs from 'fs'; +import * as promisify from 'micro-promisify'; + import {getMessageWithPrefix} from './messages'; import {Logger} from './logger'; @@ -27,11 +29,11 @@ export function getConfigFromFile(fileName: string = 'package.json') { } export function writeToDisk(fileName: string, data: string) { - return new Promise((resolve, reject) => { + return new Promise(async (resolve, reject) => { const filePath = path.join(process.cwd(), fileName); try { - fs.writeFileSync(filePath, data); + await promisify(fs.writeFile)(filePath, data); } catch (err) { reject(err); }