This repository has been archived by the owner on Jun 27, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathdisplay.js
342 lines (296 loc) · 8.22 KB
/
display.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
const readline = require('readline');
const { isWindows } = require('./misc');
// could we explore https://www.npmjs.com/package/columnify
// to simplify the columns/tables? the | - decoration is big
const Table = require('cli-table2');
const colors = require('colors/safe');
const stringLength = require('string-length');
const _ = require('lodash');
const read = require('read');
const notUndef = s => String(s === undefined ? '' : s).trim();
const unBacktick = s => s.replace(/\n?`+(bash)?/g, '');
const prettyJSONstringify = obj => JSON.stringify(obj, null, ' ');
const markdownLog = str => {
// turn markdown into something with styles and stuff
// https://blog.mariusschulz.com/content/images/sublime_markdown_with_syntax_highlighting.png
console.log(unBacktick(str));
};
// Convert rows from keys to column labels.
const rewriteLabels = (rows, columnDefs) => {
return rows.map(row => {
const consumptionRow = {};
columnDefs.forEach(columnDef => {
const [label, key, _default] = columnDef;
const val = _.get(row, key || label, _default);
consumptionRow[label] = notUndef(val);
});
return consumptionRow;
});
};
const makePlainSingle = row => {
return _.map(row, (value, key) => {
return (colors.grey('==') + ' ' + colors.bold(key) + '\n' + value).trim();
}).join('\n');
};
// An easier way to print rows for copy paste accessibility.
const makePlain = (rows, columnDefs) => {
return (
rewriteLabels(rows, columnDefs)
.map(makePlainSingle)
.join(colors.grey('\n\n - - - - - - - - - - - - - - - - - - \n\n')) + '\n'
);
};
const isTooWideForWindow = str => {
const widestRow = str.split('\n').reduce((coll, row) => {
if (stringLength(row) > coll) {
return stringLength(row);
} else {
return coll;
}
}, 0);
return widestRow > process.stdout.columns;
};
const ansiTrim = s =>
_.trim(s, [
'\r',
'\n',
' '
// '\u001b[39m',
// '\u001b[90m',
]);
const CHARS = {
// 'top': '', 'top-mid': '', 'top-left': '', 'top-right': '',
// 'bottom': ' ', 'bottom-mid': ' ', 'bottom-left': ' ', 'bottom-right': ' '
};
// Similar to makeTable, but prints the column headings in the left-hand column
// and the values in the right-hand column, in rows
const makeRowBasedTable = (rows, columnDefs, { includeIndex = true } = {}) => {
const tableOptions = {
chars: CHARS,
style: {
compact: true
}
};
const table = new Table(tableOptions);
const maxLabelLength = _.reduce(
columnDefs,
(maxLength, columnDef) => {
if (columnDef[0] && stringLength(columnDef[0]) > maxLength) {
return stringLength(columnDef[0]);
}
return maxLength;
},
1
);
const widthForValue = process.stdout.columns - maxLabelLength - 15; // The last bit accounts for some padding and borders
if (widthForValue < 1) {
return makePlain(rows, columnDefs); // There's not enough space to display the table
}
rows.forEach((row, index) => {
if (includeIndex) {
table.push([{ colSpan: 2, content: colors.grey(`= ${index + 1} =`) }]);
}
columnDefs.forEach(columnDef => {
const consumptionRow = {};
const [label, key, _default] = columnDef;
let val = _.get(row, key || label, _default);
val = notUndef(val);
if (stringLength(val) > widthForValue) {
try {
val = prettyJSONstringify(JSON.parse(val));
} catch (err) {
// Wasn't JSON, so splice in newlines so that word wraping works properly
let rest = val;
val = '';
while (stringLength(rest) > 0) {
val += rest.slice(0, widthForValue);
if (val.indexOf('\n') === -1) {
val += '\n';
}
rest = rest.slice(widthForValue);
}
}
}
let colLabel = ' ' + colors.bold(label);
if (!includeIndex) {
colLabel = colors.bold(label) + ' ';
}
consumptionRow[colLabel] = val.trim();
table.push(consumptionRow);
});
if (index < rows.length - 1) {
table.push([{ colSpan: 2, content: ' ' }]);
}
});
const strTable = ansiTrim(table.toString());
if (isTooWideForWindow(strTable)) {
return makePlain(rows, columnDefs);
}
return strTable;
};
// Wraps the cli-table2 library. Rows is an array of objects, columnDefs
// an ordered sub-array [[label, key, (optional_default)], ...].
const makeTable = (rows, columnDefs) => {
const tableOptions = {
head: columnDefs.map(([label]) => label),
chars: CHARS,
style: {
compact: true,
head: ['bold']
}
};
const table = new Table(tableOptions);
rows.forEach(row => {
const consumptionRow = [];
columnDefs.forEach(columnDef => {
const [label, key, _default] = columnDef;
const val = _.get(row, key || label, _default);
consumptionRow.push(notUndef(val));
});
table.push(consumptionRow);
});
const strTable = ansiTrim(table.toString());
if (isTooWideForWindow(strTable)) {
return makeRowBasedTable(rows, columnDefs, { includeIndex: false });
}
return strTable;
};
const makeJSON = (rows, columnDefs) =>
prettyJSONstringify(rewriteLabels(rows, columnDefs));
const makeRawJSON = rows => prettyJSONstringify(rows);
const makeSmall = rows => {
const longestRow = _.max(rows.map(r => r.name.length));
let res = [];
rows.forEach(row => {
res.push(
` ${row.name}${' '.repeat(longestRow - row.name.length + 1)} # ${
row.help
}`
);
});
return res.join('\n');
};
const DEFAULT_STYLE = 'table';
const formatStyles = {
plain: makePlain,
json: makeJSON,
raw: makeRawJSON,
row: makeRowBasedTable,
table: makeTable,
small: makeSmall
};
const printData = (
rows,
columnDefs,
ifEmptyMessage = '',
useRowBasedTable = false
) => {
const formatStyle =
(global.argOpts || {}).format || (useRowBasedTable ? 'row' : DEFAULT_STYLE);
const formatter = formatStyles[formatStyle] || formatStyles[DEFAULT_STYLE];
if (rows && !rows.length) {
console.log(ifEmptyMessage);
} else {
console.log(formatter(rows, columnDefs));
}
};
let spinner;
let currentIter = 0;
let spinSpeed;
let spinTransitions;
if (isWindows()) {
spinSpeed = 240;
spinTransitions = [' ', '. ', '.. ', '...'];
} else {
spinSpeed = 80;
spinTransitions = ['⠃', '⠉', '⠘', '⠰', '⠤', '⠆'];
}
const finalTransition = spinTransitions[0];
const clearSpinner = () => {
process.stdout.write('\x1b[?25h'); // set cursor to white...
clearInterval(spinner);
spinner = undefined;
};
const writeNextSpinnerTick = (
final = false,
_finalTransition = finalTransition
) => {
readline.moveCursor(process.stdout, -spinTransitions[currentIter].length, 0);
currentIter++;
if (currentIter >= spinTransitions.length) {
currentIter = 0;
}
process.stdout.write(final ? _finalTransition : spinTransitions[currentIter]);
};
const startSpinner = () => {
process.stdout.write(spinTransitions[currentIter]);
clearSpinner();
process.stdout.write('\x1b[?25l'); // set cursor to black...
spinner = setInterval(() => {
writeNextSpinnerTick();
}, spinSpeed);
};
const endSpinner = _finalTransition => {
if (!spinner) {
return;
}
clearSpinner();
writeNextSpinnerTick(true, _finalTransition);
};
const printStarting = msg => {
if (spinner) {
return;
}
if (msg) {
msg = ' ' + msg + ' ';
} else {
msg = '';
}
process.stdout.write(msg);
startSpinner();
};
const printDone = (success = true, message) => {
if (!spinner) {
return;
}
endSpinner();
if (message) {
message = ` ${message}`;
}
const logMsg = success
? colors.green(message || ' done!')
: colors.red(message || ' fail!');
console.log(logMsg);
};
// Get input from a user.
const getInput = (question, { secret = false } = {}) => {
return new Promise((resolve, reject) => {
read(
{
prompt: question,
silent: secret,
replace: secret ? '*' : undefined
},
(err, result) => {
if (err) {
reject(err);
}
resolve(result);
}
);
});
};
module.exports = {
clearSpinner,
endSpinner,
formatStyles,
getInput,
makeRowBasedTable,
makeTable,
markdownLog,
prettyJSONstringify,
printData,
printDone,
printStarting,
startSpinner
};