Skip to content

structopt as main args through rust-cli/paw #187

@yoshuawuyts

Description

@yoshuawuyts

A few weeks ago the CLI WG released paw, a crate to try and make CLI parsing more of a first-class citizen in Rust (post). This allows arguments to be passed into fn main as long as a trait is implemented. Obviously we also added structopt support.

So far it's been working quite well, but we think we could make this even better if we could add the trait to structopt directly:

Proposed

#[derive(structopt::StructOpt)]
struct Args {}

#[paw::main]
fn main(args: Args) {
    println!("{}", args);
}

Current

#[derive(paw_structopt::StructOpt, structopt::StructOpt)]
struct Args {}

#[paw::main]
fn main(args: Args) {
    println!("{}", args);
}

Implementation

The patch to structopt would be about 6 lines inside the structopt macro:

impl paw::ParseArgs for #name {
    type Error = std::io::Error;
    fn parse_args() -> Result<Self, Self::Error> {
        Ok(<#name as structopt::StructOpt>::from_args())
    }
}

Would you be open to a patch that allows structopt to be used directly from main?


Full TCP Example

#[derive(structopt::StructOpt)]
struct Args {
    #[structopt(flatten)]
    port: clap_port_flag::Address,
    #[structopt(flatten)]
    port: clap_port_flag::Port,
}

#[paw::main]
fn main(args: Args) -> Result<(), std::io::Error> {
    let listener = TcpListener::bind((&*args.address, args.port))?;
    println!("listening on {}", listener.local_addr()?);
    for stream in listener.incoming() {
        stream?.write(b"hello world!")?;
    }
    Ok(())
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementWe would love to have this feature! Feel free to supply a PR

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions