pax_global_header 0000666 0000000 0000000 00000000064 15250445340 0014514 g ustar 00root root 0000000 0000000 52 comment=ba5f5924187efd0aeba7258459de3a20d820d899
jhuckaby-pixl-cli-dfc810c/ 0000775 0000000 0000000 00000000000 15250445340 0015525 5 ustar 00root root 0000000 0000000 jhuckaby-pixl-cli-dfc810c/.npmignore 0000664 0000000 0000000 00000000046 15250445340 0017524 0 ustar 00root root 0000000 0000000 .gitignore
node_modules/
test.js
work
jhuckaby-pixl-cli-dfc810c/README.md 0000664 0000000 0000000 00000123126 15250445340 0017011 0 ustar 00root root 0000000 0000000 Table of Contents
- [Overview](#overview)
- [Usage](#usage)
* [Basic Tools](#basic-tools)
+ [Printing](#printing)
- [STDERR](#stderr)
- [Dying](#dying)
+ [Logging](#logging)
+ [Loading and Saving Files](#loading-and-saving-files)
+ [TTY Detection](#tty-detection)
+ [Other Tools](#other-tools)
* [Command-Line Arguments](#command-line-arguments)
+ [Argument Aliases](#argument-aliases)
+ [Verbose Mode](#verbose-mode)
+ [Quiet Mode](#quiet-mode)
* [Prompting The User](#prompting-the-user)
+ [Yes/No Questions](#yesno-questions)
* [Displaying Info Boxes](#displaying-info-boxes)
+ [Centering Text](#centering-text)
+ [Word-Wrapping Text](#word-wrapping-text)
* [Displaying Definition Lists](#displaying-definition-lists)
* [Displaying Dashboard Grids](#displaying-dashboard-grids)
* [Displaying Timeseries Charts](#displaying-timeseries-charts)
* [Displaying Tables](#displaying-tables)
* [Graphical Progress Bars](#graphical-progress-bars)
+ [Configuration](#configuration)
+ [Temporarily Erasing The Bar](#temporarily-erasing-the-bar)
+ [Customizing the Look](#customizing-the-look)
+ [Indeterminite Progress](#indeterminite-progress)
+ [Changing Color Styles](#changing-color-styles)
+ [Automatic Width](#automatic-width)
+ [Keep progress bar visible](#keep-progress-bar-visible)
+ [Unicode or ASCII](#unicode-or-ascii)
+ [Hiding the Cursor](#hiding-the-cursor)
* [Chalk](#chalk)
* [Importing Into Global](#importing-into-global)
- [License](#license)
# Overview
This module provides utilities for creating command-line Node.js apps. Features include automatic parsing of command-line args into simple key/value pairs, prompting the user for information, and displaying graphical info boxes, tables, timeseries charts, and progress bars.
# Usage
Use [npm](https://www.npmjs.com/) to install the module:
```sh
npm install pixl-cli
```
Then use `require()` to load it in your code:
```js
const cli = require('pixl-cli');
```
## Basic Tools
Here are some of the more basic functions provided by the package.
### Printing
A very simple `cli.print()` method is provided, which prints any string to [STDOUT](https://nodejs.org/api/process.html#process_process_stdout). This can be shortened to just `print()` if you import everything into the global namespace (see [Importing Into Global](#importing-into-global) below). Example:
```js
const cli = require('pixl-cli');
cli.global();
print("Hello world!\n");
```
Unlike `console.log()` this does not add an EOL at the end of each string. It works just like the standard `print()` function from other languages. However, a `println()` method is also provided which *does* add an EOL.
Note that `print()` will be silent if `--quiet` mode is enabled. See [Quiet Mode](#quiet-mode) below.
An alternate function is provided for printing verbose output, called `cli.verbose()` (or just `verbose()` if [imported into global](#importing-into-global)). This function also prints a string to [STDOUT](https://nodejs.org/api/process.html#process_process_stdout), but only does so if `--verbose` mode is enabled. Example:
```js
const cli = require('pixl-cli');
cli.global();
verbose("This will only be printed in verbose mode.\n");
```
See [Verbose Mode](#verbose-mode) below for details.
#### STDERR
To print something to [STDERR](https://nodejs.org/api/process.html#process_process_stderr) you can use the `cli.warn()` method. This works similarly as `cli.print()` in that it honors [Quiet Mode](#quiet-mode), does not include a trailing EOL, and gets imported to the global namespace if `cli.global()` is called. Example:
```js
const cli = require('pixl-cli');
cli.global();
warn("This will be printed to STDERR.\n");
```
#### Dying
To print something to [STDERR](https://nodejs.org/api/process.html#process_process_stderr) and exit immediately afterward, you can call `cli.die()` and pass in a message. This will exit with a non-zero code indicating that the process "failed". This method also gets imported to the global namespace if `cli.global()` is called. Example:
```js
const cli = require('pixl-cli');
cli.global();
die("A fatal error occurred.\n");
```
### Logging
To enable logging mode, so all calls to `print()`, `verbose()`, `warn()` and `die()` also get logged to a file, call `cli.setLogFile()` and pass in a path. The file need not exist, but the directory should. Example:
```js
cli.setLogFile( "/let/log/myscript.log" );
```
Note that once the log file is set, everything printed is logged, even if quiet mode is enabled. Additionally, all calls to `cli.verbose()` are also logged, even if `--verbose` mode is not enabled.
The log file format is simply a date/time surrounded by square brackets, followed by a single space, followed by the raw text printed. All color is automatically stripped. Example log snippet:
```
[2019/05/18 18:49:12] Hello there!
[2019/05/18 18:49:13] Good bye!
```
You can also call `cli.log()` to log something directly without also printing it to the console. If you pass an object to `cli.log()` it is serialized to JSON.
### Loading and Saving Files
Simple methods are provided to load and save files to/from strings. These are both synchronous calls. They are `loadFile()` which accepts a file path and returns the contents as a string, and `saveFile()` which accepts a file path and contents as a string. `saveFile()` writes to the specified file, replacing any existing content, and creating the file if necessary. Example of both functions:
```js
const cli = require('pixl-cli');
let contents = cli.loadFile( "my-file.txt" );
cli.print( "File contents: " + contents + "\n" );
contents = "Replacing with new content!";
cli.saveFile( "my-file.txt", contents );
```
If you want to *append* to a file instead of replacing its contents, use `cli.appendFile()`. It accepts the same arguments as `cli.saveFile()`. Example:
```js
contents = "Appending a new line!\n";
cli.appendFile( "my-file.txt", contents );
```
Note: These functions may throw errors if the underlying filesystem operations fail, so it is advisable to wrap them in a try/catch block.
### TTY Detection
To detect whether your script's output is attached to a TTY (meaning, it is attached to a user terminal and not being piped to a file or script), you can call `cli.tty()`. This will return a Boolean `true` or `false`. Example:
```js
if (cli.tty()) {
cli.print("Hello user terminal!\n");
}
```
Specifically, this queries the [STDOUT](https://nodejs.org/api/process.html#process_process_stdout) TTY. Meaning, the script's output is connected to a terminal, but its *input* may still be a pipe of some kind.
To detect the width of the current TTY (user's terminal), you can call `cli.width()`. If a TTY is attached, this will return the current number of characters that will fit in one single line. Example:
```js
let width = cli.width();
cli.print("Your terminal is " + width + " characters wide.\n");
```
### Other Tools
The following utility functions from the [pixl-tools](https://www.npmjs.com/package/pixl-tools) module are also imported, so you can use them directly:
| Function Name | Description |
|---------------|-------------|
| [cli.getTextFromBytes()](https://www.npmjs.com/package/pixl-tools#gettextfrombytes) | Convert a byte count into a human readable string, e.g. `5 MB`. |
| [cli.commify()](https://www.npmjs.com/package/pixl-tools#commify) | Apply commas to a positive integer using US-style formatting, e.g. `1,000,000`. |
| [cli.shortFloat()](https://www.npmjs.com/package/pixl-tools#shortfloat) | Trim floating point decimal to 2-digit precision, unless digits are zeros. |
| [cli.pct()](https://www.npmjs.com/package/pixl-tools#pct) | Return percentage string given arbitrary value and a maximum limit, e.g. '55%'. |
| [cli.zeroPad()](https://www.npmjs.com/package/pixl-tools#zeropad) | Pad an integer with zeros on the left side, up to a specified max. |
| [cli.getTextFromSeconds()](https://www.npmjs.com/package/pixl-tools#gettextfromseconds) | Convert a number of seconds into a human-readable string, e.g. `3 hours`. |
| [cli.getNiceRemainingTime()](https://www.npmjs.com/package/pixl-tools#getniceremainingtime) | Calculate estimated remaining time, given progress and start time. |
| [cli.pluralize()](https://www.npmjs.com/package/pixl-tools#pluralize) | Apply English language pluralization to a word, based on a specified value. |
| [cli.ucfirst()](https://www.npmjs.com/package/pixl-tools#ucfirst) | Upper-case the first character of a string, lower-case the rest. |
In fact, the entire [pixl-tools](https://www.npmjs.com/package/pixl-tools) module is made available to you as `cli.Tools`, so you don't have to import it separately.
## Command-Line Arguments
Any arguments passed to your script on the command-line are parsed using the [pixl-args](https://www.npmjs.com/package/pixl-args) module, and provided as simple key/value pairs in `cli.args`. Example:
```sh
node my-script.js --name "Joseph Huckaby" --city San\ Mateo
```
Then `cli.args` will contain:
```json
{
"name": "Joseph Huckaby",
"city": "San Mateo"
}
```
Several different kinds of arguments are available. You can use single or double-dashes, strings which appear to be integers or floats are parsed as such, any switch without a value is set to `true`, any repeated switches are converted to an array of values, and any values provided without a switch are appended to a special `other` array, which can come before or after all the switches. Here is an example of all these things:
```sh
node my-script.js file1.txt file2.txt --name "Joe" --amount 50 --freq 0.5 -z 1 --verbose --add thing1 --add thing2
```
Then `cli.args` will contain:
```json
{
"other": ["file1.txt", "file2.txt"],
"name": "Joe",
"amount": 50,
"freq": 0.5,
"z": 1,
"verbose": true,
"add": ["thing1", "thing2"]
}
```
Please see the [pixl-args](https://www.npmjs.com/package/pixl-args) module documentation for more details.
### Argument Aliases
You can support argument aliases (e.g. `-v` for `--verbose`) by providing a map to the `mapArgs()` function. Example:
```js
const cli = require('pixl-cli');
cli.mapArgs({
'v': 'verbose',
'q': 'quiet',
'd': 'debug'
});
```
### Verbose Mode
The `--verbose` switch has a special meaning. It is used by the `cli.verbose()` function, and will control whether it outputs anything or not. `cli.verbose()` works just like `cli.print()` except that it only prints if the `--verbose` switch is present on the command-line. Example use:
```js
const cli = require('pixl-cli');
cli.verbose("This will only be printed in verbose mode.\n");
```
### Quiet Mode
The `--quiet` switch also has a special meaning. If passed on the command-line, it will mute all calls to `cli.print()` and of course `cli.verbose()`, meaning they will not output anything at all. This is useful for giving your script a special silent mode, possibly for running in a crontab.
## Prompting The User
To prompt the user for input, you can call `cli.prompt()`. Pass in a string to prompt them with, a default answer, and a callback function which will be fired and passed their answer. This is an asynchronous operation, so beware of code flow. Example:
```js
const cli = require('pixl-cli');
cli.prompt("What is your name?", "", function(name) {
cli.print("Hello " + name + "!\n");
} );
```
If a default string is provided, it is displayed just after the question in square brackets, which is the typical way of hinting a default answer. If the user presses Enter without typing in a value, your default answer will be sent to your callback.
Note that if your script is running without a TTY (i.e. without an attached terminal, as in piped to a file or another script), no prompt is displayed, and your callback is fired immediately and passed your default answer.
### Yes/No Questions
If you just need to ask the user a simple yes/no question, a convenience method is provided. Just call `cli.yesno()`, provide a string to prompt them with, a default answer (`y` or `n`), and a callback. This time your callback is passed Boolean `true` if the user answered yes (or `y` or any word that contains a `y`), or `false` for no or anything non-yes. Example:
```js
cli.yesno("Do you like bacon?", "y", function(yes) {
if (yes) cli.print("You can be my friend.\n");
cli.print("You are dead to me.\n");
} );
```
Note that if your script is running without a TTY (i.e. without an attached terminal, as in piped to a file or another script), no prompt is displayed, and your callback is fired immediately and passed `true` or `false` based on your default answer.
## Displaying Info Boxes
Call `cli.box()` to render a string (or paragraph) of text surrounded by an ASCII art border. Example:
```js
const cli = require('pixl-cli');
cli.print(
cli.box("The quick brown fox jumped over the lazy dog.") + "\n"
);
```
This would produce:
```
┌───────────────────────────────────────────────┐
│ The quick brown fox jumped over the lazy dog. │
└───────────────────────────────────────────────┘
```
Absent any options, the box will be sized to fit your text string, with exactly one space of horizontal space on either side. You can customize this and several other options by passing in an object as the 2nd argument to the `cli.box()` method. Here are all the possible properties:
| Property Name | Description |
|---------------|-------------|
| `width` | An optional fixed width. If specified and the string exceeds the width, it will be word-wrapped. |
| `styles` | An array of [chalk](https://www.npmjs.com/package/chalk) styles or functions to apply to the box border graphics, defaults to `["gray"]`. |
| `hspace` | An optional number of spaces to insert on the left and right sides of the text (defaults to `1`). |
| `vspace` | An optional number of vertical lines to insert above and below the text (defaults to `0`). |
| `indent` | Number of characters to indent the box by (defaults to `0`). |
Example:
```js
let text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
cli.print(
cli.box( text, {
width: 40,
styles: ["magenta", function( text ) { return text.toUpperCase() }],
hspace: 2,
vspace: 1,
indent: 4
} ) + "\n"
);
```
This will produce:
```
┌────────────────────────────────────────────┐
│ │
│ Lorem ipsum dolor sit amet, consectetur │
│ adipisicing elit, sed do eiusmod tempor │
│ incididunt ut labore et dolore magna │
│ aliqua. Ut enim ad minim veniam, quis │
│ nostrud exercitation ullamco laboris │
│ nisi ut aliquip ex ea commodo consequat. │
│ Duis aute irure dolor in reprehenderit │
│ in voluptate velit esse cillum dolore eu │
│ fugiat nulla pariatur. Excepteur sint │
│ occaecat cupidatat non proident, sunt in │
│ culpa qui officia deserunt mollit anim │
│ id est laborum. │
│ │
└────────────────────────────────────────────┘
```
### Centering Text
To center align text within a fixed width, you can use the `cli.center()` method. This accepts a string which may be single or multiple lines, and an optional width in characters. If you omit the width, it uses the length of the longest line. Example:
```js
cli.print(
cli.center(
"This Is A Title\n" +
"The quick brown fox jumped over the lazy dog."
) + "\n"
);
```
This would produce:
```
┌───────────────────────────────────────────────┐
│ This Is A Title │
│ The quick brown fox jumped over the lazy dog. │
└───────────────────────────────────────────────┘
```
Of course, you can also just use `cli.center()` on its own, without wrapping it in a call to `cli.box()`.
### Word-Wrapping Text
To word-wrap text when using `cli.box()` simply specify a `width` property in your options object. Your string will be word-wrapped to fit into the specified width. However, there is also a low-level `cli.wrap()` function you can call directly, which simply wraps text at a specified width. Example use:
```js
cli.print(
cli.wrap( text, 40 ) + "\n"
);
```
This would produce:
```
Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim
id est laborum.
```
## Displaying Definition Lists
Call `cli.defList()` to render a two-column list of labels and values inside a box. Labels are bold by default, values are plain, and no vertical border is drawn between the columns. Colons are added to labels automatically when needed. Lines will automatically truncate with ellipsis as needed.
```js
const cli = require('pixl-cli');
let event = {
id: "emm2wtlsxrtjz8v4",
title: "Simple Shell Test",
category: "general",
username: "admin"
};
cli.println( cli.defList([
[ "Event ID", event.id ],
[ "Title", event.title ],
[ "Category", event.category ],
[ "Author", event.username ]
], {
labelStyles: ["yellow", "bold"],
textStyles: ["green"],
indent: 1
}) );
```
This produces a definition list like this, with colors when the terminal supports them:
```
┌─────────────────────────────┐
│ Event ID: emm2wtlsxrtjz8v4 │
│ Title: Simple Shell Test │
│ Category: general │
│ Author: admin │
└─────────────────────────────┘
```
The label and value columns are left-aligned. When the box would exceed the attached terminal width, long values are shortened with an ellipsis. The complete label column is preserved whenever possible. The `indent` is treated as a horizontal margin on both sides when calculating the available width.
You can customize the definition list with these options:
| Property Name | Description |
|---------------|-------------|
| `labelStyles` | An array of [chalk](https://www.npmjs.com/package/chalk) styles or functions for labels. Defaults to `["bold"]`. |
| `textStyles` | An array of styles or functions for values. Defaults to `[]`. |
| `borderStyles` | An array of styles or functions for the box border. Defaults to `["gray"]`. |
| `indent` | Horizontal margin in characters on both sides of the box. Defaults to `0`. |
| `gap` | Spaces between the label and value columns. Defaults to `1`. |
| `hspace` | Spaces between the content and each side of the box. Defaults to `1`. |
| `vspace` | Empty lines above and below the list inside the box. Defaults to `0`. |
## Displaying Dashboard Grids
Call `cli.dashGrid()` to render a responsive grid of dashboard units. Each unit contains a centered value and label, and all units have the same dimensions regardless of their content. Pass an array of `[label, value]` pairs:
```js
const cli = require('pixl-cli');
cli.println( cli.dashGrid([
[ "Conductors", 1 ],
[ "Servers", 2 ],
[ "Current Alerts", 0 ],
[ "Active Jobs", 0 ],
[ "Job Success Rate", "100%" ],
[ "Avg. Job Elapsed", "31 sec" ]
], {
minCols: 3,
maxCols: 5,
gap: 1,
valueStyles: ["bold", "green"]
}) );
```
At a width of 62 columns, the first row looks like this:
```
┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ 1 │ │ 2 │ │ 0 │
│ │ │ │ │ │
│ Conductors │ │ Servers │ │ Current Alerts │
└──────────────────┘ └──────────────────┘ └──────────────────┘
```
The grid uses the current terminal width and flows additional units onto new rows. An incomplete final row ends after its last unit. Labels and values are limited to one line and automatically shortened with an ellipsis when necessary. ANSI styles and emoji are measured by their terminal display width.
You can customize the dashboard grid with these options:
| Property Name | Description |
|---------------|-------------|
| `width` | Overall layout width, including horizontal margins. Defaults to `cli.width()`, or `80` when no terminal width is available. |
| `unitWidth` | Target outer width used to select the responsive column count. Defaults to `20`. |
| `minCols` | Preferred minimum number of columns. Defaults to `3`. Extremely narrow terminals may use fewer to avoid overflow. |
| `maxCols` | Maximum number of columns. Defaults to `5`. |
| `gap` | Horizontal spaces between units. Grid rows use `gap - 1` blank lines. Defaults to `1`, producing no vertical blank line. |
| `indent` | Horizontal margin in characters on both sides of the grid. Defaults to `0`. |
| `valueStyles` | An array of [chalk](https://www.npmjs.com/package/chalk) styles or functions for values. Defaults to `["bold"]`. |
| `labelStyles` | An array of styles or functions for labels. Defaults to `["gray"]`. |
| `borderStyles` | An array of styles or functions for unit borders. Defaults to `["gray"]`. |
## Displaying Timeseries Charts

Call `cli.chart()` to render a filled timeseries area chart using Unicode Braille characters. Each character contains two horizontal samples and four vertical dots, which gives the chart more detail than ordinary text cells can provide.
Pass the chart an array of objects containing an `x` Epoch timestamp in seconds and a numeric `y` value:
```js
const cli = require('pixl-cli');
cli.println( cli.chart({
title: "App Requests per sec",
dataType: "integer",
dataSuffix: "/sec",
height: 14,
indent: 1,
color: "green",
data: [
{ x: 1634269860, y: 39 },
{ x: 1634269920, y: 42 },
{ x: 1634269980, y: 53 },
{ x: 1634270040, y: 40 },
{ x: 1634270100, y: 81 },
{ x: 1634270160, y: 43 }
]
}) );
```
The chart automatically fills the available terminal width. The `indent` option reserves the same horizontal margin on both sides, and defaults to one character. An explicit `width` is useful for tests and redirected output, where a terminal width may not be available.
The Y axis always starts at zero and ends at the highest data value. Set `minVertScale` to enforce a minimum upper bound, such as `100` for a CPU percentage chart. The two Y-axis labels are drawn inside the frame, while the first and last timestamps are shown below it using the current system locale and time zone.
Sparse datasets are smoothed using monotone cubic interpolation. Dense datasets are reduced to two samples per Braille character using linear interpolation. A single sample produces axis labels without chart data, and an empty dataset produces only the frame.
Set `delta` to `true` to graph the difference between each sample and the one before it. This is useful for counters that accumulate over time. The first sample copies the second sample's computed delta so the chart still covers the complete time range. Set `deltaMinValue` to a number such as `0` to clamp raw deltas before rendering. Set `divideByDelta` to `true` to divide each delta by the number of seconds between its current and previous timestamps, producing a per-second rate.
You can customize the chart with these options:
| Property Name | Description |
|---------------|-------------|
| `data` | Array of `{ x, y }` samples. The `x` values must be Epoch timestamps in seconds. Defaults to `[]`. |
| `title` | Optional title displayed above the frame. |
| `width` | Overall layout width, including horizontal margins. Defaults to `cli.width()`, or `80` when no terminal width is available. |
| `height` | Number of Braille rows inside the frame. Defaults to `14`, with a minimum of `2`. |
| `indent` | Horizontal margin in characters on both sides of the chart. Defaults to `1`. |
| `dataType` | Y-axis format: `integer`, `float`, `bytes`, `seconds`, or `milliseconds`. Defaults to `integer`. |
| `dataSuffix` | Optional text appended to both Y-axis labels. Defaults to an empty string. |
| `floatPrecision` | Maximum decimal precision used by compact value formats. Defaults to `2`. |
| `minVertScale` | Minimum value for the top of the Y axis. Defaults to `0`. |
| `delta` | Render each Y value as its difference from the previous sample. Defaults to `false`. |
| `deltaMinValue` | Optional minimum for computed delta values, commonly `0`. Defaults to `false`, which disables clamping. |
| `divideByDelta` | Divide each computed delta by its elapsed time in seconds. Defaults to `false`. |
| `color` | Chalk style name, style function, or array of styles for the chart data. Defaults to no style. |
| `borderStyles` | Array of styles or functions for the frame. Defaults to `["gray"]`. |
| `labelStyles` | Array of styles or functions for both axes. Defaults to `["gray"]`. |
| `titleStyles` | Array of styles or functions for the title. Defaults to `["cyan", "bold"]`. |
## Displaying Tables

Calling `cli.table()` produces a nicely formatted ASCII table with a grid of data. It expects an array of rows, and each element should be an array of columns. The first row will be rendered as the "header" and use a different style. Example:
```js
const cli = require('pixl-cli');
let rows = [
[ "Username", "Full Name", "Email Address", "Status" ],
[ "jhuckaby", "Joseph Huckaby", "jhuckaby@test.com", "Administrator" ],
[ "tsmith", "Tom Smith", "smith@email.com", "Active" ],
[ "dcook", "David Cook", "dcook@hotmail.com", "Suspended" ]
];
cli.print(
cli.table(rows) + "\n"
);
```
This would produce the following output:
```
┌──────────┬────────────────┬───────────────────┬───────────────┐
│ Username │ Full Name │ Email Address │ Status │
├──────────┼────────────────┼───────────────────┼───────────────┤
│ jhuckaby │ Joseph Huckaby │ jhuckaby@test.com │ Administrator │
│ tsmith │ Tom Smith │ smith@email.com │ Active │
│ dcook │ David Cook │ dcook@hotmail.com │ Suspended │
└──────────┴────────────────┴───────────────────┴───────────────┘
```
Of course, if your Terminal supports ANSI color and font styles, the header would be bold and yellow, the text would be cyan, and the borders would be gray. You can customize the styles by passing an object as the second argument to `cli.table()` with the following keys:
| Property Name | Description |
|---------------|-------------|
| `headerStyles` | An array of [chalk](https://www.npmjs.com/package/chalk) styles or functions to apply to the header cell text. |
| `textStyles` | An array of [chalk](https://www.npmjs.com/package/chalk) styles or functions to apply to the table cell text. |
| `borderStyles` | An array of [chalk](https://www.npmjs.com/package/chalk) styles or functions to apply to the border graphics. |
| `indent` | Number of characters to indent the table by (defaults to `0`). |
| `autoFit` | Automatically "fit" table into the available terminal width, if it is too wide. This will add ellipsis to longer columns as required. |
Here is an example specifying all the possible options:
```js
cli.print(
cli.table(rows, {
headerStyles: ["bold", "yellow"],
textStyles: ["cyan", function( text ) { return text.toUpperCase() }],
borderStyles: ["gray"],
indent: 0,
autoFit: true
}) + "\n"
);
```
Each of the three style keys should be set to an array of style names supported by the [chalk](https://www.npmjs.com/package/chalk) module or a custom function to support different text transformations. These are arrays because each component may contain multiple styles. For example, the `headerStyles` is rendered with both `yellow` and `bold` by default.
Note that each text cell must only be one line (multi-line is not supported).
## Graphical Progress Bars

To display a graphical ASCII progress bar, first call `cli.progress.start()` to display the progress bar and begin animation. Then, as you make progress on your operation, call `cli.progress.update()` and pass in a number between `0.0` and `1.0` representing the total progress (the maximum is configurable, see below). When your operation is complete, call `cli.progress.end()`. That's it!
Here is a simple example:
```js
const cli = require('pixl-cli');
let amount = 0;
cli.progress.start();
setInterval( function() {
amount += 0.0005;
cli.progress.update( amount );
if (amount >= 1.0) {
cli.progress.end();
cli.print("\tThe end!\n\n");
process.exit(0);
}
}, 10 );
```
Note that the progress bar will redraw itself every 100ms (configurable), so you don't need to worry about calling `cli.progress.update()` constantly. You only really need to call it when the amount changes.
Note that if your script is running without a TTY (i.e. without an attached terminal, as in piped to a file or another script), the progress bar is completely no-op'ed. Meaning, it doesn't display anything, and all the API calls do nothing and don't throw any errors.
### Configuration
Calls to `cli.progress.start()` and `cli.progress.update()` accept an object containing any of the following properties:
| Property Name | Description |
|---------------|-------------|
| `amount` | Initial amount to display in progress bar (between 0 and `max`). Defaults to `0.0`. |
| `max` | Maximum amount which represents 100% of bar being filled. Defaults to `1.0`. |
| `text` | Optional custom text string to display on right side of progress bar. |
| `width` | The width of the actual progress bar in characters (defaults to `30`). |
| `indent` | Number of characters to indent the progress bar by (defaults to `0`). |
| `freq` | The animation update frequency in milliseconds (defaults to `100`). |
| `color` | Boolean (true), specifies whether to use [chalk](https://www.npmjs.com/package/chalk) colors or not. |
| `unicode` | Boolean (true), specifies whether to use Unicode characters or basic ASCII. |
| `remain` | Boolean (true), specifies whether to show the estimated remaining time or not. |
| `spinner` | An array of characters to use as the spinning animation. |
| `braces` | An array of two characters to use as the left and right braces around the bar. |
| `filling` | An array of characters to use as the bar chunk filling progression. |
| `filled` | A single character representing one filled bar chunk, defaults to "⣿". |
| `styles` | A set of color styles to use (see [Changing Color Styles](#changing-color-styles) below). |
| `pct` | Show percentage (defaults to `true`). |
If you call `cli.progress.update()` and pass in a number, the library assumes you are just updating the `amount`. However, if you pass in an object, all the specified properties are updated.
### Temporarily Erasing The Bar
If you need to temporarily erase the progress bar, presumably to write some lines of output to the console, you can call the `cli.progress.erase()` method. To reduce flickering, you can force a redraw just after outputting your lines by calling `cli.progress.draw()`.
However, if you use the built-in CLI `print()`, `println()`, `verbose()` or `verboseln()` functions, the progress bar is automatically hidden and redrawn for you. You should only need to manually erase and redraw it if you are calling some other code that outputs to STDOUT or STDERR. Example:
```js
cli.progress.erase();
console.log( some_large_object );
cli.progress.draw();
```
### Customizing the Look
The progress bar uses specific Unicode characters to achieve its look. You can customize these by passing in the following keys to your call to `cli.progress.start()`:
```js
cli.progress.start({
spinner: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'],
braces: ['⟦', '⟧'],
filling: [' ', '⡀', '⡄', '⡆', '⡇', '⣇', '⣧', '⣷'],
filled: '⣿'
});
```
The `spinner` array contains all the characters used for the 1-character spinning animation at the left side of the bar. They are picked in sequence for each tick (`freq` milliseconds). To disable the spinner, set this to an array containing one empty space character.
The `braces` array should contain exactly two elements: one for the left side, and one for the right side of the bar. By default these are stylized Unicode brackets, but can be replaced with any characters you want.
The `filling` array contains progressive characters representing a partial bar chunk as it fills up, before it is replaced with the `filled` character. To disable the partial chunk blocks, set this to an array containing one empty space character.
Finally, the `filled` is a single character (not an array) which represents a filled chunk of the progress bar. This is what replaces the `filling` animation once it completes a block.
If you switch to [plain ASCII mode](#unicode-or-ascii) by setting the `unicode` property to false, this is the same as passing the following:
```js
cli.progress.start({
spinner: ['|', '/', '-', "\\"],
braces: ['[', ']'],
filling: [' ', '.', ':'],
filled: '#'
});
```
### Indeterminite Progress
For indeterminate progress, simply set the `amount` to the `max`. If these two values are identical, the progress bar is shown in an "indeterminate" state (e.g. the filled portion of the bar is drawn in a different color, default `gray`). This is to handle cases where a job "sits at 100%" but isn't quite complete, and also handle deliberate intermintate jobs (i.e. your code can just set the `amount` to the `max` to show an interminate bar). This also hides the time remaining.
For an additional UI hint, if you know your job is going to be indeterminate from the start, set the `pct` option to `false` to hide the percentage display. Otherwise it'll show "100%" during indeterminacy.
### Changing Color Styles
The progress bar uses a set of color styles from the [chalk](https://www.npmjs.com/package/chalk) module or a custom function for the spinner, braces, bar chunks, percentage display, remaining time, and your custom text (if applicable). To customize these, pass in a `styles` object with the following keys:
```js
cli.progress.start({
styles: {
spinner: ['bold', 'green'],
braces: ['gray'],
bar: ['bold', 'cyan'],
indeterminate: ['gray'],
pct: ['bold', 'yellow'],
remain: ['green'],
text: [function( text ) { return text.toUpperCase() }]
}
});
```
Each key should be set to an array of styles supported by the [chalk](https://www.npmjs.com/package/chalk) module or a function. These are arrays because each component may contain multiple styles. For example, by default the `spinner`, `bar` and `pct` are styled with both a color and `bold`.
The `indeterminate` style is applied to the filled portion of the bar when the `amount` is exactly equal to the `max`.
### Automatic Width
To set the progress bar size automatically to take up the full width of your Terminal window, you can use the `cli.width()` function. Just subtract 27 characters from it (possibly more if you use `indent` or `text`) to account for the spinner, braces, percentage and remaining time:
```js
cli.progress.start({
width: cli.width() - 27
});
```
To handle dynamically resizing Terminal windows, just reset the width in each of your calls to `cli.progress.update()`:
```js
cli.progress.update({
amount: MY_CURRENT_AMOUNT,
width: cli.width() - 27
});
```
### Keep progress bar visible
To keep the progress bar visible after it reaches 100%, just pass the value `false` to the
`cli.progress.end()` function. This will prevent it from being erased from the screen.
### Unicode or ASCII
By default the progress bar is rendered using various Unicode characters:
```
⠼ ⟦⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ ⟧ 53% (11 sec remain)
```
However, if you set the `unicode` parameter to `false`, these will be replaced with standard ASCII equivalents:
```
/ [################: ] 55% (10 sec remain)
```
You can change the exact characters used as well. See the [Customizing the Look](#customizing-the-look) section.
### Hiding the Cursor
While the progress bar is active, your terminal cursor is hidden, and then restored when `cli.progress.end()` is called, or when your process exits. This is all handled automatically, except when your process dies unexpectedly, such as via an uncaught Ctrl-C ([SIGINT](https://nodejs.org/api/process.html#process_signal_events)), uncaught termination signal, or a hard crash. When these happen, the progress bar has no chance to restore the cursor, so it ends up remaining hidden until you close and reopen your terminal window.
To fix this, you have two options. You can either catch the [signal](https://nodejs.org/api/process.html#process_signal_events) or [crash](https://nodejs.org/api/process.html#process_event_uncaughtexception) yourself, and call `cli.progress.end()`, or you can let the library handle it for you:
When calling `cli.progress.start()` there are some optional arguments which activate special behavior for the terminal cursor restoration. They are:
| Property Name | Description |
|---------------|-------------|
| `catchInt` | When set to `true`, this will hook [SIGINT](https://nodejs.org/api/process.html#process_signal_events) and call `cli.progress.end()` to restore the cursor. |
| `catchTerm` | When set to `true`, this will hook [SIGTERM](https://nodejs.org/api/process.html#process_signal_events) and call `cli.progress.end()` to restore the cursor. |
| `catchCrash` | When set to `true`, this will hook [uncaughtException](https://nodejs.org/api/process.html#process_event_uncaughtexception) and call `cli.progress.end()` to restore the cursor. |
| `exitOnSig` | When set to `true`, this will also call [process.exit()](https://nodejs.org/api/process.html#process_process_exit_code) (with the appropriate status code) after handling the SIGINT or SIGTERM signal. |
Example:
```js
cli.progress.start({
catchInt: true,
catchTerm: true,
catchCrash: true,
exitOnSig: true
});
```
**Note:** You should only need `exitOnSig` if you are **not** already handling the [signal](https://nodejs.org/api/process.html#process_signal_events) in your own code, and calling [process.exit()](https://nodejs.org/api/process.html#process_process_exit_code) yourself.
## Chalk
All the style methods from the wonderful [chalk](https://www.npmjs.com/package/chalk) module are automatically imported, so you can use them like this:
```js
const cli = require('pixl-cli');
cli.print( cli.bold.red("This is bold and red!") + "\n" );
```
## Importing Into Global
You can optionally import some of the most commonly used methods into the global namespace, so you can use them from anywhere without having to prefix them. The method list includes `print()`, `verbose()`, a bunch of others (see below), as well as all the [chalk](https://www.npmjs.com/package/chalk) style methods. Example:
```js
const cli = require('pixl-cli');
cli.global();
print( box( bold.red("This is bold, red and in a box!") ) + "\n" );
```
The full list of methods and objects that are imported are:
- `print()`
- `println()`
- `verbose()`
- `warn()`
- `die()`
- `loadFile()`
- `saveFile()`
- `appendFile()`
- `prompt()`
- `yesno()`
- `table()`
- `box()`
- `defList()`
- `dashGrid()`
- `wrap()`
- `center()`
- `commify()`
- `shortFloat()`
- `pct()`
- `pluralize()`
- `ucfirst()`
- `progress`
- `args`
# License
**The MIT License**
*Copyright (c) 2016 - 2019 Joseph Huckaby.*
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.
jhuckaby-pixl-cli-dfc810c/chart.js 0000664 0000000 0000000 00000037256 15250445340 0017201 0 ustar 00root root 0000000 0000000 // Unicode Braille timeseries area charts for pixl-cli.
// Copyright (c) 2016 - 2026 Joseph Huckaby
// Released under the MIT License
var Width = require('./width');
var stringWidth = Width.stringWidth;
var numberFormatter = new Intl.NumberFormat();
// Braille characters contain two columns of four dots. The Unicode bit order
// is not linear across the rows, so keep an explicit map for each column.
var brailleBits = {
left: [0x01, 0x02, 0x04, 0x40],
right: [0x08, 0x10, 0x20, 0x80]
};
function wholeNumber(value, defaultValue, minimum) {
// Normalize layout options to safe, whole terminal cells.
value = Math.floor( Number(value) );
if (!isFinite(value)) value = defaultValue;
return Math.max(minimum, value);
}
function styleList(value, defaultValue) {
// The rest of pixl-cli uses arrays of chalk style names or functions. Also
// accept one style directly because chart colors are commonly a single name.
if (typeof(value) == 'undefined') return defaultValue;
if (!value) return [];
return Array.isArray(value) ? value : [value];
}
function prepareData(data) {
// Copy and normalize the caller's data without modifying their objects.
// Invalid samples are ignored so a malformed row cannot crash a report.
var rows = [];
(data || []).forEach( function(row) {
if (!row || (typeof(row) != 'object')) return;
var x = Number(row.x);
var y = Number(row.y);
if (!isFinite(x) || !isFinite(y)) return;
rows.push({ x: x, y: y });
} );
// Interpolation requires ascending, unique X coordinates. If two samples
// share a timestamp, preserve the last one supplied by the caller.
rows.sort( function(a, b) { return a.x - b.x; } );
var uniqueRows = [];
rows.forEach( function(row) {
var last = uniqueRows[ uniqueRows.length - 1 ];
if (last && (last.x == row.x)) uniqueRows[ uniqueRows.length - 1 ] = row;
else uniqueRows.push(row);
} );
return uniqueRows;
}
function applyDelta(rows, args) {
// Match pixl-chart's delta preprocessing exactly. Work backward so each
// subtraction still sees the unmodified value from the previous sample.
if (!args.delta || !rows.length) return;
var deltaMinValue = false;
if (('deltaMinValue' in args) && (args.deltaMinValue !== false)) {
deltaMinValue = Number(args.deltaMinValue);
if (!isFinite(deltaMinValue)) deltaMinValue = false;
}
for (var idx = rows.length - 1; idx >= 1; idx--) {
rows[idx].y -= rows[idx - 1].y;
// Clamp the raw delta before converting it into a rate. This ordering is
// important when deltaMinValue and divideByDelta are both enabled.
if ((deltaMinValue !== false) && (rows[idx].y < deltaMinValue)) {
rows[idx].y = deltaMinValue;
}
if (args.divideByDelta) {
rows[idx].y /= ((rows[idx].x - rows[idx - 1].x) || 1);
}
}
// There is no preceding value for the first sample. pixl-chart fills this
// gap by copying the second computed delta, keeping the original time range.
rows[0].y = 0;
if (rows.length > 1) rows[0].y = rows[1].y;
}
function createLinearInterpolant(xs, ys) {
// Create a simple piecewise-linear interpolator for reducing large datasets.
// This samples the complete time range uniformly into the available dots.
if (!xs.length) return function() { return 0; };
if (xs.length == 1) return function() { return ys[0]; };
return function(x) {
if (x <= xs[0]) return ys[0];
if (x >= xs[xs.length - 1]) return ys[ys.length - 1];
// Locate the two source samples surrounding this output timestamp.
var low = 0;
var high = xs.length - 1;
while ((high - low) > 1) {
var mid = Math.floor( (low + high) / 2 );
if (xs[mid] <= x) low = mid;
else high = mid;
}
var ratio = (x - xs[low]) / (xs[high] - xs[low]);
return ys[low] + ((ys[high] - ys[low]) * ratio);
};
}
function createInterpolant(xs, ys) {
// Adapted from: https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
// This is copied from pixl-chart. The xs array MUST be pre-sorted!
var i, length = xs.length;
// Deal with length issues.
if (length != ys.length) throw new Error('Need an equal count of xs and ys.');
if (length === 0) return function() { return 0; };
if (length === 1) {
var result = +ys[0];
return function() { return result; };
}
// Get consecutive differences and slopes.
var dys = [];
var dxs = [];
var ms = [];
for (i = 0; i < length - 1; i++) {
var dx = xs[i + 1] - xs[i];
var dy = ys[i + 1] - ys[i];
dxs.push(dx);
dys.push(dy);
ms.push(dy / dx);
}
// Get degree-1 coefficients.
var c1s = [ms[0]];
for (i = 0; i < dxs.length - 1; i++) {
var m = ms[i];
var mNext = ms[i + 1];
if ((m * mNext) <= 0) {
c1s.push(0);
}
else {
var dxCurrent = dxs[i];
var dxNext = dxs[i + 1];
var common = dxCurrent + dxNext;
c1s.push( 3 * common / (((common + dxNext) / m) + ((common + dxCurrent) / mNext)) );
}
}
c1s.push( ms[ms.length - 1] );
// Get degree-2 and degree-3 coefficients.
var c2s = [];
var c3s = [];
for (i = 0; i < c1s.length - 1; i++) {
var c1 = c1s[i];
var slope = ms[i];
var invDx = 1 / dxs[i];
var commonValue = c1 + c1s[i + 1] - slope - slope;
c2s.push( (slope - c1 - commonValue) * invDx );
c3s.push( commonValue * invDx * invDx );
}
// Return the interpolation function.
return function(x) {
// The rightmost point in the dataset should give an exact result.
var idx = xs.length - 1;
if (x == xs[idx]) return ys[idx];
// Search for the interval containing x.
var low = 0;
var mid = 0;
var high = c3s.length - 1;
while (low <= high) {
mid = Math.floor( 0.5 * (low + high) );
var xHere = xs[mid];
if (xHere < x) low = mid + 1;
else if (xHere > x) high = mid - 1;
else return ys[mid];
}
idx = Math.max(0, high);
// Interpolate the value from the precomputed coefficients.
var diff = x - xs[idx];
var diffSq = diff * diff;
return ys[idx] + (c1s[idx] * diff) + (c2s[idx] * diffSq) + (c3s[idx] * diff * diffSq);
};
}
function resampleData(rows, sampleCount) {
// Every Braille cell represents two uniformly spaced timestamps. Smooth a
// sparse series with monotone cubic interpolation, and reduce a dense series
// with linear interpolation as requested by the chart API.
if ((rows.length < 2) || (sampleCount < 1)) return [];
var xs = rows.map( function(row) { return row.x; } );
var ys = rows.map( function(row) { return row.y; } );
var interpolate = (rows.length < sampleCount) ?
createInterpolant(xs, ys) : createLinearInterpolant(xs, ys);
var xMin = xs[0];
var xMax = xs[ xs.length - 1 ];
var values = [];
for (var idx = 0; idx < sampleCount; idx++) {
var ratio = (sampleCount == 1) ? 0 : (idx / (sampleCount - 1));
values.push( interpolate(xMin + ((xMax - xMin) * ratio)) );
}
return values;
}
function getColumnMask(value, rowIndex, height, yMax, side) {
// Quantize one sample to the chart's four-dots-per-line vertical resolution,
// then turn on every dot from the baseline up to the sample height.
if (!(yMax > 0)) return 0;
var totalDots = height * 4;
var ratio = Math.max(0, Math.min(Number(value) / yMax, 1));
var filledDots = Math.round(ratio * totalDots);
var firstFilledDot = totalDots - filledDots;
var rowStart = rowIndex * 4;
var mask = 0;
for (var dot = 0; dot < 4; dot++) {
if ((rowStart + dot) >= firstFilledDot) mask |= brailleBits[side][dot];
}
return mask;
}
function renderBrailleRow(values, rowIndex, height, width, yMax) {
// Combine each adjacent pair of samples into one Unicode Braille character.
var output = '';
for (var col = 0; col < width; col++) {
var mask = getColumnMask(values[col * 2], rowIndex, height, yMax, 'left');
mask |= getColumnMask(values[(col * 2) + 1], rowIndex, height, yMax, 'right');
output += mask ? String.fromCharCode(0x2800 + mask) : ' ';
}
return output;
}
function shortFloat(value, precision) {
// Match pixl-chart's compact floating-point axis labels.
precision = precision || 2;
var power = Math.pow(10, precision);
value = Math.round(parseFloat(value || 0) * power) / power;
if (value == Math.round(value)) value += '.0';
return '' + value;
}
function getTextFromBytes(value, precision) {
// Format byte quantities using binary units and compact decimals.
precision = precision || 10;
var prefix = '';
value = Math.floor(value);
if (value < 0) {
value = -value;
prefix = '-';
}
if (value < 1024) return prefix + value + ' B';
value = Math.floor((value / 1024) * precision) / precision;
if (value < 1024) return prefix + value + ' K';
value = Math.floor((value / 1024) * precision) / precision;
if (value < 1024) return prefix + value + ' MB';
value = Math.floor((value / 1024) * precision) / precision;
if (value < 1024) return prefix + value + ' GB';
value = Math.floor((value / 1024) * precision) / precision;
return prefix + value + ' TB';
}
function getTextFromSeconds(value, abbreviated) {
// Format elapsed seconds using the largest practical unit.
var prefix = '';
if (value < 0) {
value = -value;
prefix = '-';
}
var unit = abbreviated ? 'sec' : 'second';
var amount = value;
if (value > 59) {
unit = abbreviated ? 'min' : 'minute';
amount = value = value / 60;
if (value > 59) {
unit = abbreviated ? 'hr' : 'hour';
amount = value = value / 60;
if (value > 23) {
unit = 'day';
amount = value / 24;
}
}
}
amount = (amount < 10) ? Math.floor(amount * 10) / 10 : Math.floor(amount);
var output = amount + ' ' + unit;
if ((amount != 1) && !abbreviated) output += 's';
return prefix + output;
}
function formatDataValue(value, dataType, suffix, floatPrecision) {
// Format Y-axis labels using the same core rules as pixl-chart.
var output = value;
switch (dataType) {
case 'bytes':
output = getTextFromBytes( Math.floor(value), Math.pow(10, floatPrecision - 1) );
break;
case 'seconds':
output = getTextFromSeconds(value, true);
break;
case 'milliseconds':
output = (Math.abs(value) < 1000) ? Math.floor(value) + ' ms' : getTextFromSeconds(value / 1000, true);
break;
case 'integer':
if (Math.abs(value) >= 1000000000) output = Math.floor(value / 1000000000) + 'B';
else if (Math.abs(value) >= 1000000) output = Math.floor(value / 1000000) + 'M';
else if (Math.abs(value) >= 10000) output = Math.floor(value / 1000) + 'K';
else output = numberFormatter.format( Math.floor(value) );
break;
default:
output = shortFloat(value, floatPrecision);
break;
}
if (suffix) output += suffix;
return '' + output;
}
function getDateRange(start, end) {
// Match pixl-chart's automatic date format selection thresholds.
var range = end - start;
if (range > 2764800) return 'year';
if (range > 172800) return 'month';
if (range > 43200) return 'day';
if (range > 600) return 'hour';
return 'minute';
}
function formatDate(epoch, range) {
// Use the process locale and time zone by leaving both unspecified.
var dateStyles = {
minute: { hour: 'numeric', hour12: false, minute: '2-digit', second: '2-digit' },
hour: { hour: 'numeric', hour12: true, minute: '2-digit' },
day: { hour: 'numeric', hour12: true },
month: { month: 'short', day: 'numeric' },
year: { month: 'short', day: 'numeric' }
};
return new Date(epoch * 1000).toLocaleString(undefined, dateStyles[range]);
}
function renderAxisLabels(left, right, width) {
// Keep exactly two labels on one line. On narrow terminals, divide the line
// between them and truncate each side without allowing an overflow.
if (width < 1) return '';
left = '' + left;
right = '' + right;
if ((stringWidth(left) + stringWidth(right) + 1) > width) {
var leftWidth = Math.floor((width - 1) / 2);
var rightWidth = Math.max(0, width - leftWidth - 1);
left = Width.truncate(left, leftWidth, leftWidth > 1 ? '…' : '');
right = Width.truncate(right, rightWidth, rightWidth > 1 ? '…' : '');
}
return left + new Array(Math.max(0, width - stringWidth(left) - stringWidth(right)) + 1).join(' ') + right;
}
function overtypeLabel(cli, graphText, label, width, graphStyles, labelStyles) {
// Y labels live inside the chart and deliberately replace any Braille cells
// beneath them. Style the two segments separately after measuring raw text.
label = Width.truncate(label, width, width > 1 ? '…' : '');
var labelWidth = stringWidth(label);
return cli.applyStyles(label, labelStyles) +
cli.applyStyles(graphText.slice(labelWidth), graphStyles);
}
module.exports = {
chart: function(args) {
// Render one static, filled timeseries chart as a multi-line string.
args = args || {};
var layoutWidth = ('width' in args) ?
wholeNumber(args.width, 80, 0) : (this.width() || 80);
var indent = wholeNumber(args.indent, 1, 0);
var outerWidth = Math.max(0, layoutWidth - (indent * 2));
var innerWidth = Math.max(0, outerWidth - 2);
var height = wholeNumber(args.height, 14, 2);
var indentText = this.space(indent);
// A border needs at least its two corner cells. Returning an empty string is
// safer than overflowing when the requested margins consume the whole width.
if (outerWidth < 2) return '';
var graphStyles = styleList(args.color, []);
var borderStyles = styleList(args.borderStyles, ['gray']);
var labelStyles = styleList(args.labelStyles, ['gray']);
var titleStyles = styleList(args.titleStyles, ['cyan', 'bold']);
var rows = prepareData( Array.isArray(args.data) ? args.data : [] );
applyDelta(rows, args);
var dataType = args.dataType || 'integer';
var dataSuffix = args.dataSuffix || '';
var floatPrecision = wholeNumber(args.floatPrecision, 2, 1);
var minVertScale = Number(args.minVertScale || 0);
if (!isFinite(minVertScale) || (minVertScale < 0)) minVertScale = 0;
// The Y scale is always zero-floored and otherwise bound to the highest
// sample, unless minVertScale requests a larger fixed minimum.
var yMax = minVertScale;
rows.forEach( function(row) { yMax = Math.max(yMax, row.y, 0); } );
var values = resampleData(rows, innerWidth * 2);
var output = [];
// Titles sit above the frame and align with its left border.
if (args.title) {
var title = ('' + args.title).replace(/\r?\n/g, ' ');
title = Width.truncate(title, outerWidth, outerWidth > 1 ? '…' : '');
output.push( indentText + this.applyStyles(title, titleStyles) );
}
// Render the border and all chart rows. Fewer than two samples intentionally
// leaves the Braille area blank, while one sample still supplies axis limits.
output.push( indentText + this.applyStyles('┌' + this.repeat('─', innerWidth) + '┐', borderStyles) );
for (var rowIndex = 0; rowIndex < height; rowIndex++) {
var graphText = (rows.length >= 2) ?
renderBrailleRow(values, rowIndex, height, innerWidth, yMax) : this.space(innerWidth);
var content = this.applyStyles(graphText, graphStyles);
if (rows.length && !rowIndex) {
var topLabel = formatDataValue(yMax, dataType, dataSuffix, floatPrecision);
content = overtypeLabel(this, graphText, topLabel, innerWidth, graphStyles, labelStyles);
}
else if (rows.length && (rowIndex == height - 1)) {
var bottomLabel = formatDataValue(0, dataType, dataSuffix, floatPrecision);
content = overtypeLabel(this, graphText, bottomLabel, innerWidth, graphStyles, labelStyles);
}
output.push(
indentText +
this.applyStyles('│', borderStyles) +
content +
this.applyStyles('│', borderStyles)
);
}
output.push( indentText + this.applyStyles('└' + this.repeat('─', innerWidth) + '┘', borderStyles) );
// Empty datasets have no axes. One sample produces two identical timestamps,
// which preserves the documented two-label layout without drawing an area.
if (rows.length) {
var xMin = rows[0].x;
var xMax = rows[ rows.length - 1 ].x;
var dateRange = getDateRange(xMin, xMax);
var axisText = renderAxisLabels(
formatDate(xMin, dateRange),
formatDate(xMax, dateRange),
outerWidth
);
output.push( indentText + this.applyStyles(axisText, labelStyles) );
}
return output.join('\n');
}
};
jhuckaby-pixl-cli-dfc810c/cli.js 0000664 0000000 0000000 00000076054 15250445340 0016646 0 ustar 00root root 0000000 0000000 // Tools for writing command-line apps in Node.
// Copyright (c) 2016 - 2018 Joseph Huckaby
// Released under the MIT License
var fs = require('fs');
var readline = require('readline');
var path = require('path');
var chalk = require('chalk');
var Util = require('./util');
var Width = require('./width');
var wordWrap = require('./wrap');
var ansiPattern = Util.ansiPattern;
var stringWidth = Width.stringWidth;
var widestLine = Width.widestLine;
var Tools = require('pixl-tools');
var Args = require('pixl-args');
var args = new Args();
var cli = module.exports = {
// CLI args hash
args: args.get(),
// expose some utility functions and third-party modules
chalk: chalk,
stringWidth: stringWidth,
widestLine: widestLine,
wordWrap: wordWrap,
Tools: Tools,
// for stripping colors:
ansiPattern: ansiPattern,
mapArgs: function(aliases) {
// apply alias lookup to a set of args
// e.g. { 'q':'quiet', 'v':'verbose' }
for (var key in aliases) {
if (key in this.args) {
this.args[ aliases[key] ] = this.args[key];
delete this.args[key];
}
}
},
tty: function() {
// return true if stdout is connected to a TTY,
// i.e. so we can ask the user things
return process.stdout.isTTY;
},
width: function() {
// returns current terminal width
if (!this.tty()) return 0;
return process.stdout.columns;
},
prompt: function(text, def, callback) {
// prompt user for input, send answer to callback
var self = this;
if (!this.tty()) return callback(def);
var rl = readline.createInterface(process.stdin, process.stdout);
if (!text.match(/\s$/)) text += ' ';
if (def) text += '[' + def + '] ';
this.currentPrompt = text;
rl.question(text, function(answer) {
rl.close();
delete self.currentPrompt;
callback( answer || def );
} );
},
clearPrompt: function() {
// erase previous prompt text, if any
if (this.currentPrompt) {
process.stdout.write( "\r" + this.space( stringWidth(this.currentPrompt) ) + "\r" );
}
},
restorePrompt: function() {
// restore previous prompt text, if any
if (this.currentPrompt) {
process.stdout.write( this.currentPrompt );
}
},
yesno: function(text, def, callback) {
// prompt user with a yes/no question
// callback will be sent a true/false value
this.prompt( text.trim() + " (y/n) ", def, function(answer) {
callback( answer && answer.match(/y/i) );
} );
},
repeat: function(text, amount) {
// repeat string by specified number of times
if (!amount || (amount < 0)) return "";
return (''+text).repeat(amount);
},
space: function(amount) {
// generate some amount of whitespace
return this.repeat(" ", amount);
},
pad: function(text, width) {
// pad a string with spaces on right side to take up specified width
return text + this.space(width - stringWidth(text));
},
emoji: function(emoji) {
// Draw the emoji, restore its starting cursor position, then explicitly move
// forward two cells. This overrides each terminal's automatic cursor advance.
return '\u001b7' + emoji + '\u001b8\u001b[2C';
},
center: function(text, width) {
// center string horizontally
var self = this;
text = text.toString().trim();
if (!width) width = widestLine(text);
// recurse for multi-line text blobs
if (text.match(/\n/)) {
return text.split(/\n/).map(function(line) {
return self.center(line, width);
}).join("\n");
} // multi-line
var margin = Math.floor( (width - stringWidth(text)) / 2 );
var output = this.space(margin) + text;
var remain = width - stringWidth(output);
output += this.space(remain);
return output;
},
wrap: function(text, width) {
// return word-wrapped text block
return wordWrap( text, {
width: width,
indent: "",
newline: "\n",
trim: true,
cut: false
} );
},
box: function(text, args) {
// ┌───────────────────────────────────────┐
// │ Wrap a text string in an ASCII box. │
// └───────────────────────────────────────┘
var self = this;
text = text.toString();
if (!args) args = {};
var width = args.width || 0;
var hspace = ("hspace" in args) ? args.hspace : 1;
var vspace = args.vspace || 0;
var styles = args.styles || ["gray"];
var indent = args.indent || "";
if (typeof(indent) == 'number') indent = cli.space(indent);
var output = [];
// calc width / wrap text
if (width) text = this.wrap(text, width);
else width = widestLine(text);
width += (hspace * 2);
// top border
output.push( indent + this.applyStyles("┌" + this.repeat("─", width) + "┐", styles) );
// left, content, right
// Styled text normally carries its SGR modes across newlines, but the styled
// right border resets those modes before the next content line. Make each
// line self-contained before inserting borders between them.
var safeText = (styles && styles.length) ? Util.preserveAnsiLineStyles(text) : text;
var lines = safeText.split(/\n/);
while (vspace-- > 0) {
lines.unshift( "" );
lines.push( "" );
}
lines.forEach( function(line) {
line = self.space(hspace) + line + self.space(hspace);
output.push(
indent +
self.applyStyles("│", styles) +
self.pad(line, width) +
self.applyStyles("│", styles)
);
} );
// bottom border
output.push( indent + this.applyStyles("└" + this.repeat("─", width) + "┘", styles) );
return output.join("\n");
},
defList: function(rows, args) {
// Render a two-column definition list inside a box. The labels share a
// common width, but there is deliberately no border between the columns.
var self = this;
if (!args) args = {};
// Empty arrays are valid style overrides, so test for the property rather
// than using || here. Labels are bold by default and values are plain.
var labelStyles = ('labelStyles' in args) ? args.labelStyles : ["bold"];
var textStyles = ('textStyles' in args) ? args.textStyles : [];
var borderStyles = ('borderStyles' in args) ? args.borderStyles :
(('styles' in args) ? args.styles : ["gray"]);
var hspace = ('hspace' in args) ? args.hspace : 1;
var vspace = args.vspace || 0;
// Gaps are whole terminal cells. Invalid and negative values become zero.
var gap = ('gap' in args) ? Math.floor(Number(args.gap)) : 1;
if (!isFinite(gap) || (gap < 0)) gap = 0;
var indent = args.indent || "";
if (typeof(indent) == 'number') indent = this.space(indent);
// Normalize and style all cells before measuring them. This allows ANSI
// color, custom style functions and the cli.emoji() cursor hack to coexist
// with the display-width calculations below.
var items = (rows || []).map( function(row) {
var label = '' + row[0];
var value = '' + row[1];
// Definition lists are one item per line. Flatten accidental newlines so
// a cell cannot escape its row and disturb the surrounding box.
label = label.replace(/\r?\n/g, ' ').replace(/\s+$/, '');
value = value.replace(/\r?\n/g, ' ');
if (!label.replace(ansiPattern, '').match(/:$/)) label += ':';
return {
label: self.applyStyles(label, labelStyles),
value: self.applyStyles(value, textStyles)
};
} );
var labelWidth = 0;
var valueWidth = 0;
items.forEach( function(item) {
labelWidth = Math.max( labelWidth, stringWidth(item.label) );
valueWidth = Math.max( valueWidth, stringWidth(item.value) );
} );
// The indent acts as a horizontal margin, so reserve it on both sides.
// Also reserve both box borders, both padding areas, and the requested gap
// separating the label and value columns.
var terminalWidth = this.width();
var contentWidth = labelWidth + gap + valueWidth;
if (terminalWidth) {
var availableWidth = terminalWidth - (stringWidth(indent) * 2);
var availableContentWidth = Math.max(0, availableWidth - 2 - (hspace * 2));
contentWidth = Math.min(contentWidth, availableContentWidth);
}
// Keep the complete label column whenever possible, and give all remaining
// room to values. On extremely narrow terminals labels are shortened too,
// while still reserving one cell for a value when any room remains.
if (labelWidth + gap + 1 > contentWidth) {
labelWidth = Math.max(0, contentWidth - gap - 1);
}
valueWidth = Math.max(0, contentWidth - labelWidth - (labelWidth ? gap : 0));
var truncate = function(text, width) {
// Width.truncate() preserves ANSI resets and complete emoji graphemes.
if (width < 1) return '';
return (stringWidth(text) > width) ? Width.truncate(text, width, '…') : text;
};
var lines = items.map( function(item) {
var label = truncate(item.label, labelWidth);
var value = truncate(item.value, valueWidth);
if (!labelWidth) return value;
return self.pad(label, labelWidth) + self.space(gap) + value;
} );
// Let box() handle the border, padding, vertical spacing and final row
// padding. Passing the normalized indent keeps numeric margins consistent.
return this.box( lines.join("\n"), {
styles: borderStyles,
hspace: hspace,
vspace: vspace,
indent: indent
} );
},
dashGrid: function(rows, args) {
// Render a responsive grid of equal-sized dashboard units. Each unit has a
// centered value, a centered label, a blank spacer row and its own border.
var self = this;
if (!rows || !rows.length) return '';
if (!args) args = {};
// Normalize numeric layout options to non-negative whole terminal cells.
// Invalid values fall back to their documented defaults.
var wholeNumber = function(value, defaultValue, minimum) {
value = Math.floor(Number(value));
if (!isFinite(value)) value = defaultValue;
return Math.max(minimum, value);
};
var targetUnitWidth = wholeNumber(args.unitWidth, 20, 5);
var minCols = wholeNumber(args.minCols, 3, 1);
var maxCols = wholeNumber(args.maxCols, 5, 1);
var gap = wholeNumber(args.gap, 1, 0);
var indent = args.indent || '';
if (typeof(indent) == 'number') indent = this.space(indent);
// A maximum is a hard cap. If conflicting limits are supplied, lower the
// minimum to match rather than silently exceeding the requested maximum.
if (minCols > maxCols) minCols = maxCols;
// Empty style arrays are intentional overrides, so property checks are used
// instead of ||. Values are bold, labels and borders are gray by default.
var valueStyles = ('valueStyles' in args) ? args.valueStyles : ["bold"];
var labelStyles = ('labelStyles' in args) ? args.labelStyles : ["gray"];
var borderStyles = ('borderStyles' in args) ? args.borderStyles : ["gray"];
// An explicit width makes redirected output and tests deterministic. When
// attached to a terminal, cli.width() returns process.stdout.columns.
var layoutWidth = ('width' in args) ?
wholeNumber(args.width, 80, 0) : (this.width() || 80);
var availableWidth = Math.max(0, layoutWidth - (stringWidth(indent) * 2));
if (availableWidth < 2) return '';
// Start with the preferred responsive column count, bounded by the caller's
// limits and the number of units. unitWidth is a planning target; the actual
// width is calculated below after horizontal gaps have been reserved.
var numCols = Math.floor(availableWidth / targetUnitWidth);
numCols = Math.max(minCols, Math.min(maxCols, numCols));
numCols = Math.min(numCols, rows.length);
// Each useful unit needs five cells: two borders, two padding cells and one
// content cell. On a very narrow terminal, safety takes priority over the
// requested minimum column count so the grid never overflows.
var maxFittingCols = Math.floor((availableWidth + gap) / (5 + gap));
maxFittingCols = Math.max(1, maxFittingCols);
numCols = Math.max(1, Math.min(numCols, maxFittingCols));
// All units use the same exact outer width. Any indivisible remainder stays
// unused at the right edge, including on incomplete final rows.
var unitWidth = Math.floor(
(availableWidth - ((numCols - 1) * gap)) / numCols
);
if (unitWidth < 2) return '';
var innerWidth = unitWidth - 2;
var contentWidth = Math.max(0, innerWidth - 2);
var truncate = function(text) {
// Preserve ANSI styles, complete graphemes and cli.emoji() sequences.
if (contentWidth < 1) return '';
return (stringWidth(text) > contentWidth) ?
Width.truncate(text, contentWidth, '…') : text;
};
var centerCell = function(text) {
// Center by terminal display width rather than JavaScript string length.
var remain = Math.max(0, innerWidth - stringWidth(text));
var left = Math.floor(remain / 2);
return self.space(left) + text + self.space(remain - left);
};
var units = rows.map( function(row) {
var label = ('' + row[0]).replace(/\r?\n/g, ' ');
var value = ('' + row[1]).replace(/\r?\n/g, ' ');
return {
label: self.applyStyles(label, labelStyles),
value: self.applyStyles(value, valueStyles)
};
} );
var renderUnit = function(unit) {
// The interior layout is: value, blank, label.
var top = self.applyStyles(
'┌' + self.repeat('─', innerWidth) + '┐', borderStyles
);
var bottom = self.applyStyles(
'└' + self.repeat('─', innerWidth) + '┘', borderStyles
);
var leftBorder = self.applyStyles('│', borderStyles);
var rightBorder = self.applyStyles('│', borderStyles);
var blank = leftBorder + self.space(innerWidth) + rightBorder;
return [
top,
leftBorder + centerCell(truncate(unit.value)) + rightBorder,
blank,
leftBorder + centerCell(truncate(unit.label)) + rightBorder,
bottom
];
};
var output = [];
for (var rowIdx = 0; rowIdx < units.length; rowIdx += numCols) {
var gridRow = units.slice(rowIdx, rowIdx + numCols).map(renderUnit);
// Join corresponding lines from each unit to form one complete grid row.
for (var lineIdx = 0; lineIdx < gridRow[0].length; lineIdx++) {
output.push(
indent + gridRow.map( function(unit) {
return unit[lineIdx];
} ).join(self.space(gap))
);
}
// Adjacent text lines already provide one row of vertical separation, so
// subtract one when translating the horizontal gap into blank lines.
if (rowIdx + numCols < units.length) {
for (var gapIdx = 0; gapIdx < Math.max(0, gap - 1); gapIdx++) output.push('');
}
}
return output.join("\n");
},
applyStyles: function(text, styles) {
// apply one or more chalk styles or functions to text string
if (!styles) return text;
styles.forEach( function(style) {
if (typeof style === 'function') {
text = style( text );
} else {
text = chalk[style]( text );
}
} );
return text;
},
tree: function(dir, indent, args) {
// render dir/file tree view based on array of files/dirs
var self = this;
if (!dir) dir = ".";
if (!indent) indent = "";
if (!args) args = {};
var output = [];
args.folderStyles = args.folderStyles || ["bold", "yellow"];
args.fileStyles = args.fileStyles || ["green"];
args.symlinkStyles = args.symlinkStyles || ["purple"];
args.lineStyles = args.lineStyles || ["gray"];
args.includeFilter = args.includeFilter || /./;
args.excludeFilter = args.excludeFilter || /(?!)/;
if (!indent) {
output.push( this.applyStyles( path.basename(dir) + "/", args.folderStyles ) );
}
fs.readdirSync(dir).forEach( function(filename, idx, arr) {
if (!filename.match(args.includeFilter) || filename.match(args.excludeFilter)) return;
var file = path.join( dir, filename );
var stats = fs.statSync(file);
var last = (idx == arr.length - 1);
var prefix = indent + self.applyStyles( " " + (last ? "└" : "├"), args.lineStyles ) + " ";
if (stats.isDirectory()) {
output.push( prefix + self.applyStyles(filename + "/", args.folderStyles) );
var results = self.tree(file, indent + self.applyStyles( last ? " " : " │", args.lineStyles ) + " ", args );
if (results) output.push( results );
}
else if (stats.isSymbolicLink()) {
output.push( prefix + self.applyStyles(filename, args.symlinkStyles) );
}
else {
output.push( prefix + self.applyStyles(filename, args.fileStyles) );
}
} );
return output.length ? output.join("\n") : "";
},
autoFitTableRows: function(rows, args) {
// add ellipsis to rows as needed to fit entire table into horiz terminal width
var self = this;
var avail_width = (this.width() - (stringWidth(args.indent) * 2));
if (avail_width < 1) return;
var max_col_widths = [];
rows.forEach( function(cols, idx) {
cols.forEach( function(col, idy) {
max_col_widths[idy] = Math.max( max_col_widths[idy] || 0, stringWidth(''+col) );
} );
} );
var measureTableWidth = function() {
// measure table width with current settings and max_col_widths "virtually" applied
var widestCols = [];
rows.forEach( function(cols, idx) {
cols.forEach( function(col, idy) {
var sw = Math.min( stringWidth(''+col), max_col_widths[idy] );
widestCols[idy] = Math.max( widestCols[idy] || 0, sw + 2 );
} );
} );
var numCols = widestCols.length;
var line = "┌";
widestCols.forEach( function(num, idx) {
line += self.repeat("─", num);
if (idx < numCols - 1) line += "┬";
} );
line += "┐";
return line.length;
}; // measureTableWidth
// now keep chopping down max_col_widths until we fit
while (measureTableWidth() > avail_width) {
// find largest max_col_widths and decrement it by 1
var longest_col_width = Math.max.apply( Math, max_col_widths );
if (longest_col_width < 2) return; // e-brake
var longest_col_idx = max_col_widths.indexOf(longest_col_width);
if (longest_col_idx == -1) return; // sanity
max_col_widths[longest_col_idx]--;
}
// finally prune affected columns by display width, preserving ANSI and emoji
rows.forEach( function(cols, idx) {
cols.forEach( function(col, idy) {
col = '' + col;
if (stringWidth(col) > max_col_widths[idy]) {
cols[idy] = Width.truncate(col, max_col_widths[idy], '…');
} // too wide
});
});
},
table: function(rows, args) {
// render table of cols/rows with unicode borders
// rows should be an array of arrays (columns), with row 0 being the header
var self = this;
// optional args
if (!args) args = {};
args.headerStyles = args.headerStyles || ["bold", "yellow"];
args.borderStyles = args.borderStyles || ["gray"];
args.textStyles = args.textStyles || ["cyan"];
args.indent = args.indent || "";
if (typeof(args.indent) == 'number') args.indent = cli.space(args.indent);
if (args.autoFit) this.autoFitTableRows(rows, args);
// calculate widest columns (+1spc of hpadding)
var widestCols = [];
rows.forEach( function(cols, idx) {
cols.forEach( function(col, idy) {
widestCols[idy] = Math.max( widestCols[idy] || 0, stringWidth(''+col) + 2 );
} );
} );
var numCols = widestCols.length;
var output = [];
// top border
var line = "┌";
widestCols.forEach( function(num, idx) {
line += self.repeat("─", num);
if (idx < numCols - 1) line += "┬";
} );
line += "┐";
output.push( args.indent + this.applyStyles(line, args.borderStyles) );
// header row
var line = this.applyStyles("│", args.borderStyles);
rows.shift().forEach( function(col, idx) {
col = self.applyStyles(" " + col + " ", args.headerStyles);
line += self.pad(col, widestCols[idx]) + self.applyStyles("│", args.borderStyles);
} );
output.push(args.indent + line);
// header divider
var line = "├";
widestCols.forEach( function(num, idx) {
line += self.repeat("─", num);
if (idx < numCols - 1) line += "┼";
} );
line += "┤";
output.push( args.indent + this.applyStyles(line, args.borderStyles) );
// main content
rows.forEach( function(cols, idx) {
var line = self.applyStyles("│", args.borderStyles);
cols.forEach( function(col, idy) {
col = self.applyStyles(" " + col + " ", args.textStyles);
line += self.pad(col, widestCols[idy]) + self.applyStyles("│", args.borderStyles);
} );
output.push(args.indent + line);
} );
// bottom border
var line = "└";
widestCols.forEach( function(num, idx) {
line += self.repeat("─", num);
if (idx < numCols - 1) line += "┴";
} );
line += "┘";
output.push( args.indent + this.applyStyles(line, args.borderStyles) );
return output.join("\n");
},
loadFile: function(file) {
// load file into memory synchronously, return string
return fs.readFileSync( file, { encoding: 'utf8' } );
},
saveFile: function(file, content) {
// save file to disk synchronously
fs.writeFileSync( file, content );
},
appendFile: function(file, content) {
// append to file synchronously
fs.appendFileSync( file, content );
},
jsonPretty: function(mixed) {
// return pretty-printed JSON (which I always forget how to do in Node)
return JSON.stringify( mixed, null, "\t" );
},
stripColor: function(text) {
// strip ANSI colors from text
return text.replace( this.ansiPattern, '' );
},
setLogFile: function(file) {
// log all output from our print methods to file
this.logFile = file;
},
log: function(msg) {
// log something (if log file is configured)
if (this.logFile) {
if (typeof(msg) == 'object') msg = JSON.stringify(msg);
else if (!msg.match(/\S/)) return; // skip whitespace
var dargs = Tools.getDateArgs( Tools.timeNow() );
var line = '[' + dargs.yyyy_mm_dd + ' ' + dargs.hh_mi_ss + '] ' + this.stripColor(msg.trim()).trim() + "\n";
fs.appendFileSync( this.logFile, line );
}
},
print: function(msg) {
// print message to console
if (!this.args.quiet) {
if (this.progress.running) this.progress.erase();
process.stdout.write(msg);
if (this.progress.running) this.progress.draw();
}
this.log(msg);
},
println: function(msg) {
// print plus EOL
this.print( msg + "\n" );
},
verbose: function(msg) {
// print only in verbose mode
if (this.args.verbose) this.print(msg);
else this.log(msg);
},
verboseln: function(msg) {
// verbose print plus EOL
this.verbose( msg + "\n" );
},
warn: function(msg) {
// print to stderr
if (!this.args.quiet) {
if (this.progress.running) this.progress.erase();
process.stderr.write(msg);
if (this.progress.running) this.progress.draw();
}
this.log(msg);
},
warnln: function(msg) {
// warn plus EOL
this.warn( msg + "\n" );
},
die: function(msg) {
// print to stderr and exit with non-zero code
if (this.progress.running) this.progress.end();
this.warn(msg);
process.exit(1);
},
dieln: function(msg) {
// die plus EOL
this.die( msg + "\n" );
},
global: function() {
// pollute global namespace with our wares
var self = this;
// copy over some objects
global.args = this.args;
global.progress = this.progress;
global.Tools = Tools;
// bind wrap functions
["prompt", "yesno", "table", "box", "defList", "dashGrid", "wrap", "center", "print", "println", "verbose", "verboseln", "warn", "warnln", "die", "dieln", "loadFile", "saveFile", "appendFile"].forEach( function(func) {
global[func] = self[func].bind(self);
} );
// copy over some common pixl-tools functions
["commify", "shortFloat", "pct", "pluralize", "ucfirst"].forEach( function(func) {
global[func] = self[func]; // these are already bound to Tools
} );
// expose chalk styles as global keywords
["reset","bold","dim","italic","underline","inverse","hidden","strikethrough","black","red","green","yellow","blue","magenta","cyan","white","gray","grey","bgBlack","bgRed","bgGreen","bgYellow","bgBlue","bgMagenta","bgCyan","bgWhite"].forEach( function(key) {
global[key] = chalk[key];
} );
},
progress: {
// unicode progress bar
args: {},
defaults: {
spinner: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'],
braces: ['⟦', '⟧'],
filling: [' ', '⡀', '⡄', '⡆', '⡇', '⣇', '⣧', '⣷'],
filled: '⣿',
indent: "",
styles: {
spinner: ['bold', 'green'],
braces: ['gray'],
bar: ['bold', 'cyan'],
indeterminate: ['gray'],
pct: ['bold', 'yellow'],
remain: ['green'],
text: []
},
pct: true,
width: 30,
freq: 100,
remain: true,
color: true,
unicode: true,
catchInt: false,
catchTerm: false,
catchCrash: false,
exitOnSig: true
},
asciiOverrides: {
spinner: ['|', '/', '-', "\\"],
filling: [' ', '.', ':'],
filled: '#',
braces: ['[', ']']
},
start: function(overrides) {
// start new progress session
if (!cli.tty()) return;
// copy defaults and apply user overrides
var args = Tools.copyHash( this.defaults );
Tools.mergeHashInto( args, overrides || {} );
if (!args.amount) args.amount = 0;
if (!args.max) args.max = 1.0;
if (!args.text) args.text = "";
if (!args.lastRemainCheck) args.lastRemainCheck = 0;
if (!args.timeStart) args.timeStart = Tools.timeNow();
// no color? wipe all chalk styles
if (!args.color) args.styles = {};
// ascii mode? copy over safe chars
if (!args.unicode) {
Tools.mergeHashInto( args, this.asciiOverrides );
}
// make sure indent doesn't contain a hard tab
if (typeof(args.indent) == 'number') args.indent = cli.space(args.indent);
args.indent = args.indent.replace(/\t/g, " ");
this.args = args;
this.running = true;
this.spinFrame = 0;
this.lastLine = "";
this.draw();
this.timer = setInterval( this.draw.bind(this), args.freq );
// hide CLI cursor
if (!this.args.quiet) process.stdout.write('\u001b[?25l');
// just in case
process.once('exit', function() {
if (cli.progress.running) cli.progress.end();
} );
if (args.catchInt) {
process.once('SIGINT', function() {
if (cli.progress.running) cli.progress.end();
if (args.exitOnSig) process.exit(128 + 2);
} );
}
if (args.catchTerm) {
process.once('SIGTERM', function() {
if (cli.progress.running) cli.progress.end();
if (args.exitOnSig) process.exit(128 + 15);
} );
}
if (args.catchCrash) {
process.once('uncaughtException', function() {
if (cli.progress.running) cli.progress.end();
} );
}
},
bar: function(overrides) {
// return simple bar by itself, no progress, no spinner
var args = Tools.copyHash( this.defaults );
Tools.mergeHashInto( args, overrides || {} );
if (!args.amount) args.amount = 0;
if (!args.max) args.max = 1.0;
// no color? wipe all chalk styles
if (!args.color) args.styles = {};
// ascii mode? copy over safe chars
if (!args.unicode) {
Tools.mergeHashInto( args, this.asciiOverrides );
}
// make sure indent doesn't contain a hard tab
if (typeof(args.indent) == 'number') args.indent = cli.space(args.indent);
args.indent = args.indent.replace(/\t/g, " ");
var line = args.indent;
// progress bar
line += cli.applyStyles( args.braces[0], args.styles.braces );
var bar = "";
var width = Math.max(0, Math.min(args.amount / args.max, 1.0)) * args.width;
var partial = width - Math.floor(width);
bar += cli.repeat(args.filled, Math.floor(width));
if (partial > 0) {
bar += args.filling[ Math.floor(partial * args.filling.length) ];
}
bar += cli.space(args.width - stringWidth(bar));
line += cli.applyStyles( bar, (args.amount === args.max) ? args.styles.indeterminate : args.styles.bar );
line += cli.applyStyles( args.braces[1], args.styles.braces );
// percentage
if (args.pct) {
line += " ";
var pct = cli.pct(args.amount, args.max, true);
line += cli.applyStyles( pct, args.styles.pct );
}
return line;
},
draw: function() {
// draw progress bar, spinner
if (!this.running) return;
if (!cli.tty()) return;
var args = this.args;
var line = args.indent;
// spinner
line += cli.applyStyles( args.spinner[ this.spinFrame++ % args.spinner.length ], args.styles.spinner );
line += " ";
// progress bar
line += cli.applyStyles( args.braces[0], args.styles.braces );
var bar = "";
var width = Math.max(0, Math.min(args.amount / args.max, 1.0)) * args.width;
var partial = width - Math.floor(width);
bar += cli.repeat(args.filled, Math.floor(width));
if (partial > 0) {
bar += args.filling[ Math.floor(partial * args.filling.length) ];
}
bar += cli.space(args.width - stringWidth(bar));
line += cli.applyStyles( bar, (args.amount === args.max) ? args.styles.indeterminate : args.styles.bar );
line += cli.applyStyles( args.braces[1], args.styles.braces );
// percentage
if (args.pct) {
line += " ";
var pct = cli.pct(args.amount, args.max, true);
line += cli.applyStyles( pct, args.styles.pct );
}
// remaining
var now = Tools.timeNow();
var elapsed = now - args.timeStart;
if ((args.amount > 0) && (args.amount < args.max) && (elapsed >= 5) && args.remain) {
if (now - args.lastRemainCheck >= 1.0) {
args.lastRemainString = cli.getNiceRemainingTime( elapsed, args.amount, args.max, true, true );
args.lastRemainCheck = now;
}
if (args.lastRemainString) {
line += cli.applyStyles( " (" + args.lastRemainString + " remain)", args.styles.remain );
}
}
// custom text
if (args.text) {
line += " ";
line += cli.applyStyles( args.text.trim(), args.styles.text );
}
// clean up last line
if (this.lastLine) {
var curWidth = stringWidth(line);
var lastWidth = stringWidth(this.lastLine);
if (curWidth < lastWidth) {
line += cli.space(lastWidth - curWidth);
}
}
if (!this.args.quiet) process.stdout.write( line + "\r" );
this.lastLine = line;
},
update: function(args) {
if (!this.running) return;
if (!cli.tty()) return;
if (typeof(args) == 'number') {
// just updating the amount
this.args.amount = args;
}
else {
// update any key/value pairs
for (var key in args) {
this.args[key] = args[key];
}
}
this.args.amount = Math.max(0, Math.min(this.args.max, this.args.amount));
},
erase: function() {
// erase progress
if (!this.running) return;
if (!cli.tty()) return;
if (this.lastLine && !this.args.quiet) {
process.stdout.write( cli.space( stringWidth(this.lastLine) ) + "\r" );
}
},
end: function(erase) {
// end of progress session
if (!this.running) return;
if (!cli.tty()) return;
if (erase !== false) {
this.erase();
}
clearTimeout( this.timer );
this.running = false;
this.args = {};
this.lastLine = '';
// restore CLI cursor
if (!this.args.quiet) process.stdout.write('\u001b[?25h');
}
} // progress
};
// Mix in optional renderers which depend on the core CLI helpers above.
Tools.mergeHashInto( cli, require('./chart.js') );
// import some common utilities
["getTextFromBytes", "commify", "shortFloat", "pct", "zeroPad", "getTextFromSeconds", "getNiceRemainingTime", "pluralize", "ucfirst"].forEach( function(func) {
module.exports[func] = Tools[func].bind(Tools);
} );
// import chalk into our module
["reset","bold","dim","italic","underline","inverse","hidden","strikethrough","black","red","green","yellow","blue","magenta","cyan","white","gray","grey","bgBlack","bgRed","bgGreen","bgYellow","bgBlue","bgMagenta","bgCyan","bgWhite"].forEach( function(key) {
module.exports[key] = chalk[key];
} );
jhuckaby-pixl-cli-dfc810c/package.json 0000664 0000000 0000000 00000001162 15250445340 0020013 0 ustar 00root root 0000000 0000000 {
"name": "pixl-cli",
"version": "1.1.6",
"description": "Tools for building command-line apps for Node.js.",
"author": "Joseph Huckaby ",
"homepage": "https://github.com/jhuckaby/pixl-cli",
"license": "MIT",
"main": "cli.js",
"repository": {
"type": "git",
"url": "https://github.com/jhuckaby/pixl-cli"
},
"bugs": {
"url": "https://github.com/jhuckaby/pixl-cli/issues"
},
"keywords": [
"cli",
"commandline",
"prompt",
"progress",
"progressbar",
"table"
],
"dependencies": {
"pixl-args": "^1.0.0",
"pixl-tools": "^2.0.2",
"chalk": "2.4.1"
},
"devDependencies": {}
}
jhuckaby-pixl-cli-dfc810c/util.js 0000664 0000000 0000000 00000004717 15250445340 0017051 0 ustar 00root root 0000000 0000000 // Shared Unicode and terminal utilities for pixl-cli.
// Match ANSI terminal escape sequences so they can be ignored during measurement.
var ansiPattern = new RegExp([
'[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
'(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'
].join('|'), 'g');
// Split strings into user-perceived characters, including complete emoji sequences.
var graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
function splitAnsiGraphemes(text) {
// Split a string into complete ANSI sequences and Unicode grapheme clusters.
// ANSI sequences are kept intact so callers can preserve them while editing text.
var units = [];
var pattern = new RegExp(ansiPattern.source, 'g');
var offset = 0;
var match = null;
var addText = function(value) {
for (var item of graphemeSegmenter.segment(value)) {
units.push({ text: item.segment, ansi: false });
}
};
while ((match = pattern.exec(text))) {
if (match.index > offset) addText( text.substring(offset, match.index) );
units.push({ text: match[0], ansi: true });
offset = pattern.lastIndex;
}
if (offset < text.length) addText( text.substring(offset) );
return units;
}
function preserveAnsiLineStyles(text) {
// A styled multi-line string normally relies on terminal modes carrying across
// newline characters. Callers such as cli.box() insert independently styled
// borders between those lines, whose reset codes can cancel the content styles.
// Close all modes at each line ending, then restore the exact SGR state after the
// next border by replaying the original SGR history at the next line's start.
var lines = text.split('\n');
if (lines.length < 2) return text;
var sgrHistory = '';
var sgrPattern = /^(?:\u001B\[|\u009B)[0-9:;]*m$/;
var reset = '\u001b[0m';
return lines.map( function(line, idx) {
var reopen = sgrHistory;
// Only sequences from the original text enter the history. Synthetic reset
// and replay sequences added here must not accumulate on subsequent lines.
splitAnsiGraphemes(line).forEach( function(unit) {
if (unit.ansi && unit.text.match(sgrPattern)) sgrHistory += unit.text;
} );
if ((idx < lines.length - 1) && sgrHistory) line += reset;
return reopen + line;
} ).join('\n');
}
module.exports = {
ansiPattern: ansiPattern,
graphemeSegmenter: graphemeSegmenter,
splitAnsiGraphemes: splitAnsiGraphemes,
preserveAnsiLineStyles: preserveAnsiLineStyles
};
jhuckaby-pixl-cli-dfc810c/width.js 0000664 0000000 0000000 00000011273 15250445340 0017206 0 ustar 00root root 0000000 0000000 // Terminal display-width measurement for pixl-cli.
var Util = require('./util');
var ansiPattern = Util.ansiPattern;
var graphemeSegmenter = Util.graphemeSegmenter;
// These built-in Unicode properties let us identify emoji without carrying a large,
// generated lookup table. VS16 changes text-default symbols to emoji presentation.
var zeroWidthClusterPattern = /^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Nonspacing_Mark}|\p{Enclosing_Mark}|\p{Surrogate})+$/u;
var emojiPattern = /\p{Emoji}/u;
var emojiPresentationPattern = /\p{Emoji_Presentation}/u;
var emojiModifierPattern = /\p{Emoji_Modifier}/u;
var regionalIndicatorPattern = /\p{Regional_Indicator}/gu;
var extendedPictographicPattern = /\p{Extended_Pictographic}/gu;
var keycapPattern = /^[\d#*]\uFE0F?\u20E3$/;
var keycapBaseWithVs16Pattern = /^[\d#*]\uFE0F$/;
function stringWidth(text) {
// Measure Western Unicode and emoji terminal columns, ignoring ANSI styling.
if ((typeof(text) != 'string') || !text.length) return 0;
text = text.replace(ansiPattern, '');
if (!text.length) return 0;
// Printable ASCII needs no Unicode segmentation and is by far the common case.
if (text.match(/^[\u0020-\u007E]*$/)) return text.length;
var width = 0;
var segments = graphemeSegmenter.segment(text);
for (var item of segments) {
var segment = item.segment;
if (zeroWidthClusterPattern.test(segment)) continue;
// Native emoji generally occupy two terminal columns. The extra checks cover
// text-default emoji switched by VS16, flags, keycaps and unqualified sequences.
var regionalIndicators = segment.match(regionalIndicatorPattern);
var pictographs = segment.match(extendedPictographicPattern);
var isEmoji = false;
if (segment.includes('\u20E3')) {
isEmoji = keycapPattern.test(segment);
}
else if (regionalIndicators) {
isEmoji = (regionalIndicators.length >= 2);
}
else {
isEmoji = emojiPresentationPattern.test(segment) ||
(emojiPattern.test(segment) && segment.includes('\uFE0F') &&
!keycapBaseWithVs16Pattern.test(segment)) ||
(emojiPattern.test(segment) && emojiModifierPattern.test(segment)) ||
(segment.includes('\u200D') && pictographs && (pictographs.length >= 2));
}
width += isEmoji ? 2 : 1;
}
return width;
}
function widestLine(text) {
// Return the visual width of the widest line in a multi-line string.
var width = 0;
text.split(/\n/).forEach( function(line) {
width = Math.max( width, stringWidth(line) );
} );
return width;
}
function truncate(text, width, suffix) {
// Truncate a string to an exact terminal display width. Preserve complete ANSI
// sequences and grapheme clusters, and retain trailing SGR codes to reset styles.
if (typeof(text) != 'string') text = '' + text;
if (suffix == null) suffix = '';
if (stringWidth(text) <= width) return text;
var suffixWidth = stringWidth(suffix);
var contentWidth = Math.max(0, width - suffixWidth);
var outputWidth = 0;
var output = '';
var units = Util.splitAnsiGraphemes(text);
var trailingAnsi = [];
// cli.emoji() surrounds one grapheme with cursor save, restore and movement
// sequences. Treat this entire construct as one display unit so truncation
// can never keep the save sequence while discarding its matching restore.
for (var idx = 0; idx <= units.length - 4; idx++) {
if (
units[idx].ansi && (units[idx].text === '\u001b7') &&
!units[idx + 1].ansi &&
units[idx + 2].ansi && (units[idx + 2].text === '\u001b8') &&
units[idx + 3].ansi && (units[idx + 3].text === '\u001b[2C')
) {
var emojiUnit = units.slice(idx, idx + 4).map( function(unit) {
return unit.text;
} ).join('');
units.splice(idx, 4, {
text: emojiUnit,
ansi: false
});
}
}
for (var idx = units.length - 1; idx >= 0; idx--) {
if (!units[idx].ansi) break;
if (units[idx].text.match(/^(?:\u001B\[|\u009B)[^m]*m$/)) {
trailingAnsi.unshift(units[idx].text);
}
}
for (var idx = 0, len = units.length; idx < len; idx++) {
var unit = units[idx];
if (unit.ansi) {
output += unit.text;
continue;
}
var unitWidth = stringWidth(unit.text);
if ((outputWidth + unitWidth) > contentWidth) break;
output += unit.text;
outputWidth += unitWidth;
}
// A wide grapheme may not fit the final available cell. Pad that cell so the
// ellipsis still lands at the exact requested width and tables remain aligned.
if (outputWidth < contentWidth) output += ' '.repeat(contentWidth - outputWidth);
return output + suffix + trailingAnsi.join('');
}
// Preserve the compatibility aliases provided by the old CommonJS dependencies.
stringWidth.default = stringWidth;
widestLine.default = widestLine;
module.exports = {
stringWidth: stringWidth,
widestLine: widestLine,
truncate: truncate
};
jhuckaby-pixl-cli-dfc810c/wrap.js 0000664 0000000 0000000 00000007065 15250445340 0017044 0 ustar 00root root 0000000 0000000 // Display-width-aware word wrapping for pixl-cli.
var Util = require('./util');
var stringWidth = require('./width').stringWidth;
function getWrapTokens(text) {
// Split text into alternating words and breakable whitespace, while preserving
// ANSI sequences as zero-width units in their original positions.
var units = Util.splitAnsiGraphemes(text);
units.forEach( function(unit) {
unit.width = unit.ansi ? 0 : stringWidth(unit.text);
unit.breakable = !unit.ansi && !!unit.text.match(/^(?:\s|\u200B)+$/u);
} );
var tokens = [];
var token = null;
var pending = [];
units.forEach( function(unit) {
// ANSI codes do not determine whether a token is a word or whitespace.
if (unit.ansi) {
if (token) token.units.push(unit);
else pending.push(unit);
return;
}
var type = unit.breakable ? 'break' : 'word';
if (!token || (token.type != type)) {
if (token) tokens.push(token);
token = { type: type, units: pending.concat([unit]) };
pending = [];
}
else token.units.push(unit);
} );
if (token) tokens.push(token);
else if (pending.length) tokens.push({ type: 'word', units: pending });
return tokens;
}
function joinWrapUnits(units) {
// Join tokenized graphemes and ANSI sequences back into their original string.
return units.map( function(unit) { return unit.text; } ).join('');
}
function trimWrapLines(text) {
// Trim spaces and tabs from each line without removing the initial indentation.
return text.split('\n').map( function(line) {
return line.replace(/[ \t]+$/, '');
} ).join('\n');
}
function wordWrap(text, options) {
// Wrap text using terminal display columns instead of JavaScript string length.
options = options || {};
if (text == null) return text;
var width = options.width || 50;
var indent = (typeof(options.indent) == 'string') ? options.indent : ' ';
var newline = options.newline || ('\n' + indent);
var escape = (typeof(options.escape) == 'function') ? options.escape : function(value) {
return value;
};
var tokens = getWrapTokens(text);
var lines = [];
var lineUnits = [];
var flushLine = function() {
var line = joinWrapUnits(lineUnits);
if (line.slice(-1) == '\n') line = line.slice(0, -1);
lines.push( escape(line) );
lineUnits = [];
};
if (options.cut === true) {
// Cut mode fills every line to the requested display width, even when that
// means breaking a word. Complete grapheme clusters always stay together.
var lineWidth = 0;
tokens.forEach( function(token) {
token.units.forEach( function(unit) {
if (unit.text.includes('\n')) {
if (stringWidth(joinWrapUnits(lineUnits))) flushLine();
else lineUnits = [];
lineWidth = 0;
return;
}
if (!unit.ansi && lineWidth && ((lineWidth + unit.width) > width)) {
flushLine();
lineWidth = 0;
}
lineUnits.push(unit);
lineWidth += unit.width;
} );
} );
}
else {
tokens.forEach( function(token) {
var tokenText = joinWrapUnits(token.units);
if (token.type == 'break') {
lineUnits = lineUnits.concat(token.units);
if (tokenText.includes('\n')) {
if (stringWidth(joinWrapUnits(lineUnits))) flushLine();
else lineUnits = [];
}
return;
}
var lineText = joinWrapUnits(lineUnits);
var candidateWidth = stringWidth(lineText + tokenText);
if (lineUnits.length && (candidateWidth > width)) flushLine();
lineUnits = lineUnits.concat(token.units);
} );
}
if (lineUnits.length) flushLine();
var result = indent + lines.join(newline);
if (options.trim === true) result = trimWrapLines(result);
return result;
}
module.exports = wordWrap;