clappen
Flatten prefix for
clap
About
Integrate flatten prefix in your clap parsers easily.
For more details, see:
Basic usage
use Parser;
// export is the name of the macro generated
// this mod definition does not appear in the
// final generated code, it's just a convenient
// wrapper for item definitions
// export is the name of the macro generated
// mod definition not used too
// generate the default struct without prefix
prefixed_struct_generator!;
Motivation
clap unfortunately doesn't preserve field structure and prefix when flattening commands.
See this issue for more in-depth explanation.
This crate allows fixing that while not requiring custom wrapper to the end clap parser used. It's just a struct macro generator that uses clap default behaviour around arg attribute.
See clap documentation for arg.
Limitations
-
Providing custom
longorenvto your fields is not supported. See Roadmap. -
References to fields with more than 1 nesting level won't work - like
self.my_field_level1.my_field_level2.
Generally this should not be needed because you want to get something out of your reusable struct parser (and Rust might get in your way for borrow-related things).
If you still want to do that, you can write custom getter functions, and the renamed fields will be picked in theimplblocks. -
Probably some edge cases are not covered. For example,
clapsubcommands should be working, but it was not tested extensively as my use case is mainly reusingstructs in a mono repository fashion.
Roadmap
- Maybe add support for
long/envprefix injection.
This would make the integration withclaptighter and the code more complicated though.
FAQ
Why is clappen_command required with command(flatten) even without prefix ?
Because people work with copy/paste.
For example, if this was not required, you might write this
But then if you copy paste this and turn it to a reusable parser, you get this
Making clappen_command required for all flatten items avoids having to think about that when refactoring, you know that your prefix will be maintained even when using a single struct without a prefix.
Related stuff
- Project https://github.com/wfraser/clap_wrapper - implements prefix as well, but you can't reuse the struct with another prefix.
- Issue https://github.com/clap-rs/clap/issues/3513#issuecomment-1344372578 for the original idea.
Special thanks
- Big up to @dtolnay and its wonderful work in
syn,quoteandpaste.
The initial implementation usedpastebut it is sadly now unmaintained. - Kudos to @epage for tireless maintaining
clapand all its great features.