UNPKG

1.83 kBJavaScriptView Raw
1/**
2
3 cli-utils.js
4
5 Helper functions for cli interface.
6
7**/
8
9
10//
11// Dependencies
12//
13
14var chalk = require("chalk"),
15 fs = require("fs");
16
17
18//
19// Exports
20//
21
22var utils = module.exports = {};
23
24
25
26/**
27
28 Right appends spaces to a string
29
30 @param {String} str Base string
31 @param {Number} len Desired length
32 @returns {String} The padded string
33
34**/
35
36utils.pad = function(str, len) {
37 while (str.length < len) str += " ";
38 return str;
39};
40
41
42
43/**
44
45 Sorts and outputs strings in a grid format.
46
47 @param {Array} grid Array of lines, where each line has two cells (e.g. ["A", "B"])
48 @param {Number} options.len Length of each column
49 @param {String} [options.title] Title to display above the grid
50 @param {Array} [options.headers] Array of strings containing column headers
51
52**/
53
54utils.showGrid = function(grid, options) {
55
56 var str, i, j, m, n;
57
58 options = options || {};
59 if ("undefined" === typeof options.sort) options.sort = true;
60
61 if (options.sort)
62 grid.sort(function(a, b) {
63 return (a[0] < b[0]) ? -1 : (a[0] > b[0]) ? 1 : 0;
64 });
65
66 console.log("");
67
68 if (options.title) {
69 console.log(" " + chalk.cyan(options.title));
70 console.log("");
71 }
72
73 if (options.headers) {
74 str = " ";
75 for (j = 0, m = options.headers.length; j < m; j++)
76 str += utils.pad(options.headers[j], options.len);
77 console.log(chalk.yellow(str));
78 }
79
80 for (i = 0, n = grid.length; i < n; i++) {
81 str = " ";
82 for (j = 0, m = grid[i].length; j < m; j++)
83 str += utils.pad(grid[i][j], options.len);
84 console.log(str);
85 }
86
87 console.log("");
88
89};
90
91
92/**
93
94 Reads a file in (avoids `require("fs")` at the top of each file)
95
96 @param {String} p Path to the file
97 @returns {String} Contents of file
98
99**/
100
101utils.readFile = function(p) {
102 return require("fs").readFileSync(p, "utf8");
103};