Optimist

Optimist is an option parser that "just gets out of your way".

Description

Optimist is a commandline option parser that just gets out of your way. One line of code per option is all you need to write. For that, you get a nice automatically-generated help page, robust option parsing, and sensible defaults for everything you don't specify.

This code is a crystal rewrite and feature improved version of the rubygem: https://github.com/ManageIQ/optimist

Features

See the Extended Features section below for the differences/enhancements

Usage

Code example:

require "optimist"

opts = Optimist.options do
  opt :monkey, "Use monkey mode"                     # flag --monkey, default false
  opt :name, "Monkey name", cls: Optimist::StringOpt # string --name <s>, default nil
  opt :num_limbs, "Number of limbs", default: 4      # integer --num-limbs <i>, default to 4
end

opts.each { |k, v| p [k, v.value, v.given?] }

Example - not setting any command-line options:

$ crystal examples/a_basic_example.cr
["monkey", false, false]
["name", nil, false]
["num_limbs", 4, false]
["help", false, false]

Example - setting some command-line options:

$ crystal examples/a_basic_example.cr -m --num 5
["monkey", true, true]
["name", nil, false]
["num_limbs", 5, true]
["help", false, false]

Example - using -h (help)

$ crystal examples/a_basic_example.cr -h
Options:
  -m, --monkey           Use monkey mode
  -n, --name=<s>         Monkey name
  -u, --num-limbs=<i>    Number of limbs (Default: 4)
  -h, --help             Show this message

See more examples in the examples directory

Main Interface / Basic Features

Differences with the Ruby version

Extended features unavailable in the original Optimist rubygem

Parser Settings

Option Settings

Permitted

Permitted options allow specifying valid choices for an option using lists, ranges or regexp's

Alternate named options

Short options can now take be provided as an Array of list of alternate short-option characters.

Long options can be given alternate names using alt:

See example

Stringflag option-type

It is useful to allow an option that can be set as a string, used with a default string or unset, especialy in the case of specifying a log-file using this usage model:

$ toolname               # no logging
$ toolname --log         # enable logging with a default logfile name
$ toolname --log my.log  # enable logging to my.log

AFAICT this was not possible with the original Optimist. This can be set using cls: Optimist::StringFlagOpt

Installation

  1. Add the dependency to your shard.yml:

    dependencies:
      optimist:
        github: nanobowers/optimist
  2. Run shards install

Contributing

  1. Fork it (https://github.com/your-github-user/optimist/fork)
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Contributors