OptHash.

One who ever wrote a program designed to be run from the command line knows that he had to deal with command line options, parse the command line, retrieve the options, check for presence of mandatory options, supply default values for optional options etc. He also had to maintain a --help option output which reflects the actual usage of the program.

If you enjoy this job, OptHash is not for you.


1 Introduction.

OptHash

For now, it doesn't make coffe, maybe tea if you ask politely.

OptHash's name (i.e. "OptHash") may be confusing as it doesn't return a hash but an array, the first entry of this array is the (option => arg) hash, the second entry is the remaining arguments array.
For short, it returns : [ options-hash, arg-array ]

2 Quick start.

Say you wrote an program example.rb using OptHash, an end-user installs it and wants to know all the options this program accepts, he types :

example.rb --help
and gets this result :
Usage   : example.rb --config arg --action arg [--dir [arg],...] 
		[--verbosity [arg]] [-z] [--help] 
		[--version] 
Options :
	--config -c arg 
		Required: Configuration file.
	--action -a arg 
		Required: Action to perform.
	--dir --path -d -p [arg] ,... (default <./>)
		Optional: Directory to process.
	--verbosity -v [arg] (default <1>)
		Optional: Specify verbosity level (0..3).
	*Note* : Following options are deprecated.
	-z 
		Optional: Ignored, kept for SYSV compatibility.
	Or
	--help -h 
		Display these informations and exit successfully.
	Or
	--version -V 
		Display program version and exit successfully.

He wants to know more and tries using your program :

example.rb --config /home/pat \
    --action search --dir "/lib /usr/lib/ /var/lib"\
    --dir /usr/local/lib \
    blah foo,bar blurb --print
example.rb will receive this structure :
[{"verbosity"=>"1",
  "dir"=>["/lib", "/usr/lib/", "/var/lib", "/usr/local/lib"],
  "config"=>"/home/pat",
  "action"=>"search"},
 ["blah", ["foo", "bar"], "blurb", "--print"]]

In fact, the user will also receive this result as example.rb is a fake program which only prints what it received from OptHash.
Here is this program :

#!/usr/bin/env ruby
require 'rubrix/opthash'
require 'pp'

optArray =
[
[ "--config", "-c",
            OptHash::REQUIRED_ARGUMENT, nil, true, OptHash::SINGLE_ARGUMENT,
            "Configuration file." ],
[ "--action", "-a",
            OptHash::REQUIRED_ARGUMENT, nil, true, OptHash::SINGLE_ARGUMENT,
            "Action to perform." ],
[ "--dir", "--path", "-d", "-p",    
            OptHash::OPTIONAL_ARGUMENT, './', false, OptHash::LIST_ARGUMENT,
            "Directory to process." ],
[ "--verbosity",  "-v",
            OptHash::OPTIONAL_ARGUMENT, '1', false, OptHash::SINGLE_ARGUMENT,
            "Specify verbosity level (0..3)." ],
  '*Note* : Following options are deprecated.',
[ "-z",
            OptHash::NO_ARGUMENT, nil , false, 0,
            "Ignored, kept for SYSV compatibility." ],
]


parser = OptHash::OptH.new( { 'posixly' => true, 'optPerLine' => 3 } )
opt = parser.opt2h( "example.rb", "Version 2.1.0 i386", optArray )
pp( opt )

Well, at first sight it may seem a bit esoteric...
The program has to require the opthash module.
The optArray are specifications to OptHash. It describes options and their arguments.
The program instantiates the OptH class then calls its opt2h method to parse the command line.

Either the end-user entered the --help or --version option (or some error for which he will be warned) and the program terminates after displaying the requested information, either the program receive an array from where the command line can be accessed in a simple way.
For instance, if we refer to the the example above, the program can access the config option argument by a simple instruction :

confArg = opt[ 0 ][ "config" ]

3 A more formal approach attempt.

3.1 The OptHash module.

OptHash is a module in which the OptH class is defined, this class consist mostly in a method : opt2h. In this module, outside the OptH class, the opt2hash method is defined, it creates an OptH instance object and calls it's opt2h method which will use its defaults arguments.

The Object Oriented way to use optHash is to create an OpH class instance and initialize it with arguments which will change it's behaviour.

3.2 The OO interface.

Return a new OptH object.

The Hash argument may contain :

The instance method :

returns an Array.

opt2h returns a two entries array, the first entry is a hash, the second is an array.

The option set array passed to opt2hash :

Entries in this array may be

The option array set entry.

It is an array which contains the following entries :
  1. One or more option names entries, like "--dir" "-d" "--path" "-p". the first entry with leading '-' stripped will be the name of the option in the output hash, others are aliases.
  2. An entry describing the option argument. it's value may be :
    • OptHash::NO_ARGUMENT
    • OptHash::REQUIRED_ARGUMENT
    • OptHash::OPTIONAL_ARGUMENT
  3. The argument default value. this argument is put in the hash when no option or no argument is supplied by the user
  4. True when this option is mandatory, false when this option is optional
  5. The argument format, may be :
    • 0 (N/A)
    • OptHash::SINGLE_ARGUMENT
    • OptHash::LIST_ARGUMENT
  6. A description string for the --help option.

3.3 Micellaneous notes.

When an option appears twice or more on the command line, when this option accepts an argument list, the arguments of all the instances of the option are put in the option argument array. When the option accepts a single argument, the last option argument (or nil when the argument is optional and not present) is put in the hash.

An option in the command line may appear as an unambiguous abbreviation of the defined option.

4 Installation.

OptHash had only been tested on a GNU/Linux system.
It, and more especially its test suite may not work on other systems.
OptHash had been developped with Ruby 1.8, but it should work with previous versions of Ruby.

Unzip the tarball with tar xzvf opthash-version.tar.gz, it ceates the opthash-version directory, then read the README file in that directory.

Since version 1.1.0, opthash is installed in the rubrix directory of your Ruby library directory, thus now use : require 'rubrix/opthash.rb'

Download page

Send bug reports to almazz at wanadoo dot fr

5 Legal informations.

OptHash is copyrighted : Copyright (C) 2005 Patrick Davalan. All rights reserved.
OptHash is free software it may be used, modified and distributed under the same terms as Ruby.
See the file COPYING in the OptHash distribution.

OptHash is provided "as is" without any warranty.

This software is OSI Certified Open Source Software.
"OSI Certified" is a certification mark of the Open Source Initiative.

keywords : Ruby, opthash, command line parser, free software,
1 Introduction.
2 Quick start.
3 A more formal approach attempt.
3.1 The OptHash module.
3.2 The OO interface.
3.3 Micellaneous notes.
4 Installation.
5 Legal informations.
Alma inside !