cli icon indicating copy to clipboard operation
cli copied to clipboard

Flags from structures

Open saschagrunert opened this issue 4 years ago • 6 comments

I’m quite not sure if this is nicely doable with golang, because we have nothing like a procedural macro for it. It could be done with reflection and tags…

Anyways, here comes the idea: I saw in the upcoming release of clap (a command line parser for Rust) that it is capable of deriving the flags from a structure, like this:

#[derive(Clap)]
#[clap(
    after_help = "More info at: https://github.com/saschagrunert/kubernix",
    author = "Sascha Grunert <[email protected]>",
    raw(global_setting = "AppSettings::ColoredHelp"),
    raw(version = "crate_version!()")
)]
/// The global configuration
pub struct Config {
    #[get = "pub"]
    #[clap(subcommand)]
    /// All available subcommands
    subcommand: Option<SubCommand>,

    #[get = "pub"]
    #[clap(
        default_value = "kubernix-run",
        env = "KUBERNIX_RUN",
        global = true,
        long = "root",
        short = "r",
        value_name = "PATH"
    )]
    /// Path where all the runtime data is stored
    root: PathBuf,

    …
}

The amazing thing is now that I’m able to use a single configuration structure and map it directly to command line arguments. So there is no need of an additional structure any more. The documentation comments (starting with ///) are automatically transferred into the help message as well.

I would like to spin up the discussion if we are considering something like this for this library, too. What do you think?

saschagrunert avatar Oct 24 '19 18:10 saschagrunert

These guys are doing what you are talking about @saschagrunert

https://github.com/alecthomas/kong

asahasrabuddhe avatar Jan 25 '20 18:01 asahasrabuddhe

Ah okay we could add something via go tags. I think this might be a nice feature.

saschagrunert avatar Jan 25 '20 18:01 saschagrunert

I've also done struct tags -> cli.App via reflection. Feel free to pull in, I could make a PR for this repo if that's of interest http://github.com/Southclaws/clive

Southclaws avatar Feb 03 '20 09:02 Southclaws

This issue or PR has been automatically marked as stale because it has not had recent activity. Please add a comment bumping this if you're still interested in it's resolution! Thanks for your help, please let us know if you need anything else.

stale[bot] avatar May 03 '20 11:05 stale[bot]

Closing this as it has become stale.

stale[bot] avatar Jun 02 '20 11:06 stale[bot]

This would actually be a very thoughtful addition, has it been considered at all?

refs avatar Apr 29 '21 12:04 refs

The way I see it urfave/cli gives you the basic building blocks. User could use reflection and tags and build the necessary flag slice for commands. I like this feature but I'd rather not have the cli library do it directly

dearchap avatar Oct 17 '22 10:10 dearchap