Nette Command-Line 2.0: The Help That Writes Itself

37 minutes ago by David Grudl  

For thirteen years, all nette/command-line needed was a look at your help text, and it figured out what your script could do. Version 2.0 turns this around: you write the method that does the work, and the library writes the help for you. In color, this time.

The Laziest Parser in the World

The parser from 2013 honestly said Stupid command line arguments parser in its docblock. And its trick really was simple: you didn't have to describe anything to it. You wrote the help you would have written for the script anyway, and it read from it what the script accepts:

$parser = new Parser('
Usage: convert.php [options] <files>...

Options:
	-f, --format <jpg|png|webp>  Target format (default: webp)
	-n, --dry-run                Only show what would be done
', [
	'files' => [Parser::Repeatable => true],
]);

$args = $parser->parse();

Angle brackets mean an option with a value, the pipes inside them the allowed values, (default: webp) the default value and -n, --dry-run the short form. No API, no configuration, just text written for people. And since the help itself was the definition, it could never lie. Documentation that quietly goes stale because someone added an option and forgot to describe it simply could not happen here.

It was a good idea and it worked for years. Nette Tester still lives by it.

But You Want This

The help of today's tools comes in color. Headings stand out, options have their own color, default values fade into gray. Once you see it, black-and-white text starts to look like a printout from 1995. You want it too.

You can put colors into a heredoc. But writing \e[38;2;215;175;95m into your help is a pain, reading it afterwards too, and in a log or a pipe it turns into unreadable mush. You align the columns by hand, and as soon as a description doesn't fit the width of the terminal, the layout falls apart. And once the script gets commands, each with its own help, one text suddenly becomes ten.

The example above also hides a small confession. The argument files couldn't be written into the help, so it ended up in the second array. Everything the text couldn't express went there: normalizing values, checking paths, repetition. The more the script could do, the more of its description moved out of the help.

So, the Other Way Around

Version 2.0 keeps the principle and only reverses the direction. You still don't describe what the command line can do. You still write only what you would have written anyway. Except it's no longer the help, it's the method that does the actual work:

use Nette\CommandLine\Attributes as Cli;

final class ImageConverter
{
	#[Cli\Command('Converts images to another format')]
	public function convert(
		#[Cli\Argument('Images to convert', repeatable: true)]
		array $files,
		#[Cli\Option('Target format', alias: '-f', enum: ['jpg', 'png', 'webp'])]
		string $format = 'webp',
		#[Cli\Flag('Only show what would be done', alias: '-n')]
		bool $dryRun = false,
	): int
	{
		// converts the files to $format, with $dryRun only prints what it would do
		return 0;
	}
}

And running it:

$converter = new ImageConverter;
$program = Command::from($converter->convert(...));
$runner = new Runner($program, title: 'Converter', version: '1.0');
exit($runner->run());

That's the whole script. The help in the screenshot above is its output, and you didn't write a single line of it. You never touch $argv, you parse nothing, the values arrive straight in the parameters. The parameter $dryRun becomes the option --dry-run, its default value becomes the default value of the option, and the texts in the attributes are the descriptions in the help. Runner adds --help and --version on its own, calls the method, and whatever it returns is the exit code of the script.

Users can type the way they're used to: --format png, --format=png and -f png mean the same, single-letter options can be stuck together (-nf png) and options may stand anywhere between the files.

The best thing about version 1.x stays. The help comes from the same method that does the work, so it still can't claim anything other than what the script really does. It's just guarded from the other side now.

Underneath the attributes lies a plain API with methods like addOption(). It comes in handy for a quick script without a class or when you put the options together at runtime; you'll find more about it in the documentation.

The Signature Says More Than You'd Expect

The attributes mostly carry descriptions. The library reads most of the rest from plain PHP. The method name removeDuplicates() gives the command remove-duplicates, a parameter with a default value is optional, and a parameter typed by a backed enum gets its list of allowed values for free:

enum Format: string
{
	case Jpg = 'jpg';
	case Png = 'png';
	case Webp = 'webp';
}

// ...
#[Cli\Option('Target format', alias: '-f')]
Format $format = Format::Webp,

The help then shows --format <jpg|png|webp> and the method gets Format::Png instead of a string.

The library also checks that the signature makes sense, right at startup, not when a user runs into the problem. If you add int $quality = 80 and forget that the command line always delivers a string, you find out on the very first run, whatever command you type:

Parameter $quality of handler ImageConverter::convert() does not accept string,
which option --quality gives as its value.

All it takes is a normalizer on the option, such as Normalizers::int(), which checks the string and turns it into a number.

When the User Makes a Mistake

On a typo, version 1.x threw an exception, and unless you handled it yourself, the user stared at a stack trace. Version 2.0 answers like a well-behaved tool:

The help follows right below the message, so there's nothing to look up, and the script ends with exit code 2, the traditional way to report a wrong command line. Your method isn't called at all in that case, so it never runs with nonsensical values.

The Script Grows

Today it converts images, tomorrow it should shrink them too. Tools like that are controlled by commands, much like composer install and composer update. You don't rewrite anything: each command is one method with the #[Cli\Command] attribute, and you add a whole class of such methods in a single call. The program itself no longer has a method of its own, it's just a wrapper that holds the commands, which is why you create it with new Command:

$tools = new ImageTools;  // contains the methods convert() and resize()
$program = new Command('images', commandRequired: true);
$program->addCommandsFrom($tools);

$runner = new Runner($program, title: 'Images', version: '1.0');
exit($runner->run());

Each command has its own help (php images.php convert --help) and commands can be nested. When a user types an option of another command, the library tells them where it belongs: Option --width belongs to command resize.

What's more interesting is how to handle options that several commands need. You describe them once, in the constructor of a class:

final readonly class Output
{
	public function __construct(
		#[Cli\Option('Directory for the results', valueName: 'dir')]
		public ?string $outputDir = null,
		#[Cli\Flag('Overwrite existing files')]
		public bool $overwrite = false,
	) {
	}
}

And every command that needs them asks for them with a parameter:

#[Cli\Command('Converts images to another format')]
public function convert(
	#[Cli\Argument('Images to convert', repeatable: true)]
	array $files,
	Output $output,
): int

The command convert now accepts --output-dir and --overwrite, and so does every other command whose method takes Output. When the command runs, the library builds the object from the values of these options and passes it to the method. No array, no keys, just a typed object.

A Console That Knows Where It Writes

A script doesn't only read, it also prints. That's what the Console class is for, and it's the part that moved furthest since 1.x. You add colors with methods, never with markup in the text:

$console = new Console;
$console->writeLine('3 images converted', 'green');
$console->writeLine($console->color('gray', 'Results in ') . $outputDir);

Nothing is looked up in the text, so you don't have to escape XML, HTML or user input. And above all, it isn't your code that decides about colors, it's where the output goes. In a terminal it's in color; in a pipe, a file or CI the same code prints plain text. NO_COLOR and FORCE_COLOR are respected, and hex colors are drawn as the nearest color an older terminal can show.

During longer work it helps to show what the script is doing. That's what the status line is for. setStatus() draws it at the end of the output, and the next call overwrites it with new text. When you print something with writeLine() in the meantime, the status line disappears and the text takes its place. The next setStatus() then draws it again, one line lower. At the end, clearStatus() removes it completely:

foreach ($files as $i => $file) {
	$console->setStatus(sprintf('%d/%d  %s', $i + 1, count($files), $file));  // 4/12  holiday.jpg
	// ... converts the file
	$console->writeLine($console->color('green', '✓') . " $file → $target");  // takes the place of the status line
}
$console->clearStatus();

The results pile up and below them a single line keeps changing. Not a character of it ends up in a log, because outside a terminal setStatus() does nothing at all.

And when the script needs a decision only a person can make, Prompt asks for it:

$prompt = new Prompt($console);
$answer = $prompt->choose('Overwrite photo.webp?', ['y', 'n', 'a', 'q'], default: 'n');
// Overwrite photo.webp? [y/N/a/q]

It asks only when someone really sits at the terminal, so it never takes an answer from a pipe nobody is watching. What the script should do without a person, you decide up front with $prompt->isInteractive().

Upgrading from 1.x

Version 2.0 is a new API without a compatibility layer, so scripts built on 1.x need to be rewritten. Luckily, that's exactly the kind of work for an AI agent: the Nette plugin for Claude Code and Codex includes a guide by which the agent rewrites the code faithfully and points out every place where 2.0 behaves differently.

If you're still figuring out how to organize CLI scripts in a Nette application in the first place, have a look at the earlier article CLI Scripts in a Nette Application. Everything else is in the documentation.

composer require nette/command-line

Thirteen years ago you wrote the help and the parser took care of the rest. Today you write a method and the library takes care of the rest, the help included. It is still what it always was: an exact description of what your script can do. Only now it's in color.

David Grudl Open-source creator and AI specialist who opens doors to the world of artificial intelligence. His projects including Nette and Texy! power websites you visit daily. He contributes to Uměligence and La Trine while hosting Tech Guys. Through AI workshops, he champions technology that genuinely improves people's lives.