UNPKG

2.54 kBJavaScriptView Raw
1'use strict';
2const marked = require('marked');
3const chalk = require('chalk');
4const TerminalRenderer = require('marked-terminal');
5const hasUnicode = require('has-unicode');
6const prettyJson = require('prettyjson');
7const util = require('util');
8const isPlainObject = require('is-plain-object');
9const Base = require('yeoman-generator').generators.Base;
10
11marked.setOptions({
12 renderer: new TerminalRenderer({
13 strong: chalk.bold.underline,
14 em: chalk.bold,
15 showSectionPrefix: false,
16 reflowText: true,
17 width: 66
18 })
19});
20
21let pad = (x, num) => {
22 let padding = Array.apply(Array, new Array(num)).join(' ');
23 return padding + x.split('\n').join('\n' + padding);
24}
25
26module.exports = Base.extend({
27 constructor: function() {
28 Base.apply(this, arguments);
29
30 this.option('verbose', {
31 desc: 'Print verbose logging messages.',
32 alias: 'v',
33 type: Boolean
34 });
35
36 let marks = hasUnicode() ? {
37 success: '✓ ',
38 warning: '❢ ',
39 fatal: '✗ ',
40 } : {
41 success: '> ',
42 warning: '! ',
43 fatal: 'x '
44 };
45 marks.success = chalk.green(marks.success);
46 marks.warning = chalk.yellow(marks.warning);
47 marks.fatal = chalk.red(marks.fatal);
48
49 let print = this.log.bind(this);
50 let defaults = {
51 markdown: true,
52 padding: 2
53 };
54 let fmt = (t, o) => {
55 let opts = Object.assign({}, defaults, o);
56 let s;
57 switch(typeof t) {
58 case "string":
59 s = opts.markdown ? marked(t).trim() : t;
60 break;
61 case "object":
62 s = isPlainObject(t) ? prettyJson.render(t) : util.inspect(t);
63 break;
64 default:
65 s = util.inspect(t);
66 break;
67 }
68 return opts.padding ? pad(s, opts.padding) : s;
69 }
70
71 let status = mark =>
72 (t, opts) => print(mark + chalk.bold(fmt(t, opts)));
73
74 this.log = (t, opts) => print(fmt(t, opts));
75
76 this.log.success = status(marks.success);
77 this.log.warning = status(marks.warning);
78 this.log.fatal = status(marks.fatal);
79
80 let verboseStatus = log =>
81 (t, opts) => {
82 if (this.shouldLogVerbose()) {
83 log(t, opts)
84 }
85 };
86
87 this.verbose.success = verboseStatus(this.log.success);
88 this.verbose.warning = verboseStatus(this.log.warning);
89 this.verbose.fatal = verboseStatus(this.log.fatal);
90
91 },
92 verbose(x, opts) {
93 if (this.shouldLogVerbose()) {
94 this.log(x, opts);
95 }
96 },
97 shouldLogVerbose() {
98 return this.options.verbose || this.options.debug;
99 }
100});