Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

A modern, powerful commmand line argument parser 🔨

License

NotificationsYou must be signed in to change notification settings

robik/commandr

Repository files navigation

Logo

commandr

A modern, powerful commmand line argument parser.
Batteries included.


❗️ Report a bug ·💡 Request feature



commandr handles all kinds of command-line arguments with a nice and clean interface.
Comes with help generation, shell auto-complete scripts and validation.

Table of Contents

Preview

Installation

Add this entry to yourdub.json file:

"dependencies": {..."commandr":"~>0.1"...  }

FAQ

  • Does it use templates/compile-time magic?

    No, at least currently not. Right now everything is done at runtime, so there's not much overhead on compilation time resources.In the future I'll probably look into generation of compile-time struct.

    The reason is that I want it to be rather simple and easy to learn, and having a lot of generated code hurts e.g. generated documentationand some minor things such as IDE auto-complete (even right now mixin-s cause some problems).

  • Are the results typesafe? / Does it use UDA?

    No, parsed arguments are returned in aProgramArgs class instance that allow to fetch parsed data,

    However it should be possible to generate program definition from struct/class with UDA and thenfill the parsed data into struct instance, but it is currently out of scope of this project (at least for now).

Features

  • Flags (boolean values)

    • Short and long forms are supported (-v,--verbose)
    • Supports stacking of flags (-vvv is same as-v -v -v)
  • Options (taking a string value)

    • Short and long forms are supported (-c test,--config test)
    • Equals sign accepted (-c=1,--config=test)
    • Repeated options are supported (-c 1 -c 2)
    • Default values can be specified.
    • Options be marked as required.
  • Arguments (positional)

    • Required by default, can be marked as optional
    • Default values can be specified.
    • Repeated options are supported (only last argument)
  • Commands (git-style)

    • Infinitely recursive subcommands (you can go as deep as needed)
    • Contains own set of flags/options and arguments
    • Dedicated help output
    • Comfortable command handling withProgramArgs.on()
  • Provided help output

    • Generated help output for your program and sub-commands
    • Can be configured to suit your needs, such as disabling colored output.
    • Provided usage, help and version information.
    • Completly detached from coreProgram, giving you complete freedom in writing your own help output.
    • You can categorize commands for better help output
  • Consistency checking

    • When you build your program model,commandr checks its consistency.
    • Detects name duplications as well as short/long options.
    • Detects required parameters with default value.
  • BASH auto-complete script

    • You can generate completion script with single function call
    • Completion script works on flags, options and sub-commands (at any depth)
    • Acknowledges difference between flags and options
  • Validators

    • Passed values can be checked for correctness
    • Simple process of creating custom validating logic
    • Provided validators for common cases:EnumValidator,FileSystemValidator andDelegateValidator
  • Suggestions

    • Suggestion with correct flag, option or sub-command name is provided when user passes invalid value
    • Also supported forEnumValidator (acceptsValues)

Getting Started

Basic Usage

Simple example showing how to create a basic program and parse arguments:

importstd.stdio;import commandr;voidmain(string[] args) {auto a =new Program("test","1.0")          .summary("Command line parser")          .author("John Doe <me@foo.bar.com>")          .add(new Flag("v",null,"turns on more verbose output")              .name("verbose")              .repeating)          .add(new Option(null,"test","some teeeest"))          .add(newArgument("path","Path to file to edit"))          .parse(args);      writeln("verbosity level", a.occurencesOf("verbose"));      writeln("arg:", a.arg("path"));}

Subcommands

You can create subcommands in your program or command using.add. You can nest commands.

Adding subcommands adds a virtual required argument at the end to your program. This makes you unable to declare repeating or optional arguments (because you cannot have required argument past these).

Default command can be set with.defaultCommand(name) call after defining all commands.

After parsing, every subcommand gets its ownProgramArgs instance, forming a hierarchy. Nested args inherit arguments from parent, so that options defined higherin hierarchy are copied.ProgramArgs defines a helper methodon, that allows to dispatch method on specified command.

