getopt2

Crates.iogetopt2
lib.rsgetopt2
version0.1.0-alpha.1
created_at2025-09-17 00:48:32.000252+00
updated_at2025-09-17 00:48:32.000252+00
descriptionZero dependency strict command line argument parser
homepagehttps://gitlab.com/hsn10/getopt2
repositoryhttps://gitlab.com/hsn10/getopt2.git
max_upload_size
id1842622
size62,198
Radim Kolar (hsn10)

documentation

README

getopt2 - strict command line argument parser for Rust

Version 0.1.0 MIT Licensed

License: MIT Crates.io Version MSRV Crates.io Safe Rust dependency status Documentation Downloads

Features

  1. GNU argument parsing rules. Options can be anywhere in command line before --
  2. double dash -- support. Anything after -- is not treated as options.

Code quality

  1. MSRV 1.56, accessible from entire Rust 2021 Edition.
  2. Rust port of well tested Scala getopt code.
  3. Small code size. Less than 200 LOC.
  4. Zero dependencies.
  5. No unsafe Rust.
  6. Runs on stable 2021 Edition Rust.
  7. 68 unit tests + 1 quick check test + 7 integration tests + 6 doc tests.

Usage

1. Create getopt instance

let g = getopt2::new(arguments, optstring)

getopt2::new constructor arguments:

  1. arguments command line arguments. Can be anything what can be converted to Iterator over String. You can use std::env::args() but you need to skip first argument because its executable name. It can be done manually or by calling hideBin utility function which strips its first argument.
  2. optstring is a anything providing AsRef <str>. optstring is containing the legitimate option characters. Valid option characters are alphanumeric plus '?'. If such a character is followed by a colon, the option requires an argument.
Returned value:
  1. Function returns Result <getopt>.
  2. Result wraps parsing errors and getopt structure.
  3. Parsing can fail only if optstring is invalid.
  4. If required argument is missing function new() won't fail. Call validate() on parsed result for optional argument checking.

2. Check parsed options

getopt structure returned by constructor has following public members:

  1. arguments : Vec <String> command line arguments with options removed
  2. options_map : HashMap <char, bool> map of recognized options. option -> have_argument
  3. options : HashMap <char, String> options parsed. If option do not have argument, it is mapped to "" String, otherwise it is mapped to its argument as String.

Structure getopt supports IntoIterator and can transform itself into Iterator over supplied command line arguments. It supports consuming itself or use self immutable reference for enumerating arguments.

getopt.iter() returns Iterator over pub field arguments without consuming itself.

getopt.len() returns number of command line arguments. It's convience shortcut for getopt.arguments.len().

getopt.get() returns value of command line option. It's convience shortcut for getopt.options.get().

getopt.has() returns if option got supplied on command line. It's convience shortcut for getopt.options.contains_key().

3. Optional - Check if correct options were provided

You can run strict parse checks by calling validate(getopt) function.

This function returns back Result with supplied getopt instance on success or error as String. It can detect if unknown options were encountered or required arguments are missing.

Example

  use std::env::args;
  use getopt2::hideBin;

  let rc = getopt2::new(hideBin(args()), "ab:c");
  if let Ok(g) = rc {
     // command line options parsed sucessfully
     if let Some(arg) = g.options.get(&'b') {
        // handle b argument stored in arg
     };
  };

Reference

  1. POSIX getopt function.
  2. GNU libc getopt function.
  3. OpenBSD getopt
  4. FreeBSD getopt

Known getopt extensions

Fully implemented
  1. GNU getopt parsing rules.
    1. Options can be anywhere in command line before --
    2. double dash -- support. Anything after -- is not treated as options.
  2. POSIX extension in the getopt function where the argument string specification can start with a colon (:). When the option string begins with a colon, it modifies the behavior of getopt to handle error cases differently. Specifically, it suppresses the default error messages that getopt prints when it encounters an unrecognized option or a missing argument, and it returns : instead of ? for these error cases. This allows using ? as option because its possible to spot difference unknown option and -? option.
    1. Extension is implemented in way that '?' as option is always supported. ':' at start of option string is fully optional and have no effect on activating this extension.
Not implemented
  1. Two colons in optstring indicates that the argument is optional. This is an extension not covered by POSIX. This will change only validate function because we do not report errors in getopt2::new if required argument is missing.
  2. In GNU getopt, if the option string (optstring) begins with a + character, it triggers POSIX-compatible parsing. This means that the first non-option argument will stop option parsing, similar to how setting the POSIXLY_CORRECT environment variable behaves.

Possible future developments

Some code for these features exists, but development is paused. Partially implemented code is not compiled during normal build and can't be enabled in stock crate using features.

  1. posix strict mode. First non option stops option parsing. This is needed for parsing nested command lines.
Commit count: 0

cargo fmt