getopt-like flags package for golang,

goopt

A getopt-like processor of command-line flags. It works much like the "flag" package, only it processes arguments in a way that is compatible with the getopt_long syntax, which is an extension of the syntax recommended by POSIX.

Example program

The example program named example/example.go, is meant to be more useful for someone trying to see how the package works. It comes with a makefile demonstrating how to do some nice tricks, such as enabling bash completion on your flags, and generating man pages and html versions of the man page (see the man page for the example program).

Test suite

The test suite is the file .test, which compiles and verifies the output of the program in the test-program directory, as well as the example program. You can configure git to run the test suite automatically by running the setup-git.sh script.

Documentation

Once the package is installed via goinstall, use the following to view the documentation:

godoc --http=:6060

If you installed it from github, you will want to do this from the source directory:

godoc --http=:6060 --path=.

This will run in the foreground, so do it in a terminal without anything important in it. Then you can go to http://localhost:6060/ and navigate via the package directory to the documentation or the left-hand navigation, depending on if it was goinstalled or run from a git clone.

Comments
  • Remove -v as a synonym for --version.

    Remove -v as a synonym for --version.

    Note that -v is commonly used for --verbose, and should not be grabbed by the goopt library, especially this late in its release cycle.

    (I'm sure mine wasn't the only program broken by this change.)

  • Improvements

    Improvements

    First of all thank you for this package. I found it very useful for CLI applications. I dare to suggest some small improvements for it:

    • some typo fixes

    • change error message for alternatives from:

    Error in flag --color: invalid flag: cyan
    

    to:

    Error in flag --color: invalid value: cyan
    

    because boolean values are mostly called flags

    • ExtraUsage where we can add additional information about non-option args for example:
    Usage of example:
            example [options] <subcommand> [options]
    Options:
      -v       --verbose                                   output verbosely
               --quiet                                     be quiet, instead
               --color, --colour=[default|red|green|blue]  determine the color of the output
      -n 1     --repeat=1                                  number of repetitions
      -u User  --user=User                                 name of user
               --child=name of child                       specify child of user
      -h       --help                                      Show usage message
    Subcommands:
      foo      make some action
      bar      make some other action
    
    • add version option
      -v       --version                                   Show version
    

    it just prints Version value

  • getopt_long accepts

    getopt_long accepts "-" as an argument value. This change makes goopt…

    … behave the same way.

    Evidence:

    #include <stdio.h>
    #include <stdlib.h>
    #include <getopt.h>
    
    int
    main (int argc, char **argv)
    {
      int c;
    
      while (1)
        {
          static struct option long_options[] =
            {
              {"file",    required_argument, 0, 'f'},
              {0, 0, 0, 0}
            };
          /* getopt_long stores the option index here. */
          int option_index = 0;
    
          c = getopt_long (argc, argv, "f:",
                           long_options, &option_index);
    
          /* Detect the end of the options. */
          if (c == -1)
            break;
    
          switch (c)
            {
            case 0:
              printf ("option %s", long_options[option_index].name);
              if (optarg)
                printf (" with arg %s", optarg);
              printf ("\n");
              break;
    
            case 'f':
              printf ("option -f with value `%s'\n", optarg);
              break;
    
            case '?':
              /* getopt_long already printed an error message. */
              break;
    
            default:
              abort ();
            }
        }
    
      /* Print any remaining command line arguments (not options). */
      if (optind < argc)
        {
          printf ("non-option ARGV-elements: ");
          while (optind < argc)
            printf ("%s ", argv[optind++]);
          putchar ('\n');
        }
    
      exit (0);
    }
    
    10009» cc -o main ./main.c
    10010» ./main -f -
    option -f with value `-'
    

    goopt behaves differently:

    package main
    
    import "github.com/droundy/goopt"
    import "fmt"
    
    func main() {
    	file := goopt.String([]string{"--file", "-f"}, "", "file name")
    	goopt.Parse(nil)
    	fmt.Printf("option -f with value `%s'\n", file)
    }
    
    10012» go run ./main.go -f -
    Flag -f requires argument!
    exit status 1
    

    This patch allows goopt to behave like getopt_long:

    10006(master)⚡ » go run ./test/main.go -f -
    option -f with value `-'
    
  • No duplicate Label for short and long options for Help()

    No duplicate Label for short and long options for Help()

    It seemed waste of screen realestate to print something like -r RS_REGEX --rs=RS_REGEX so here's my suggestion to make it -r, --rs=RS_REGEX

    How it looks:

    Options:
      -c           --count        Print number of matches. (same as grep -c)
      -v           --invert       Select non-matching records (same as grep -v).
      -a           --and          Extract records with all of patterns. (default: any)
                   --color, --hl  Highlight matches. Default is enabled iff stdout is a TTY.
      -r RS_REGEX  --rs=RS_REGEX  Input record separator. default: /^$|^(=====*|-----*)$/
      -h           --help         Show usage message
    

    to

    Options:
      -c, --count        Print number of matches. (same as grep -c)
      -v, --invert       Select non-matching records (same as grep -v).
      -a, --and          Extract records with all of patterns. (default: any)
      --color, --hl      Highlight matches. Default is enabled iff stdout is a TTY.
      -r, --rs=RS_REGEX  Input record separator. default: /^$|^(=====*|-----*)$/
      -h, --help         Show usage message
    

    It's more friendly for narrow terminals, and more GNU style (e.g. ls --help or co --help), but not exactly, because I removed indent for long-version-only options.

    Also fixed Makefiles (use of $(GOROOT)/src/Make.inc seems obsolete now) and .test script, only to the extent I can run the test cases.

  • RequireOrder

    RequireOrder

    I've added a RequireOrder option that mimics the "require_order" configuration flag for Getopt::Long in Perl (http://perldoc.perl.org/Getopt/Long.html#require_order), which makes the module able to be more "POSIXLY_CORRECT", and opens up the possibility of doing partial processing (ala git itself having global git flags and then more local subcommand flags later on).

    I think a very nice compliment to this option would be a way to specify an arbitrary slice to parse in place of os.Args so that this really could be run multiple times for subcommands and the like, although then we run into scoping issues of not wanting previously defined flags to be processed on the second run (which is why a commit for that change isn't included here also). A solution I would propose for that (and would love some dialog about) would be a "GoOpt" struct/object that contains all the options parsing but includes a backwards-compatible interface that just uses a shared object. If you like the idea, I'd really enjoy implementing such a thing and sending another pull request when it is complete.

Fully featured Go (golang) command line option parser with built-in auto-completion support.

go-getoptions Go option parser inspired on the flexibility of Perl’s GetOpt::Long. Table of Contents Quick overview Examples Simple script Program wit

Dec 14, 2022
Idiomatic Go input parsing with subcommands, positional values, and flags at any position. No required project or package layout and no external dependencies.
Idiomatic Go input parsing with subcommands, positional values, and flags at any position. No required project or package layout and no external dependencies.

Sensible and fast command-line flag parsing with excellent support for subcommands and positional values. Flags can be at any position. Flaggy has no

Jan 1, 2023
Drop-in replacement for Go's flag package, implementing POSIX/GNU-style --flags.

Description pflag is a drop-in replacement for Go's flag package, implementing POSIX/GNU-style --flags. pflag is compatible with the GNU extensions to

Dec 30, 2022
Drop-in replacement for Go's flag package, implementing POSIX/GNU-style --flags.

Description pflag is a drop-in replacement for Go's flag package, implementing POSIX/GNU-style --flags. pflag is compatible with the GNU extensions to

Nov 25, 2022
Flags-first package for configuration

ff stands for flags-first, and provides an opinionated way to populate a flag.FlagSet with configuration data from the environment.

Dec 26, 2022
A rich tool for parsing flags and values in pure Golang

A rich tool for parsing flags and values in pure Golang. No additional library is required and you can use everywhere.

Jan 25, 2022
Golang flags parser with zero dependency

flags Golang flags parser with zero dependency. Usage See simple.go for basic usage. Concept flags gives a simple way to get flag's value from argumen

Jan 16, 2022
Automatically sets up command line flags based on struct fields and tags.
Automatically sets up command line flags based on struct fields and tags.

Commandeer Commandeer sets up command line flags based on struct fields and tags. Do you... like to develop Go apps as libraries with tiny main packag

Dec 1, 2022
Generate flags by parsing structures

Flags based on structures. The sflags package uses structs, reflection and struct field tags to allow you specify command line options. It supports di

Nov 24, 2022
Library for setting values to structs' fields from env, flags, files or default tag

Configuration is a library for injecting values recursively into structs - a convenient way of setting up a configuration object. Available features:

Dec 7, 2022
persistent storage for flags in go

ingo is a simple Go library helping you to persist flags in a ini-like config file. Features and limitations Requires Go 1.5 or later automatically cr

Sep 26, 2022
A kubectl plugin for finding decoded secret data with productive search flags.

kubectl-secret-data What is it? This is a kubectl plugin for finding decoded secret data. Since kubectl only outputs base64-encoded secrets, it makes

Dec 2, 2022
A kubectl plugin for finding decoded secret data with productive search flags.

kubectl-secret-data What is it? This is a kubectl plugin for finding decoded secret data. Since kubectl outputs base64-encoded secrets basically, it m

Dec 2, 2022
Expressive flags for Go

Expressive flags for Go Package xflags provides an alternative to Go's flag package for defining and parsing command line arguments with an emphasis o

Dec 8, 2022
Go socket with SO_REUSEPORT and SO_REUSEADDR flags
Go socket with SO_REUSEPORT and SO_REUSEADDR flags

This library helps go developers to open sockets with SO_REUSEPORT and SO_REUSEADDR flags. Why ? This flags will allow many processes to bind to the s

Dec 29, 2022
Generate markdown from go-flags

goflags-markdown -- generate markdown from a go-flags parser TODO Commands/sub-commands/etc Custom formatting Usage package main import ( "os" fla

May 22, 2022
Prompts users to enter values for required flags in Cobra CLI applications

Cobra Flag Prompt Cobra Flag Prompt prompts users to enter values for required flags. It is an extension of Cobra, and requires that you use Cobra to

Nov 13, 2021
A go1.18 wrapper to provide simple generics based API for defining command line flags.

gflag A go1.18 wrapper to provide simple generics based API for defining command line flags. Example package main import ( "flag" "fmt" "time" "

Dec 20, 2021
Go-flags wireframing demo

go-flags-demo redo - global option redo Redo global option via automatic code-gen TOC go-flags-demo - global option redo Synopsis Usage Development Hi

Jan 22, 2022