auto args =new Program("test","1.0")      .add(new Flag("v",null,"turns on more verbose output")          .name("verbose")          .repeating)      .add(new Command("greet")          .add(newArgument("name","name of person to greet")))      .add(new Command("farewell")          .add(newArgument("name","name of person to say farewell")))      .parse(args);args  .on("greet", (args) {// args.flag("verbose") works    writefln("Hello %s!", args.arg("name"));  })  .on("farewell", (args) {    writefln("Bye %s!", args.arg("name"));  });

Delegate passed toon function receivesProgramArgs instance for that subcommand. Because it is alsoProgramArgs,on chain can be nested, as in:

// assuming program has nested subcommandsa.on("branch", (args) {  args    .on("add", (args) {      writefln("adding branch %s", args.arg("name"));    })    .on("rm", (args) {      writefln("removing branch %s", args.arg("name"));    });});

Validation

You can attach one or more validators to options and arguments withvalidate method. Every validator has its own helper function that simplifies adding it do option (usually starting withaccepts):

newProgram("test")// adding validator manually  .add(new Option("s","scope","")      .validate(new EnumValidator(["local","global","system"]))  )// helper functionnew Program("test")  .add(new Option("s","scope","")      .acceptsValues(["local","global","system"]));

Built-in validators

  • EnumValidator - Allows to pass values from white-list.

    Helpers:.acceptsValues(values)

  • FileSystemValidator - Verifies whenever passed values are files/directories or just exist (depending on configuration).

    Helpers:.acceptsFiles(),.acceptsDirectories(),.acceptsPaths(bool existing)

  • DelegateValidator - Verifies whenever passed values with user-defined delegate.

    Helpers:.validateWith(delegate),validateEachWith(delegate)

You can create custom validators either by implementingIValidator interface, or by usingDelegateValidator:

newProgram("test")// adding validator manually  .add(new Option("s","scope","")      .validateEachWith(opt=> opt.isDirectory,"must be a valid directory")  );

Printing help

You can print help for program or any subcommand withprintHelp() function:

program.printHelp();// prints program helpprogram.commands["test"].printHelp();

To customise help output, passHelpOutput struct instance:

HelpOutput helpOptions;helpOptions.colors =false;helpOptions.optionsLimit =2;program.printHelp(helpOptions);

Bash autocompletion

Commandr can generate BASH autocompletion script. During installation of your program you can save the generated script to/etc/bash_completion.d/<programname>.bash (or any other path depending on distro).

import commandr;import commandr.completion.bash;string script = program.createBashCompletionScript();// save script to file

Configuration

TODO

Cheat-Sheet

Defining entries

Overview of available entries that can be added to program or command with.add method:

WhatTypeExampleDefinition
Flagbool--verbosenew Flag(abbrev?, full?, summary?)
Optionstring[]--db=testnew Option(abbrev?, full?, summary?)
Argumentstring[]123new Argument(name, summary?)

Reading values

Shows how to access values after parsing args.

Examples assumeargs variable contains result ofparse() orparseArgs() function calls (an instance ofProgramArgs)

ProgramArgs args = program.parse(args);
WhatTypeFetch
Flagboolargs.flag(name)
Flagintargs.occurencesOf(name)
Optionstringargs.option(name)
Optionstring[]args.options(name)
Argumentstringargs.arg(name)
Argumentstring[]args.args(name)

Property Matrix

Table below shows which fields exist and which don't (or should not be used).

Columnname contains name of the method to set the value. All methods returnthis to allow chaining.

NameProgramCommandFlagOptionArgument
.name✔️✔️✔️✔️✔️
.version_✔️✔️️❌
.summary✔️️️:heavy_check_mark:️❌
.description️❌✔️️:heavy_check_mark:✔️
.abbrev✔️✔️
.full✔️️️:heavy_check_mark:
.tag️:heavy_check_mark:✔️️
.defaultValue️:heavy_check_mark:✔️️
.required️:heavy_check_mark:✔️️
.optional️:heavy_check_mark:✔️️
.repeating✔️️:heavy_check_mark:✔️️
.topic✔️️❌
.topicGroup✔️✔️️❌
.authors✔️️❌
.binaryName✔️️❌

Roadmap

Current major missing features are:

  • Command/Option aliases
  • Combined short flags/options (e.g.-qLob)
  • EnumValidator/FileSystemValidator auto-completion hinting

See theopen issues for a list of proposed features (and known issues).


[8]ページ先頭

©2009-2025 Movatter.jp