All Projects → funbox → Optimus

funbox / Optimus

Licence: mit
Command line arguments parser for Elixir

Programming Languages

elixir
2628 projects

Projects that are alternatives of or similar to Optimus

minimist2
TypeScript/JavaScript ES6 rewrite of popular Minimist argument parser
Stars: ✭ 20 (-81.82%)
Mutual labels:  argument-parser
Kotlin Argparser
Easy to use and concise yet powerful and robust command line argument parsing for Kotlin
Stars: ✭ 431 (+291.82%)
Mutual labels:  argument-parser
Argh
Rust derive-based argument parsing optimized for code size
Stars: ✭ 803 (+630%)
Mutual labels:  argument-parser
AnyOption
C/C++ Command line and resource file option parsing
Stars: ✭ 83 (-24.55%)
Mutual labels:  argument-parser
Structopt
Parse command line arguments by defining a struct
Stars: ✭ 323 (+193.64%)
Mutual labels:  argument-parser
Clap
Create your command-line parser, with all of the bells and whistles, declaratively or procedurally.
Stars: ✭ 7,174 (+6421.82%)
Mutual labels:  argument-parser
go-getoptions
Fully featured Go (golang) command line option parser with built-in auto-completion support.
Stars: ✭ 41 (-62.73%)
Mutual labels:  argument-parser
Clikt
Multiplatform command line interface parsing for Kotlin
Stars: ✭ 1,658 (+1407.27%)
Mutual labels:  argument-parser
Fire Hpp
Fire for C++: Create fully functional CLIs using function signatures
Stars: ✭ 395 (+259.09%)
Mutual labels:  argument-parser
Argh
Argh! A minimalist argument handler.
Stars: ✭ 752 (+583.64%)
Mutual labels:  argument-parser
Argparse
Argparse for golang. Just because `flag` sucks
Stars: ✭ 294 (+167.27%)
Mutual labels:  argument-parser
Caporal.js
A full-featured framework for building command line applications (cli) with node.js
Stars: ✭ 3,279 (+2880.91%)
Mutual labels:  argument-parser
Argparse
Argument Parser for Modern C++
Stars: ✭ 680 (+518.18%)
Mutual labels:  argument-parser
cpp-utilities
Common C++ classes and routines used by my applications such as argument parser, IO and conversion utilities
Stars: ✭ 35 (-68.18%)
Mutual labels:  argument-parser
Argumentum
C++ command line parsing library
Stars: ✭ 92 (-16.36%)
Mutual labels:  argument-parser
cmd-ts
💻 A type-driven command line argument parser
Stars: ✭ 92 (-16.36%)
Mutual labels:  argument-parser
Clize
CLIze: Turn Python functions into command-line interfaces
Stars: ✭ 439 (+299.09%)
Mutual labels:  argument-parser
Sywac
🚫 🐭 Asynchronous, single package CLI framework for Node
Stars: ✭ 109 (-0.91%)
Mutual labels:  argument-parser
Typescript To Cli
Transform your typescript module into a CLI
Stars: ✭ 101 (-8.18%)
Mutual labels:  argument-parser
Clipp
easy to use, powerful & expressive command line argument parsing for modern C++ / single header / usage & doc generation
Stars: ✭ 687 (+524.55%)
Mutual labels:  argument-parser

Optimus

Optimus avatar: Transformer's head shaped as a letter “O”

Build Status Coverage Status

A command line arguments parsing library for Elixir.

It's aim is to take off the maximum possible amount of manual argument handling. The intended use case is to configure Optimus parser, run it against the command line and then do nothing but take completely validated ready to use values.

The library was strongly inspired by the awesome clap.rs library. Optimus does not generally follow its design, but it tries to follow the idea of zero manual manipulation with the values after the parser has returned them.

Installation

Add optimus to your list of dependencies in mix.exs:

def deps do
  [{:optimus, "~> 0.2"}]
end

Example

Let's configure a CLI interface to an imaginary utility which reads data from a file of the following format:

# timestamp, value
1481729245, 12.0
1481729245, 13.0
1481729246, 11.1
...

and outputs some statistic metrics of the values. It also has a subcommand which validates the source file integrity.

