diff --git a/lib/index.js b/lib/index.js index 2fadf0a..9573d50 100644 --- a/lib/index.js +++ b/lib/index.js @@ -8,6 +8,7 @@ const tmpdir = require('os').tmpdir(); const crypto = require('crypto'); const fs = require('fs'); const through = require('through2'); +const wrapConsoleMethod = require('./wrap-console-method'); const DEFAULT_WRITE_LEVEL = 'INFO'; @@ -37,6 +38,9 @@ class UI { // Output stream this.progress = false; this.actualOutputStream = options.outputStream || process.stdout; + + this._tapConsole(); + this.outputStream = through(function (data, enc, callback) { if (this.process) { spinner.stop(); @@ -57,6 +61,13 @@ class UI { this.errorReport = null; this.ci = !!options.ci; } + + _tapConsole() { + Object.keys(console).forEach(member => { + if (typeof original !== 'function') { return; } + wrapConsoleMethod(this, console, member); + }); + } /** Unified mechanism to write a string to the console. Optionally include a writeLevel, this is used to decide if the specific diff --git a/lib/wrap-console-method.js b/lib/wrap-console-method.js new file mode 100644 index 0000000..c92b989 --- /dev/null +++ b/lib/wrap-console-method.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = function wrapConsoleMethod(ui, console, name) { + const original = console[name]; + + console[name] = function(...args) { + if (ui.progress) { ui.spinner.stop(); } + try { + original.apply(console, args); + } finally { + if (ui.progress) { ui.spinner.start(); } + } + } +}; diff --git a/tests/unit/wrap-console-method-test.js b/tests/unit/wrap-console-method-test.js new file mode 100644 index 0000000..befea5b --- /dev/null +++ b/tests/unit/wrap-console-method-test.js @@ -0,0 +1,28 @@ +'use strict'; + +const wrapConsoleMethod = require('../../lib/wrap-console-method'); +const { expect } = require('chai'); + +describe('wrapConsoleMethod', function() { + it('works', function() { + let called = []; + function foo(...args) { + expect(this).to.eql(console); + called.push(args) + } + const ui = { }; + const console = { foo }; + + expect(console.foo).to.eql(foo); + wrapConsoleMethod(ui, console, 'foo'); + + expect(console.foo).to.not.eql(foo); + console.foo(1,2,3,4); + expect(called).to.eql([[1,2,3,4]]) + console.foo(2,3,4,5); + expect(called).to.eql([ + [1,2,3,4], + [2,3,4,5] + ]) + }) +});