[cli] Allow dynamic label in output.time() function (#6492)

Updates the `output.time()` function to accept a function as the "label" parameter. When a function is passed, it will be invoked twice, once at the beginning of the promise being executed, and a second time after the promise has resolved. The second time, the return value of the promise is passed to the label function, so that the resolved value may be used to create the label.

Drops usage of Node's `console.time()` and `console.timeEnd()` since we were using it in a hacky and unnecessary way.
This commit is contained in:
Nathan Rajlich
2021-07-19 13:48:02 -07:00
committed by GitHub
parent 8cc72a6872
commit 181f1d60b6

View File

@@ -1,7 +1,5 @@
import chalk from 'chalk'; import chalk from 'chalk';
import boxen from 'boxen'; import boxen from 'boxen';
import { format } from 'util';
import { Console } from 'console';
import renderLink from './link'; import renderLink from './link';
import wait, { StopSpinner } from './wait'; import wait, { StopSpinner } from './wait';
@@ -138,20 +136,20 @@ function _createOutput({ debug: debugEnabled = false }: OutputOptions = {}) {
} }
} }
const c = { async function time<T>(
_times: new Map(), label: string | ((r?: T) => string),
log(a: string, ...args: string[]) { fn: Promise<T> | (() => Promise<T>)
debug(format(a, ...args)); ) {
},
};
async function time(label: string, fn: Promise<any> | (() => Promise<any>)) {
const promise = typeof fn === 'function' ? fn() : fn; const promise = typeof fn === 'function' ? fn() : fn;
if (debugEnabled) { if (debugEnabled) {
c.log(label); const startLabel = typeof label === 'function' ? label() : label;
Console.prototype.time.call(c, label); debug(startLabel);
const start = Date.now();
const r = await promise; const r = await promise;
Console.prototype.timeEnd.call(c, label); const endLabel = typeof label === 'function' ? label(r) : label;
const duration = Date.now() - start;
debug(`${endLabel}: ${(duration / 1000).toFixed(2)}s`);
return r; return r;
} }