adapter.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. 'use strict';
  2. const _ = require('lodash');
  3. const inquirer = require('inquirer');
  4. const diff = require('diff');
  5. const chalk = require('chalk');
  6. const logger = require('./util/log');
  7. /**
  8. * `TerminalAdapter` is the default implementation of `Adapter`, an abstraction
  9. * layer that defines the I/O interactions.
  10. *
  11. * It provides a CLI interaction
  12. *
  13. * @constructor
  14. */
  15. class TerminalAdapter {
  16. constructor() {
  17. this.promptModule = inquirer.createPromptModule();
  18. }
  19. get _colorDiffAdded() {
  20. return chalk.black.bgGreen;
  21. }
  22. get _colorDiffRemoved() {
  23. return chalk.bgRed;
  24. }
  25. _colorLines(name, str) {
  26. return str.split('\n').map(line => this[`_colorDiff${name}`](line)).join('\n');
  27. }
  28. /**
  29. * Prompt a user for one or more questions and pass
  30. * the answer(s) to the provided callback.
  31. *
  32. * It shares its interface with `Base.prompt`
  33. *
  34. * (Defined inside the constructor to keep interfaces separated between
  35. * instances)
  36. *
  37. * @param {Array} questions
  38. * @param {Function} callback
  39. */
  40. prompt(questions, cb) {
  41. const promise = this.promptModule(questions);
  42. promise.then(cb || _.noop);
  43. return promise;
  44. }
  45. /**
  46. * Shows a color-based diff of two strings
  47. *
  48. * @param {string} actual
  49. * @param {string} expected
  50. */
  51. diff(actual, expected) {
  52. let msg = diff.diffLines(actual, expected).map(str => {
  53. if (str.added) {
  54. return this._colorLines('Added', str.value);
  55. }
  56. if (str.removed) {
  57. return this._colorLines('Removed', str.value);
  58. }
  59. return str.value;
  60. }).join('');
  61. // Legend
  62. msg = '\n' +
  63. this._colorDiffRemoved('removed') +
  64. ' ' +
  65. this._colorDiffAdded('added') +
  66. '\n\n' +
  67. msg +
  68. '\n';
  69. console.log(msg);
  70. return msg;
  71. }
  72. }
  73. /**
  74. * Logging utility
  75. * @type {env/log}
  76. */
  77. TerminalAdapter.prototype.log = logger();
  78. module.exports = TerminalAdapter;