Note

Turn on dark mode: upper right, little sun-looking thing. Code blocks in this theme look hideous in light mode, and I simply haven’t been able to work up the enthusiasm to learn enough scss to figure out how to fix it. I could change themes, I guess, but that affects the whole site, and… just use the dark theme for now, ok? Thanks.


claptrap opts lib: very small, much features, getoptish

https://sr.ht/~ser/claptrap/

Every few months, when I start a new CLI, I spend a good amount of time looking around for a flags library. For trivial programs, the stdlib flag library is OK, but it breaks getopt arguments style, the undisputed most popular arguments standard for POSIXy OSes, in the world. And there are a wealth of alternative flags libraries available, some quite good, but I am inevitably unsatisfied with them for usually one of three reasons:

  • They’re huge. Lots of code, lots of dependencies. This is especially a problem when you’re trying to validate all of your dependencies for a sensitive program, like something that interacts with credentials.
  • They have an API that feels more like a framework than a library. These are flags libraries you find yourself building your application around. Any flags library that forces you to restructure your program falls in this category.
  • They’re too bare-bones. Having to re-write input type validation code over and over gets tedious. This is where I shy away from most of the getopts clones. getopts is pretty bare bones, but conforming to the usage patterns doesn’t force you to copy the skeletal feature set.

Over time, I’d built up some tooling to evaluate lib tools; I’ve posted that, and the analysis, here, and I focused this time on clapper, which seemed to fit the bill. There were a couple of small features I wanted, and I sent in a couple of patches, but after one particularly engaging hacking session I ended up with a drastic rewrite that maintained and expanded the feature set while preserving the small size and general getopts compatability. At this point, it was a different library, so I rebranded it and Claptrap was born.

Claptrap is a small but powerful Go package to parse command-line arguments
getopt(3) style. Designed to not burden your application down while providing a rich feature set and validation. for making CLI based libraries with ease. It has support for:

  • getopt long & short flags (–bool, -b)
  • combined short (-b -e == -be)
  • inverted bools (–bool => –no-bool)
  • typed params (int, bool, Duration, string, float)
  • mandatory flags and arguments
  • positional arguments
  • global flags
  • subcommands
  • variadic flags (-a 1 -a 2 -a 3)
  • partial command matching (–list == –ls == –st)
  • Usage()

And it’s 455 lines of code, and 0 dependencies.