Skip to content

mo_cli: an argument parser to create command line interfaces

Sebastian Müller requested to merge add_mo_cli into develop

This module provides a class cli_parser to create a command line argument parser for a fortran executable. One can define options with a name (--name) and a short name (-n) and set them to have a value or not (-n ). Also default values can be passed and options can be set to "required". A single "blank" option can bedefined, that is not indicated by a hyphenated switch.

See the following example:

program main
  use mo_cli, only: cli_parser
  implicit none
  type(cli_parser) :: parser

  parser = cli_parser( &
    description="This program has a CLI.", &
    add_version_option=.true., &
    version="1.3")

  call parser%add_option( &
    name="cwd", &
    blank=.true., &
    help="The working directory.")

  call parser%add_option( &
    name="file", &
    s_name="f", &
    has_value=.true., &
    value_name="path", &
    default="nope", &
    help="Your file path.")

  call parser%add_option( &
    name="file2", &
    has_value=.true., &
    value_name="path", &
    required=.true., &
    help="Your 2nd file path.")

  call parser%add_option("opt", help="A switch")

  call parser%parse()

  print*, "file: ", parser%option_value("file")
  print*, "dir: ", parser%option_value("cwd")
  print*, "opt: ", parser%option_was_read("opt")

end program main

This can be called like:

$ ./prog --file2 f2 -f f1 --opt a/path
 file: f1
 dir: a/path
 opt:  T

Or to display the auto generated help:

$ ./prog -h
This program has a CLI.

  Usage: PROJ [options] <cwd>

Options:
  <cwd>
      Description: The working directory.

  --file2 <path>
      Description: Your 2nd file path.
      (required)

  --help / -h
      Description: Print this help message.

  --version / -v
      Description: Print the version of the program.

  --file / -f <path>
      Description: Your file path.
      Default: nope

  --opt
      Description: A switch

Merge request reports