defmodule Statcalc do
  def main(argv) do
    Optimus.new!(
      name: "statcalc",
      description: "Statistic metrics calculator",
      version: "1.2.3",
      author: "John Smith [email protected]",
      about: "Utility for calculating statistic metrics of values read from a file for a certain period of time",
      allow_unknown_args: false,
      parse_double_dash: true,
      args: [
        infile: [
          value_name: "INPUT_FILE",
          help: "File with raw data",
          required: true,
          parser: :string
        ],
        outfile: [
          value_name: "OUTPUT_FILE",
          help: "File to write statistics to",
          required: false,
          parser: :string
        ]
      ],
      flags: [
        print_header: [
          short: "-h",
          long: "--print-header",
          help: "Specifies wheather to print header before the outputs",
          multiple: false,
        ],
        verbosity: [
          short: "-v",
          help: "Verbosity level",
          multiple: true,
        ],
      ],
      options: [
        date_from: [
          value_name: "DATE_FROM",
          short: "-f",
          long: "--from",
          help: "Start date for the period",
          parser: fn(s) ->
            case Date.from_iso8601(s) do
              {:error, _} -> {:error, "invalid date"}
              {:ok, _} = ok -> ok
            end
          end,
          required: true
        ],
        date_to: [
          value_name: "DATE_TO",
          short: "-t",
          long: "--to",
          help: "End date for the period",
          parser: fn(s) ->
            case Date.from_iso8601(s) do
              {:error, _} -> {:error, "invalid date"}
              {:ok, _} = ok -> ok
            end
          end,
          required: false,
          default: &Date.utc_today/0
        ],
      ],
      subcommands: [
        validate: [
          name: "validate",
          about: "Validates the raw contents of a file",
          args: [
            file: [
              value_name: "FILE",
              help: "File with raw data to validate",
              required: true,
              parser: :string
            ]
          ]
        ]
      ]
    ) |> Optimus.parse!(argv) |> IO.inspect
  end
end

(The whole sample code can be found in optimus_example repo.)

Nearly all of the configuration options above are not mandatory.

Also most configuration parameters are self-explanatory, except parser. For options and positional arguments parser is a lambda which accepts a string argument and returns either {:ok, parsed_value} or {:error, string_reason}. There are also some predefined parsers which are denoted by atoms: :string, :integer and :float. No parser means that :string parser will be used.

Not required options can have a default value. Both a term (string, number, etc.) or a lambda with zero arity can be used. If the option accepts multiple values, the default value should be a list, for example [1.0] or fn -> ["x", "y"] end.

Now if we try to launch our compiled escript without any args we'll see the following:

>./statcalc
The following errors occured:
- missing required arguments: INPUT_FILE
- missing required options: --from(-f), --to(-t)

Try
    statcalc --help

to see available options

There are several things to note:

  • the script exited (in Optimus.parse!) since we haven't received a valid set of arguments;
  • a list of errors is displayed (and it's as full as possible);
  • a user is offered to launch statcalc with --help flag which is automatically handled by Optimus.

If we launch statcalc --help, we'll see the following:

>./statcalc --help
Statistic metrics calculator 1.2.3
John Smith [email protected]
Utility for calculating statistic metrics of values read from a file for a certain period of time

USAGE:
    statcalc [--print-header] --from DATE_FROM --to DATE_TO INPUT_FILE [OUTPUT_FILE]
    statcalc --version
    statcalc --help
    statcalc help subcommand

ARGS:

    INPUT_FILE         File with raw data
    OUTPUT_FILE        File to write statistics to

FLAGS:

    -h, --print-header        Specifies wheather to print header before the
                              outputs

OPTIONS:

    -f, --from        Start date for the period
    -t, --to          End date for the period  (default: 2017-12-20)

SUBCOMMANDS:

    validate        Validates the raw contents of a file

The things to note are:

  • Optimus formed a formatted help information and also exited;
  • it also offers some other autogenerated commands (--version and help subcommand).

Now if we finally produce a valid list of args, we'll have our arguments parsed:

>./statcalc --print-header -f 2016-01-01 -t 2016-02-01 infile.raw outfile.dat
%Optimus.ParseResult{
  args: %{
    infile: "infile.raw",
    outfile: "outfile.dat"
  },
  flags: %{
    print_header: true
  },
  options: %{
    date_from: ~D[2016-01-01],
    date_to: ~D[2016-02-01]
  },
  unknown: []
}

Optimus.ParseResult is a struct with four fields: args, flags, options, which are maps, and unknown, which is a list. Things to note are:

  • unknown list is always empty if we set allow_unknown_args: false for our (sub)command;
  • values in args, flags and options maps are kept under keys specified in configuration;
  • for options with multiple: true the value is a list;
  • for flags without multiple: true the value is a boolean;
  • for flags with multiple: true the value is an integer (representing the number of occurrences of a flag).

Credits

Brutal picture for the project was made by Igor Garybaldi.

Sponsored by FunBox

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].