[Pkg-javascript-commits] [node-cli-table] 01/14: Imported Upstream version 0.3.1
Ross Gammon
ross-guest at moszumanska.debian.org
Tue Mar 17 21:33:22 UTC 2015
This is an automated email from the git hooks/post-receive script.
ross-guest pushed a commit to branch master
in repository node-cli-table.
commit 3fc5572b3870e4768ad2e6cdc49b230c032e14d9
Author: Ross Gammon <rossgammon at mail.dk>
Date: Mon Mar 16 22:19:50 2015 +0100
Imported Upstream version 0.3.1
---
.gitignore | 2 +
.travis.yml | 7 ++
History.md | 51 +++++++++
Makefile | 8 ++
README.md | 177 ++++++++++++++++++++++++++++++
examples/revs.js | 59 ++++++++++
lib/index.js | 298 ++++++++++++++++++++++++++++++++++++++++++++++++++
lib/utils.js | 84 ++++++++++++++
package.json | 26 +++++
test/index.test.js | 257 +++++++++++++++++++++++++++++++++++++++++++
test/newlines.test.js | 92 ++++++++++++++++
11 files changed, 1061 insertions(+)
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..fe02460
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+lib-cov
+node_modules
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..3b44214
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,7 @@
+language: node_js
+node_js:
+ - "0.6"
+ - "0.8"
+ - "0.10"
+ - "0.11"
+
diff --git a/History.md b/History.md
new file mode 100644
index 0000000..f4e2698
--- /dev/null
+++ b/History.md
@@ -0,0 +1,51 @@
+
+0.3.1 / 2014-10-22
+==================
+
+ * fix example for new paths
+ * Readme badges
+ * Lighter production installs
+ * Safe colors
+ * In addition to 256-xterm ansi colors, handle 24-bit colors
+ * set up .travis.yml
+
+0.3.0 / 2014-02-02
+==================
+
+ * Switch version of colors to avoid npm broken-ness
+ * Handle custom colored strings correctly
+ * Removing var completely as return var width caused other problems.
+ * Fixing global leak of width variable.
+ * Omit horizontal decoration lines if empty
+ * Add a test for the the compact mode
+ * Make line() return the generated string instead of appending it to ret
+ * Customize the vertical cell separator separately from the right one
+ * Allow newer versions of colors to be used
+ * Added test for bordercolor
+ * Add bordercolor in style options and enable deepcopy of options
+
+0.2.0 / 2012-10-21
+==================
+
+ * test: avoid module dep in tests
+ * fix type bug on integer vertical table value
+ * handle newlines in vertical and cross tables
+ * factor out common style setting function
+ * handle newlines in body cells
+ * fix render bug when no header provided
+ * correctly calculate width of cells with newlines
+ * handles newlines in header cells
+ * ability to create cross tables
+ * changing table chars to ones that windows supports
+ * allow empty arguments to Table constructor
+ * fix headless tables containing empty first row
+ * add vertical tables
+ * remove reference to require.paths
+ * compact style for dense tables
+ * fix toString without col widths by cloning array
+ * [api]: Added abiltity to strip out ANSI color escape codes when calculating cell padding
+
+0.0.1 / 2011-01-03
+==================
+
+Initial release
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..9e35e45
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,8 @@
+
+test:
+ @NODE_ENV=test ./node_modules/.bin/expresso $(TESTFLAGS) test/*.test.js
+
+test-cov:
+ @TESTFLAGS=--cov $(MAKE) test
+
+.PHONY: test test-cov
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..b5a8e22
--- /dev/null
+++ b/README.md
@@ -0,0 +1,177 @@
+CLI Table [![NPM Version](http://badge.fury.io/js/cli-table.svg)](http://badge.fury.io/js/cli-table) [![Build Status](https://secure.travis-ci.org/Automattic/cli-table.svg)](http://travis-ci.org/Automattic/cli-table)
+=========
+
+This utility allows you to render unicode-aided tables on the command line from
+your node.js scripts.
+
+![Screenshot](http://i.imgur.com/sYq4T.png)
+
+## Features
+
+- Customizable characters that constitute the table.
+- Color/background styling in the header through
+ [colors.js](http://github.com/marak/colors.js)
+- Column width customization
+- Text truncation based on predefined widths
+- Text alignment (left, right, center)
+- Padding (left, right)
+- Easy-to-use API
+
+## Installation
+
+```bash
+npm install cli-table
+```
+
+## How to use
+
+### Horizontal Tables
+```javascript
+var Table = require('cli-table');
+
+// instantiate
+var table = new Table({
+ head: ['TH 1 label', 'TH 2 label']
+ , colWidths: [100, 200]
+});
+
+// table is an Array, so you can `push`, `unshift`, `splice` and friends
+table.push(
+ ['First value', 'Second value']
+ , ['First value', 'Second value']
+);
+
+console.log(table.toString());
+```
+
+### Vertical Tables
+```javascript
+var Table = require('cli-table');
+var table = new Table();
+
+table.push(
+ { 'Some key': 'Some value' }
+ , { 'Another key': 'Another value' }
+);
+
+console.log(table.toString());
+```
+### Cross Tables
+Cross tables are very similar to vertical tables, with two key differences:
+
+1. They require a `head` setting when instantiated that has an empty string as the first header
+2. The individual rows take the general form of { "Header": ["Row", "Values"] }
+
+```javascript
+var Table = require('cli-table');
+var table = new Table({ head: ["", "Top Header 1", "Top Header 2"] });
+
+table.push(
+ { 'Left Header 1': ['Value Row 1 Col 1', 'Value Row 1 Col 2'] }
+ , { 'Left Header 2': ['Value Row 2 Col 1', 'Value Row 2 Col 2'] }
+);
+
+console.log(table.toString());
+```
+
+### Custom styles
+The ```chars``` property controls how the table is drawn:
+```javascript
+var table = new Table({
+ chars: { 'top': '═' , 'top-mid': '╤' , 'top-left': '╔' , 'top-right': '╗'
+ , 'bottom': '═' , 'bottom-mid': '╧' , 'bottom-left': '╚' , 'bottom-right': '╝'
+ , 'left': '║' , 'left-mid': '╟' , 'mid': '─' , 'mid-mid': '┼'
+ , 'right': '║' , 'right-mid': '╢' , 'middle': '│' }
+});
+
+table.push(
+ ['foo', 'bar', 'baz']
+ , ['frob', 'bar', 'quuz']
+);
+
+console.log(table.toString());
+// Outputs:
+//
+//╔══════╤═════╤══════╗
+//║ foo │ bar │ baz ║
+//╟──────┼─────┼──────╢
+//║ frob │ bar │ quuz ║
+//╚══════╧═════╧══════╝
+```
+
+Empty decoration lines will be skipped, to avoid vertical separator rows just
+set the 'mid', 'left-mid', 'mid-mid', 'right-mid' to the empty string:
+```javascript
+var table = new Table({ chars: {'mid': '', 'left-mid': '', 'mid-mid': '', 'right-mid': ''} });
+table.push(
+ ['foo', 'bar', 'baz']
+ , ['frobnicate', 'bar', 'quuz']
+);
+
+console.log(table.toString());
+// Outputs: (note the lack of the horizontal line between rows)
+//┌────────────┬─────┬──────┐
+//│ foo │ bar │ baz │
+//│ frobnicate │ bar │ quuz │
+//└────────────┴─────┴──────┘
+```
+
+By setting all chars to empty with the exception of 'middle' being set to a
+single space and by setting padding to zero, it's possible to get the most
+compact layout with no decorations:
+```javascript
+var table = new Table({
+ chars: { 'top': '' , 'top-mid': '' , 'top-left': '' , 'top-right': ''
+ , 'bottom': '' , 'bottom-mid': '' , 'bottom-left': '' , 'bottom-right': ''
+ , 'left': '' , 'left-mid': '' , 'mid': '' , 'mid-mid': ''
+ , 'right': '' , 'right-mid': '' , 'middle': ' ' },
+ style: { 'padding-left': 0, 'padding-right': 0 }
+});
+
+table.push(
+ ['foo', 'bar', 'baz']
+ , ['frobnicate', 'bar', 'quuz']
+);
+
+console.log(table.toString());
+// Outputs:
+//foo bar baz
+//frobnicate bar quuz
+```
+
+## Running tests
+
+Clone the repository with all its submodules and run:
+
+```bash
+$ make test
+```
+
+## Credits
+
+- Guillermo Rauch <guillermo at learnboost.com> ([Guille](http://github.com/guille))
+
+## License
+
+(The MIT License)
+
+Copyright (c) 2010 LearnBoost <dev at learnboost.com>
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+'Software'), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/examples/revs.js b/examples/revs.js
new file mode 100644
index 0000000..83d0105
--- /dev/null
+++ b/examples/revs.js
@@ -0,0 +1,59 @@
+
+/**
+ * Module requirements.
+ */
+
+var Table = require('../lib');
+
+/**
+ * Example.
+ */
+
+/* col widths */
+var table = new Table({
+ head: ['Rel', 'Change', 'By', 'When']
+ , colWidths: [6, 21, 25, 17]
+});
+
+table.push(
+ ['v0.1', 'Testing something cool', 'rauchg at gmail.com', '7 minutes ago']
+ , ['v0.1', 'Testing something cool', 'rauchg at gmail.com', '8 minutes ago']
+);
+
+console.log(table.toString());
+
+
+/* compact */
+var table = new Table({
+ head: ['Rel', 'Change', 'By', 'When']
+ , colWidths: [6, 21, 25, 17]
+ , style : {compact : true, 'padding-left' : 1}
+});
+
+table.push(
+ ['v0.1', 'Testing something cool', 'rauchg at gmail.com', '7 minutes ago']
+ , ['v0.1', 'Testing something cool', 'rauchg at gmail.com', '8 minutes ago']
+ , []
+ , ['v0.1', 'Testing something cool', 'rauchg at gmail.com', '8 minutes ago']
+);
+
+console.log(table.toString());
+
+/* headless */
+var headless_table = new Table();
+headless_table.push(['v0.1', 'Testing something cool', 'rauchg at gmail.com', '7 minutes ago']);
+console.log(headless_table.toString());
+
+/* vertical */
+var vertical_table = new Table();
+vertical_table.push({ "Some Key": "Some Value"},
+ { "Another much longer key": "And its corresponding longer value"}
+);
+
+console.log(vertical_table.toString());
+
+/* cross */
+var cross_table = new Table({ head: ["", "Header #1", "Header #2"] });
+cross_table.push({ "Header #3": ["Value 1", "Value 2"] },
+ { "Header #4": ["Value 3", "Value 4"] });
+console.log(cross_table.toString());
diff --git a/lib/index.js b/lib/index.js
new file mode 100644
index 0000000..80628e3
--- /dev/null
+++ b/lib/index.js
@@ -0,0 +1,298 @@
+
+/**
+ * Module dependencies.
+ */
+
+var colors = require('colors/safe')
+ , utils = require('./utils')
+ , repeat = utils.repeat
+ , truncate = utils.truncate
+ , pad = utils.pad;
+
+/**
+ * Table constructor
+ *
+ * @param {Object} options
+ * @api public
+ */
+
+function Table (options){
+ this.options = utils.options({
+ chars: {
+ 'top': '─'
+ , 'top-mid': '┬'
+ , 'top-left': '┌'
+ , 'top-right': '┐'
+ , 'bottom': '─'
+ , 'bottom-mid': '┴'
+ , 'bottom-left': '└'
+ , 'bottom-right': '┘'
+ , 'left': '│'
+ , 'left-mid': '├'
+ , 'mid': '─'
+ , 'mid-mid': '┼'
+ , 'right': '│'
+ , 'right-mid': '┤'
+ , 'middle': '│'
+ }
+ , truncate: '…'
+ , colWidths: []
+ , colAligns: []
+ , style: {
+ 'padding-left': 1
+ , 'padding-right': 1
+ , head: ['red']
+ , border: ['grey']
+ , compact : false
+ }
+ , head: []
+ }, options);
+};
+
+/**
+ * Inherit from Array.
+ */
+
+Table.prototype.__proto__ = Array.prototype;
+
+/**
+ * Width getter
+ *
+ * @return {Number} width
+ * @api public
+ */
+
+Table.prototype.__defineGetter__('width', function (){
+ var str = this.toString().split("\n");
+ if (str.length) return str[0].length;
+ return 0;
+});
+
+/**
+ * Render to a string.
+ *
+ * @return {String} table representation
+ * @api public
+ */
+
+Table.prototype.render
+Table.prototype.toString = function (){
+ var ret = ''
+ , options = this.options
+ , style = options.style
+ , head = options.head
+ , chars = options.chars
+ , truncater = options.truncate
+ , colWidths = options.colWidths || new Array(this.head.length)
+ , totalWidth = 0;
+
+ if (!head.length && !this.length) return '';
+
+ if (!colWidths.length){
+ var all_rows = this.slice(0);
+ if (head.length) { all_rows = all_rows.concat([head]) };
+
+ all_rows.forEach(function(cells){
+ // horizontal (arrays)
+ if (typeof cells === 'object' && cells.length) {
+ extractColumnWidths(cells);
+
+ // vertical (objects)
+ } else {
+ var header_cell = Object.keys(cells)[0]
+ , value_cell = cells[header_cell];
+
+ colWidths[0] = Math.max(colWidths[0] || 0, get_width(header_cell) || 0);
+
+ // cross (objects w/ array values)
+ if (typeof value_cell === 'object' && value_cell.length) {
+ extractColumnWidths(value_cell, 1);
+ } else {
+ colWidths[1] = Math.max(colWidths[1] || 0, get_width(value_cell) || 0);
+ }
+ }
+ });
+ };
+
+ totalWidth = (colWidths.length == 1 ? colWidths[0] : colWidths.reduce(
+ function (a, b){
+ return a + b
+ })) + colWidths.length + 1;
+
+ function extractColumnWidths(arr, offset) {
+ var offset = offset || 0;
+ arr.forEach(function(cell, i){
+ colWidths[i + offset] = Math.max(colWidths[i + offset] || 0, get_width(cell) || 0);
+ });
+ };
+
+ function get_width(obj) {
+ return typeof obj == 'object' && obj.width != undefined
+ ? obj.width
+ : ((typeof obj == 'object' ? utils.strlen(obj.text) : utils.strlen(obj)) + (style['padding-left'] || 0) + (style['padding-right'] || 0))
+ }
+
+ // draws a line
+ function line (line, left, right, intersection){
+ var width = 0
+ , line =
+ left
+ + repeat(line, totalWidth - 2)
+ + right;
+
+ colWidths.forEach(function (w, i){
+ if (i == colWidths.length - 1) return;
+ width += w + 1;
+ line = line.substr(0, width) + intersection + line.substr(width + 1);
+ });
+
+ return applyStyles(options.style.border, line);
+ };
+
+ // draws the top line
+ function lineTop (){
+ var l = line(chars.top
+ , chars['top-left'] || chars.top
+ , chars['top-right'] || chars.top
+ , chars['top-mid']);
+ if (l)
+ ret += l + "\n";
+ };
+
+ function generateRow (items, style) {
+ var cells = []
+ , max_height = 0;
+
+ // prepare vertical and cross table data
+ if (!Array.isArray(items) && typeof items === "object") {
+ var key = Object.keys(items)[0]
+ , value = items[key]
+ , first_cell_head = true;
+
+ if (Array.isArray(value)) {
+ items = value;
+ items.unshift(key);
+ } else {
+ items = [key, value];
+ }
+ }
+
+ // transform array of item strings into structure of cells
+ items.forEach(function (item, i) {
+ var contents = item.toString().split("\n").reduce(function (memo, l) {
+ memo.push(string(l, i));
+ return memo;
+ }, [])
+
+ var height = contents.length;
+ if (height > max_height) { max_height = height };
+
+ cells.push({ contents: contents , height: height });
+ });
+
+ // transform vertical cells into horizontal lines
+ var lines = new Array(max_height);
+ cells.forEach(function (cell, i) {
+ cell.contents.forEach(function (line, j) {
+ if (!lines[j]) { lines[j] = [] };
+ if (style || (first_cell_head && i === 0 && options.style.head)) {
+ line = applyStyles(options.style.head, line)
+ }
+
+ lines[j].push(line);
+ });
+
+ // populate empty lines in cell
+ for (var j = cell.height, l = max_height; j < l; j++) {
+ if (!lines[j]) { lines[j] = [] };
+ lines[j].push(string('', i));
+ }
+ });
+ var ret = "";
+ lines.forEach(function (line, index) {
+ if (ret.length > 0) {
+ ret += "\n" + applyStyles(options.style.border, chars.left);
+ }
+
+ ret += line.join(applyStyles(options.style.border, chars.middle)) + applyStyles(options.style.border, chars.right);
+ });
+
+ return applyStyles(options.style.border, chars.left) + ret;
+ };
+
+ function applyStyles(styles, subject) {
+ if (!subject)
+ return '';
+ styles.forEach(function(style) {
+ subject = colors[style](subject);
+ });
+ return subject;
+ };
+
+ // renders a string, by padding it or truncating it
+ function string (str, index){
+ var str = String(typeof str == 'object' && str.text ? str.text : str)
+ , length = utils.strlen(str)
+ , width = colWidths[index]
+ - (style['padding-left'] || 0)
+ - (style['padding-right'] || 0)
+ , align = options.colAligns[index] || 'left';
+
+ return repeat(' ', style['padding-left'] || 0)
+ + (length == width ? str :
+ (length < width
+ ? pad(str, ( width + (str.length - length) ), ' ', align == 'left' ? 'right' :
+ (align == 'middle' ? 'both' : 'left'))
+ : (truncater ? truncate(str, width, truncater) : str))
+ )
+ + repeat(' ', style['padding-right'] || 0);
+ };
+
+ if (head.length){
+ lineTop();
+
+ ret += generateRow(head, style.head) + "\n"
+ }
+
+ if (this.length)
+ this.forEach(function (cells, i){
+ if (!head.length && i == 0)
+ lineTop();
+ else {
+ if (!style.compact || i<(!!head.length) ?1:0 || cells.length == 0){
+ var l = line(chars.mid
+ , chars['left-mid']
+ , chars['right-mid']
+ , chars['mid-mid']);
+ if (l)
+ ret += l + "\n"
+ }
+ }
+
+ if (cells.hasOwnProperty("length") && !cells.length) {
+ return
+ } else {
+ ret += generateRow(cells) + "\n";
+ };
+ });
+
+ var l = line(chars.bottom
+ , chars['bottom-left'] || chars.bottom
+ , chars['bottom-right'] || chars.bottom
+ , chars['bottom-mid']);
+ if (l)
+ ret += l;
+ else
+ // trim the last '\n' if we didn't add the bottom decoration
+ ret = ret.slice(0, -1);
+
+ return ret;
+};
+
+/**
+ * Module exports.
+ */
+
+module.exports = Table;
+
+module.exports.version = '0.0.1';
diff --git a/lib/utils.js b/lib/utils.js
new file mode 100644
index 0000000..b073f5c
--- /dev/null
+++ b/lib/utils.js
@@ -0,0 +1,84 @@
+
+/**
+ * Repeats a string.
+ *
+ * @param {String} char(s)
+ * @param {Number} number of times
+ * @return {String} repeated string
+ */
+
+exports.repeat = function (str, times){
+ return Array(times + 1).join(str);
+};
+
+/**
+ * Pads a string
+ *
+ * @api public
+ */
+
+exports.pad = function (str, len, pad, dir) {
+ if (len + 1 >= str.length)
+ switch (dir){
+ case 'left':
+ str = Array(len + 1 - str.length).join(pad) + str;
+ break;
+
+ case 'both':
+ var right = Math.ceil((padlen = len - str.length) / 2);
+ var left = padlen - right;
+ str = Array(left + 1).join(pad) + str + Array(right + 1).join(pad);
+ break;
+
+ default:
+ str = str + Array(len + 1 - str.length).join(pad);
+ };
+
+ return str;
+};
+
+/**
+ * Truncates a string
+ *
+ * @api public
+ */
+
+exports.truncate = function (str, length, chr){
+ chr = chr || '…';
+ return str.length >= length ? str.substr(0, length - chr.length) + chr : str;
+};
+
+/**
+ * Copies and merges options with defaults.
+ *
+ * @param {Object} defaults
+ * @param {Object} supplied options
+ * @return {Object} new (merged) object
+ */
+
+function options(defaults, opts) {
+ for (var p in opts) {
+ if (opts[p] && opts[p].constructor && opts[p].constructor === Object) {
+ defaults[p] = defaults[p] || {};
+ options(defaults[p], opts[p]);
+ } else {
+ defaults[p] = opts[p];
+ }
+ }
+ return defaults;
+};
+exports.options = options;
+
+//
+// For consideration of terminal "color" programs like colors.js,
+// which can add ANSI escape color codes to strings,
+// we destyle the ANSI color escape codes for padding calculations.
+//
+// see: http://en.wikipedia.org/wiki/ANSI_escape_code
+//
+exports.strlen = function(str){
+ var code = /\u001b\[(?:\d*;){0,5}\d*m/g;
+ var stripped = ("" + str).replace(code,'');
+ var split = stripped.split("\n");
+ return split.reduce(function (memo, s) { return (s.length > memo) ? s.length : memo }, 0);
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..483172e
--- /dev/null
+++ b/package.json
@@ -0,0 +1,26 @@
+{ "name": "cli-table"
+ , "description": "Pretty unicode tables for the CLI"
+ , "version": "0.3.1"
+ , "author": "Guillermo Rauch <guillermo at learnboost.com>"
+ , "contributors": ["Sonny Michaud <michaud.sonny at gmail.com> (http://github.com/sonnym)"]
+ , "repository": {
+ "type": "git",
+ "url": "https://github.com/Automattic/cli-table.git"
+ }
+ , "keywords": ["cli", "colors", "table"]
+ , "dependencies": {
+ "colors": "1.0.3"
+ }
+ , "devDependencies": {
+ "expresso": "~0.9"
+ , "should": "~0.6"
+ }
+ , "main": "lib"
+ , "files": [
+ "lib"
+ ]
+ , "scripts": {
+ "test": "make test"
+ }
+ , "engines": { "node": ">= 0.2.0" }
+}
diff --git a/test/index.test.js b/test/index.test.js
new file mode 100644
index 0000000..a8faae7
--- /dev/null
+++ b/test/index.test.js
@@ -0,0 +1,257 @@
+
+/**
+ * Module requirements.
+ */
+
+require('should');
+
+var Table = require('../');
+
+/**
+ * Tests.
+ */
+
+module.exports = {
+
+ 'test complete table': function (){
+ var table = new Table({
+ head: ['Rel', 'Change', 'By', 'When']
+ , style: {
+ 'padding-left': 1
+ , 'padding-right': 1
+ , head: []
+ , border: []
+ }
+ , colWidths: [6, 21, 25, 17]
+ });
+
+ table.push(
+ ['v0.1', 'Testing something cool', 'rauchg at gmail.com', '7 minutes ago']
+ , ['v0.1', 'Testing something cool', 'rauchg at gmail.com', '8 minutes ago']
+ );
+
+ var expected = [
+ '┌──────┬─────────────────────┬─────────────────────────┬─────────────────┐'
+ , '│ Rel │ Change │ By │ When │'
+ , '├──────┼─────────────────────┼─────────────────────────┼─────────────────┤'
+ , '│ v0.1 │ Testing something … │ rauchg at gmail.com │ 7 minutes ago │'
+ , '├──────┼─────────────────────┼─────────────────────────┼─────────────────┤'
+ , '│ v0.1 │ Testing something … │ rauchg at gmail.com │ 8 minutes ago │'
+ , '└──────┴─────────────────────┴─────────────────────────┴─────────────────┘'
+ ];
+
+ table.toString().should.eql(expected.join("\n"));
+ },
+
+ 'test width property': function (){
+ var table = new Table({
+ head: ['Cool'],
+ style: {
+ head: [],
+ border: []
+ }
+ });
+
+ table.width.should.eql(8);
+ },
+
+ 'test vertical table output': function() {
+ var table = new Table({ style: {'padding-left':0, 'padding-right':0, head:[], border:[]} }); // clear styles to prevent color output
+
+ table.push(
+ {'v0.1': 'Testing something cool'}
+ , {'v0.1': 'Testing something cool'}
+ );
+
+ var expected = [
+ '┌────┬──────────────────────┐'
+ , '│v0.1│Testing something cool│'
+ , '├────┼──────────────────────┤'
+ , '│v0.1│Testing something cool│'
+ , '└────┴──────────────────────┘'
+ ];
+
+ table.toString().should.eql(expected.join("\n"));
+ },
+
+ 'test cross table output': function() {
+ var table = new Table({ head: ["", "Header 1", "Header 2"], style: {'padding-left':0, 'padding-right':0, head:[], border:[]} }); // clear styles to prevent color output
+
+ table.push(
+ {"Header 3": ['v0.1', 'Testing something cool'] }
+ , {"Header 4": ['v0.1', 'Testing something cool'] }
+ );
+
+ var expected = [
+ '┌────────┬────────┬──────────────────────┐'
+ , '│ │Header 1│Header 2 │'
+ , '├────────┼────────┼──────────────────────┤'
+ , '│Header 3│v0.1 │Testing something cool│'
+ , '├────────┼────────┼──────────────────────┤'
+ , '│Header 4│v0.1 │Testing something cool│'
+ , '└────────┴────────┴──────────────────────┘'
+ ];
+
+ table.toString().should.eql(expected.join("\n"));
+ },
+
+ 'test table colors': function(){
+ var table = new Table({
+ head: ['Rel', 'By'],
+ style: {head: ['red'], border: ['grey']}
+ });
+
+ var off = '\u001b[39m'
+ , red = '\u001b[31m'
+ , orange = '\u001b[38;5;221m'
+ , grey = '\u001b[90m'
+
+ , c256s = orange + 'v0.1' + off;
+
+ table.push(
+ [c256s, 'rauchg at gmail.com']
+ );
+
+ var expected = [
+ grey + '┌──────┬──────────────────┐' + off
+ , grey + '│' + off + red + ' Rel ' + off + grey + '│' + off + red + ' By ' + off + grey + '│' + off
+ , grey + '├──────┼──────────────────┤' + off
+ , grey + '│' + off + ' ' + c256s + ' ' + grey + '│' + off + ' rauchg at gmail.com ' + grey + '│' + off
+ , grey + '└──────┴──────────────────┘' + off
+ ];
+
+ table.toString().should.eql(expected.join("\n"));
+ },
+
+ 'test custom chars': function (){
+ var table = new Table({
+ chars: {
+ 'top': '═'
+ , 'top-mid': '╤'
+ , 'top-left': '╔'
+ , 'top-right': '╗'
+ , 'bottom': '═'
+ , 'bottom-mid': '╧'
+ , 'bottom-left': '╚'
+ , 'bottom-right': '╝'
+ , 'left': '║'
+ , 'left-mid': '╟'
+ , 'right': '║'
+ , 'right-mid': '╢'
+ },
+ style: {
+ head: []
+ , border: []
+ }
+ });
+
+ table.push(
+ ['foo', 'bar', 'baz']
+ , ['frob', 'bar', 'quuz']
+ );
+
+ var expected = [
+ '╔══════╤═════╤══════╗'
+ , '║ foo │ bar │ baz ║'
+ , '╟──────┼─────┼──────╢'
+ , '║ frob │ bar │ quuz ║'
+ , '╚══════╧═════╧══════╝'
+ ];
+
+ table.toString().should.eql(expected.join("\n"));
+ },
+
+ 'test compact shortand': function (){
+ var table = new Table({
+ style: {
+ head: []
+ , border: []
+ , compact : true
+ }
+ });
+
+ table.push(
+ ['foo', 'bar', 'baz']
+ , ['frob', 'bar', 'quuz']
+ );
+
+ var expected = [
+ '┌──────┬─────┬──────┐'
+ , '│ foo │ bar │ baz │'
+ , '│ frob │ bar │ quuz │'
+ , '└──────┴─────┴──────┘'
+ ];
+
+ table.toString().should.eql(expected.join("\n"));
+ },
+
+ 'test compact empty mid line': function (){
+ var table = new Table({
+ chars: {
+ 'mid': ''
+ , 'left-mid': ''
+ , 'mid-mid': ''
+ , 'right-mid': ''
+ },
+ style: {
+ head: []
+ , border: []
+ }
+ });
+
+ table.push(
+ ['foo', 'bar', 'baz']
+ , ['frob', 'bar', 'quuz']
+ );
+
+ var expected = [
+ '┌──────┬─────┬──────┐'
+ , '│ foo │ bar │ baz │'
+ , '│ frob │ bar │ quuz │'
+ , '└──────┴─────┴──────┘'
+ ];
+
+ table.toString().should.eql(expected.join("\n"));
+ },
+
+ 'test decoration lines disabled': function (){
+ var table = new Table({
+ chars: {
+ 'top': ''
+ , 'top-mid': ''
+ , 'top-left': ''
+ , 'top-right': ''
+ , 'bottom': ''
+ , 'bottom-mid': ''
+ , 'bottom-left': ''
+ , 'bottom-right': ''
+ , 'left': ''
+ , 'left-mid': ''
+ , 'mid': ''
+ , 'mid-mid': ''
+ , 'right': ''
+ , 'right-mid': ''
+ , 'middle': ' ' // a single space
+ },
+ style: {
+ head: []
+ , border: []
+ , 'padding-left': 0
+ , 'padding-right': 0
+ }
+ });
+
+ table.push(
+ ['foo', 'bar', 'baz']
+ , ['frobnicate', 'bar', 'quuz']
+ );
+
+ var expected = [
+ 'foo bar baz '
+ , 'frobnicate bar quuz'
+ ];
+
+ table.toString().should.eql(expected.join("\n"));
+ },
+
+};
diff --git a/test/newlines.test.js b/test/newlines.test.js
new file mode 100644
index 0000000..e83114b
--- /dev/null
+++ b/test/newlines.test.js
@@ -0,0 +1,92 @@
+/**
+ * Module requirements.
+ */
+
+require('should');
+
+var Table = require('../');
+
+/**
+ * Tests.
+ */
+
+module.exports = {
+ 'test table with newlines in headers': function() {
+ var table = new Table({
+ head: ['Test', "1\n2\n3"]
+ , style: {
+ 'padding-left': 1
+ , 'padding-right': 1
+ , head: []
+ , border: []
+ }
+ });
+
+ var expected = [
+ '┌──────┬───┐'
+ , '│ Test │ 1 │'
+ , '│ │ 2 │'
+ , '│ │ 3 │'
+ , '└──────┴───┘'
+ ];
+
+ table.toString().should.eql(expected.join("\n"));
+ },
+
+ 'test column width is accurately reflected when newlines are present': function() {
+ var table = new Table({ head: ['Test\nWidth'], style: {head:[], border:[]} });
+ table.width.should.eql(9);
+ },
+
+ 'test newlines in body cells': function() {
+ var table = new Table({style: {head:[], border:[]}});
+
+ table.push(["something\nwith\nnewlines"]);
+
+ var expected = [
+ '┌───────────┐'
+ , '│ something │'
+ , '│ with │'
+ , '│ newlines │'
+ , '└───────────┘'
+ ];
+
+ table.toString().should.eql(expected.join("\n"));
+ },
+
+ 'test newlines in vertical cell header and body': function() {
+ var table = new Table({ style: {'padding-left':0, 'padding-right':0, head:[], border:[]} });
+
+ table.push(
+ {'v\n0.1': 'Testing\nsomething cool'}
+ );
+
+ var expected = [
+ '┌───┬──────────────┐'
+ , '│v │Testing │'
+ , '│0.1│something cool│'
+ , '└───┴──────────────┘'
+ ];
+
+ table.toString().should.eql(expected.join("\n"));
+ },
+
+ 'test newlines in cross table header and body': function() {
+ var table = new Table({ head: ["", "Header\n1"], style: {'padding-left':0, 'padding-right':0, head:[], border:[]} });
+
+ table.push({ "Header\n2": ['Testing\nsomething\ncool'] });
+
+ var expected = [
+ '┌──────┬─────────┐'
+ , '│ │Header │'
+ , '│ │1 │'
+ , '├──────┼─────────┤'
+ , '│Header│Testing │'
+ , '│2 │something│'
+ , '│ │cool │'
+ , '└──────┴─────────┘'
+ ];
+
+ table.toString().should.eql(expected.join("\n"));
+ }
+};
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/node-cli-table.git
More information about the Pkg-javascript-commits
mailing list