clap-rs / clap

A full featured, fast Command Line Argument Parser for Rust
docs.rs/clap
Apache License 2.0
14.31k stars 1.04k forks source link

Generate `.env` string form Command #4729

Open joepio opened 1 year ago

joepio commented 1 year ago

Please complete the following tasks

Clap Version

4

Describe your use case

Clap gives the options to either use flags or environment variables to configure their instance.

Generating a .env file can help users to setup more complex configurations. We can use the env = "MY_ENV marco setting to find out for which arguments we should generate such as file.

Describe the solution you'd like

            use clap::CommandFactory;
            let command = Opts::command();

            let mut out = String::from("# Generated by `atomic-server setup-env` \n");
            for arg in command.get_arguments() {
                if let Some(env) = arg.get_env() {
                    let Some(hint) = arg.get_help() else {
                        continue;
                    };
                    out.push_str(&format!("# {}\n", hint));
                    let possible_vals = arg.get_possible_values();
                    if !possible_vals.is_empty() {
                        out.push_str(&format!(
                            "# Possible values: {:?}\n",
                            possible_vals
                                .iter()
                                .map(|v| v.get_name())
                                .collect::<Vec<&str>>()
                        ));
                    }
                    out.push_str(&format!(
                        "# {}=\n\n",
                        env.to_str().expect("Can't convert env to string"),
                    ));
                }
            }

This works for me, but it could be improved. The enums don't show their descriptions at the moment, and there is no hint about data type / boolean type.

I think this feature could be available from clap::Command::generate_dotenv, which could return a string.

Alternatives, if applicable

No response

Additional Context

No response

epage commented 1 year ago

I think something like this could be useful. I think it should at least start as a separate crate like man and completions, maybe clap_dotenv. I'm ambivalent on whether that is within the clap repo or not.

dzmitry-lahoda commented 3 months ago

seems somewhat relevant https://github.com/clap-rs/clap/issues/3131 , so it ask to generate cli args. but in general idea of serialization is common.