• Stars
    star
    10
  • Rank 1,748,272 (Top 36 %)
  • Language
    Ruby
  • License
    Apache License 2.0
  • Created over 14 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simple command line option parsing for Ruby

Ruby

Description

The getopt Ruby library is a simple command line parsing library. It implements a Getopt::Std class for basic command line parsing, as well as a Getopt::Long class for more advanced command line parsing.

Installation

gem install getopt

Adding the trusted cert

gem cert --add <(curl -Ls https://raw.githubusercontent.com/djberg96/getopt/main/certs/djberg96_pub.pem)

Synopsis

Getopt::Std

require 'getopt/std'

# Look for -o with argument, and -I and -D boolean arguments
opt = Getopt::Std.getopts("o:ID")

if opt["I"]
  # Do something if -I passed
  
if opt["D"]
  # Do something if -D passed
  
if opt["o"]
  case opt["o"]
    # blah, blah, blah
  end
end

Getopt::Long

require 'getopt/long'

opt = Getopt::Long.getopts(
  ["--foo", "-f", Getopt::BOOLEAN],
  ["--bar", "-b", Getopt::REQUIRED]
)
 
# Or, to save your fingers some typing:
#
# require "getopt/long"
# include Getopt
# opt = Long.getopts(
#    ["--foo", "-f", BOOLEAN],
#    ["--bar", "-b", REQUIRED]
# )

if opt["foo"]
  # Do something if --foo or -f passed
end

if opt["b"]
  # Do something if --bar or -b passed
end

Singleton Methods

Std.getopts(switches)

Takes a series of single character switches that can be accepted on the command line. Any characters followed by a ":" require an argument. The rest are considered boolean switches.

The method returns a hash, with the switches as the key (minus the leading '-'). For boolean switches, the value is either true or false. Switches that were not passed on the command line do not appear in the hash.

In the event that a switch which accepts an argument appears multiple times the value for that key becomes an array of values.

Long.getopts(switches)

Takes an array of switches beginning with "--" followed by one or more alphanumeric or hyphen characters, or "-" followed by a single character. The type of argument, if any, can be specified as BOOLEAN, OPTIONAL, REQUIRED or INCREMENT.

The array should be in the form:

# long form, short form (alias), option type
["--long", "-l", Getopt::OPTION]

Note that only the long form is required. If the short form is not specified, it will automatically be set to the first letter of the long switch. If multiple long switches with the same first character are listed without short switches, only the first long switch gets the short switch alias.

If the argument type is not specified, the default is BOOLEAN.

For the truly lazy, you can also pass a string of long switches (with no short switches or argument types).

See the 'examples' directory for more examples.

Getopt::Long argument types

REQUIRED

If the option is specified on the command line, it must be followed by a non-blank argument. This argument cannot be another switch. If this switch appears multiple times, the values are collected into an array.

BOOLEAN

If the option is specified on the command line, its value is set to true. It must not be followed by a non-blank argument, excluding other switches. Attempting to pass a boolean switch more than once will raise an error.

OPTIONAL

If the option is specified on the command line, it may or may not accept an argument, excluding other valid switches. If an argument is present, it's value is set to that argument. If an argument is not present, it's value is set to nil.

INCREMENT

If the option is specified on the command line, its value is incremented by one for each appearance on the command line, or set to 1 if it appears only once.

Future Plans

  • Add support for negatable options so that you can do "--no-foo", for example.

  • Add support for numeric types, so that you don't have to manually convert strings to numbers.

  • Allow shortcut characters for the option types, e.g. "?" for BOOLEAN, "+" for INCREMENT, etc.

Known Issues

Getopt::Std

You cannot squish switches that require arguments with the argument itself. For example, if you do Getopt::Std.getopts("o:ID"), it will not parse "-IDohello" properly. Instead, you must do "-IDo hello". Or, you can just separate the argument, e.g. "-I -D -o hello".

Getopt::Long

If you mix and match compressed switches with separate, optional switches the optional switch will be set to true instead of nil if it separated from the compressed switches.

Reporting Issues

If you find any other issues, please log them on the project page at https://github.com/djberg96/getopt.

Other Stuff

Neither class attempts to be POSIX compliant in any way, shape or form.

And I don't care!

Notes From the Author

My main gripe with the getoptlong library currently in the standard library is that it doesn't return a hash, yet gives you partial hash behavior. This was both confusing and annoying, since the first thing I do (along with everyone else) is collect the results into a hash for later processing.

My main gripe with the optparse library (also in the standard library) is that it treats command line processing like event processing. It's too complex, when most of the time all you want to do is slurp the command line options into a hash.

So, I did something utterly novel with this library. I collected the command line options ... (wait for it) ... into a hash! Then I give that hash to you, aliases and all. I did get some ideas from Perl's Getopt::Long library, but this is in no way a port of that module (which supports POSIX parsing, GNU parsing, more option types, etc). My goal was to provide the functionality that I felt would cover the vast majority of common cases, yet still provide a little extra spice with switch types (REQUIRED, OPTIONAL, etc).

There are a few extra things I plan to add (see the 'Future Plans' above) but I do not plan on this library ever becoming as feature rich as, say, Perl's Getopt::Long module.

If you plan to write a full fledged command line application, e.g. you plan on implementing a full help system, gobs of command line options and tons of switches, consider Jim Freeze's commandline gem.

Warranty

This package is provided "as is" and without any express or implied warranties, including, without limitation, the implied warranties of merchantability and fitness for a particular purpose.

License

Apache-2.0

Copyright

(C) 2005-2021, Daniel J. Berger All Rights Reserved

Author

Daniel J. Berger

More Repositories

1

sys-proctable

A cross-platform Ruby interface for gathering process information on your operating system
Ruby
145
star
2

sys-filesystem

A Ruby library for getting filesystem information
Ruby
103
star
3

net-ping

A collection of classes that provide different ways to ping computers.
Ruby
101
star
4

sys-cpu

A Ruby interface for getting CPU information
Ruby
43
star
5

ptools

Extra methods (power tools) for the File class for Ruby
Ruby
38
star
6

sys-uname

A Ruby interface for getting operating system information.
Ruby
28
star
7

rack-auth-kerberos

A Rack library for authenticating users via Kerberos
Ruby
19
star
8

interface

Java style interfaces for Ruby
Ruby
19
star
9

strongtyping

Strong typing for Ruby
C
12
star
10

gis-distance

Calculate geographic distances using latitude and longitude
Ruby
12
star
11

sys-uptime

A Ruby interface for getting system uptime information
Ruby
12
star
12

pr-zlib

A pure Ruby implementation of the zlib library
Ruby
12
star
13

sys-admin

A Ruby library that presents a unified, cross-platform replacement for the Etc module
Ruby
12
star
14

io-extra

Additional methods for the IO class on Unix platforms
C
12
star
15

highlander

Ruby library to prevent multiple instances of the same process from running
Ruby
11
star
16

file-find

A better way to find files with Ruby
Ruby
10
star
17

attempt

A thin wrapper for begin + rescue + sleep + retry.
Ruby
9
star
18

html-table

An interface for generating HTML tables with Ruby, with some rules enforcement
Ruby
8
star
19

linux-kstat

A Ruby library for gathering Linux kernel statistics out of /proc/stat
Ruby
8
star
20

solaris-kstat

A Ruby interface for the kstat (kernel statistics) library on Solaris
Ruby
7
star
21

mail-sympa

A Ruby interface for the Sympa mailing list management software
Ruby
6
star
22

mkmf-lite

A lighter version of mkmf designed for use a library
Ruby
6
star
23

proc-wait3

Adds the wait3, wait4, waitid, pause, sigsend, and getrusage methods to the Ruby Process module
C
6
star
24

pathname2

An alternate implementation of the Pathname class
Ruby
6
star
25

use

A Ruby library that allows you to selectively mixin methods from a module
Ruby
5
star
26

file-temp

An alternative for generating temporary files with Ruby
Ruby
5
star
27

win32-open3

An open3 implementation for Ruby 1.8.x on MS Windows
Ruby
4
star
28

win32-sspi

Yet another Ruby SSPI module
Ruby
4
star
29

crypt-rot13

A Ruby interface for everyone's favorite encryption scheme
Ruby
4
star
30

ez-email

A very easy interface for sending simple text based emails with Ruby
Ruby
4
star
31

archive-tar-external

A Ruby tar and compression library that wraps external system calls
Ruby
4
star
32

enumerable-extra

Modified Enumerable methods designed to make list comprehensions easier
Ruby
3
star
33

hashslice

A Ruby library that adds hash slicing to the core Hash class
Ruby
3
star
34

dbi-dbrc

A database resource control interface for Ruby that lets you avoid hard coding your passwords
Ruby
3
star
35

oracle-model-generator

A Ruby library for generating ActiveRecord models from Oracle tables or views
Ruby
3
star
36

deckbuilder

Proof of concept for a Rails deckbuilding app
Ruby
2
star
37

netrunner-tracker

A web app for tracking games of Android: Netrunner
Ruby
2
star
38

net-proto

A Ruby interface for getting network protocol information
Ruby
2
star
39

apple-system-logger

A Ruby interface for the Apple system logger
Ruby
2
star
40

azure-sastoken

A Ruby library for generating SAS tokens.
Ruby
2
star
41

crystal-uname

A Crystal library for getting operating system information
Crystal
2
star
42

win32-thread

A Ruby interface to native threads on MS Windows
Ruby
2
star
43

sys-memory

A Ruby library for collecting memory information on your system
Ruby
2
star
44

net-tnsping

A Ruby library that simulates the Oracle tnsping utility
Ruby
2
star
45

union

A Ruby analogue of a C union
Ruby
2
star
46

win32-xpath

Custom File.expand_path for Windows
Ruby
2
star
47

secure-manifest

A Rubygems plugin that validates gem contents against its manifest file
Ruby
1
star
48

berger_spec

My own personal Ruby test suite
Ruby
1
star
49

crystal-ptools

A port of my ptools Ruby library over to Crystal
Crystal
1
star
50

notation

A Ruby library that lets you use symbols as method names
Ruby
1
star
51

solaris-file

A specialized File class for Solaris that adds ACL support and door methods
Ruby
1
star
52

crypt-fog

Very simple encryption for Ruby
Ruby
1
star
53

final

A library for simulating the effects of final in Ruby
Ruby
1
star
54

sys-host

A Ruby library that provides hostname and IP address information
C
1
star
55

sctp-socket

Ruby bindings for SCTP sockets
C
1
star
56

facade

A Ruby library that provides an easy way to implement the facade pattern in your classes
Ruby
1
star
57

ansiblestuff

Temporary Repo to futz with my own Ansible playbooks
1
star