cli

Arguments, questions, tables, progress bars and colors.

v1.0.0Tooling & CLIbundledimport "cli";
Overview Installation Documentation Examples

Overview

Everything a command-line program needs: parse --options and arguments, ask questions, print aligned tables and progress bars, and color the output.

bundled — works offline --name=value, flags, -abc ask / confirm / choose tables, progress, colors

Quick start

import "cli";

$args = cli_args();                       // tool --out=dist -v build
if ($args->has("v")) {
    echo cli_color("verbose mode", "gray");
}
$target = $args->arg(0, "build");
$out = $args->get("out", "build");
echo "building " . $target . " into " . $out;

echo cli_table(["file", "bytes"], [["main.hphp", "812"], ["lib.hphp", "2048"]]);

Installation

In a project

Inside a project (a folder with hphp.yaml, see Projects & packages):

hphp install cli

This adds the library to hphp.yaml, installs it into .hphp/packages/cli/ and pins the exact version in hphp.lock:

require:
  cli: "^1.0"

Use it

import "cli";

cli is bundled with the compiler, so import "cli"; also works in a single file without installing anything, and hphp install works offline.

Outside a project

hphp install cli          # for your user, shared by all scripts
hphp create myapp                 # or start a project, then: hphp install cli
Packagecli
Version1.0.0 (follows the compiler)
Entry filecli.hphp
Sourcepackages/lib/cli ↗

Documentation

Arguments

cli_args() parses the program's own arguments ($argv without the program name); cli_parse($list) parses any list, which is handy in tests.

InputResult
--out=distget("out") → "dist"
--verbosehas("verbose"), get("verbose") → "true"
-xzflags x and z
build srcarg(0) → "build", arg(1) → "src"
-- --not-an-optioneverything after -- is positional
-5negative numbers stay positional
CliArgs methodReturns
has($name)whether the option was given
get($name, $default = "")the value as a string
int($name, $default = 0)the value as an int
arg($i, $default = "")positional argument $i
count()number of positional arguments

Questions

FunctionWhat it does
cli_ask($question, $default = "")a line of input; Enter keeps the default
cli_confirm($question, $default = false)y/n (also j for German keyboards)
cli_choose($question, $options, $default = 0)numbered menu; returns the chosen index

Output

FunctionWhat it does
cli_table($headers, $rows)aligned columns with a rule under the header
cli_progress($done, $total, $width = 30)[#######.......] 25%
cli_color($text, $color)red, green, yellow, blue, magenta, cyan, gray, bold, dim, underline
cli_strip($text)removes color codes
cli_width($text) / cli_pad($text, $n)visible width (ignores colors, counts UTF-8 characters)

Examples

4 complete programs. Every one is type-checked with the compiler before the site is published; copy one into src/ of a project (hphp create) and run it.

01A command with options

cli_args() reads the program's arguments: --name=value options, --flag switches, -abc short flags and plain positional arguments. This tool greets everyone named on the command line.

01-arguments.hphp
<?php
import "cli";

$args = cli_args();

// usage help when nothing was given
if ($args->count() == 0 || $args->has("help")) {
    echo "usage: greet [--greeting=Hello] [--shout] <name>...";
    exit(1);
}

$greeting = $args->get("greeting", "Hello");
$shout = $args->has("shout");

// one line per positional argument
for ($i = 0; $i < $args->count(); $i++) {
    $line = $greeting . ", " . $args->arg($i) . "!";
    if ($shout) {
        $line = strtoupper($line);
    }
    echo $line;
}
Try it
hphp run 01-arguments.hphp Ada Grace
hphp run 01-arguments.hphp --greeting=Hi --shout Ada

02An interactive setup

Asks a few questions like an installer would: free text with a default (cli_ask), a numbered menu (cli_choose) and a yes/no question (cli_confirm). Enter always keeps the value in brackets.

02-interactive-setup.hphp
<?php
import "cli";

echo cli_color("New project", "bold");
echo "";

// questions
$name = cli_ask("Project name", "my_app");
$kinds = ["console app", "web server", "library"];
$kind = cli_choose("What do you want to build?", $kinds, 0);
$tests = cli_confirm("Add tests?", true);

// summary
echo "";
echo cli_table(["setting", "value"], [
    ["name", $name],
    ["kind", $kinds[$kind]],
    ["tests", $tests ? "yes" : "no"],
]);
echo "";

if (cli_confirm("Create it?", true)) {
    echo cli_color("created " . $name, "green");
} else {
    echo cli_color("cancelled", "yellow");
}
Try it
hphp run 02-interactive-setup.hphp

03A file report with a table

Lists the files of a folder, largest first, as an aligned table. cli_table() pads every column to its widest cell (colors do not count), so the output stays readable in any terminal.

03-file-report.hphp
<?php
import "cli";

$dir = cli_args()->arg(0, ".");

// collect [name, size] for every regular file
$files = [];
foreach (scandir($dir) as $name) {
    $path = $dir . "/" . $name;
    if ($name != "." && $name != ".." && is_file($path)) {
        $files[] = [$name, filesize($path)];
    }
}

// largest first
usort($files, function($a, $b) {
    return $b[1] - $a[1];
});

// format the rows; big files in yellow
$rows = [];
$total = 0;
foreach ($files as $f) {
    $size = number_format($f[1]) . " B";
    if ($f[1] > 100000) {
        $size = cli_color($size, "yellow");
    }
    $rows[] = [$f[0], $size];
    $total = $total + $f[1];
}

echo cli_table(["file", "size"], $rows);
echo "";
echo count($files) . " files, " . number_format($total) . " bytes";
Try it
hphp run 03-file-report.hphp
hphp run 03-file-report.hphp ../..

04A progress bar

cli_progress() returns the bar as a string; print it with a carriage return (\r) through printf so it redraws in place instead of adding a line each step.

04-progress.hphp
<?php
import "cli";

$steps = 40;

for ($i = 1; $i <= $steps; $i++) {
    // pretend to work
    usleep(50000);

    // redraw the same line
    printf("\r%s  step %d/%d", cli_progress($i, $steps), $i, $steps);
}

echo "";
echo cli_color("done", "green");
Try it
hphp run 04-progress.hphp