Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Argument parsing in function #110

Closed
notramo opened this issue Dec 5, 2023 · 4 comments
Closed

Argument parsing in function #110

notramo opened this issue Dec 5, 2023 · 4 comments

Comments

@notramo
Copy link

notramo commented Dec 5, 2023

I want to refactor argument parsing into a separate function. It would parse the arguments, and validate them (min/max for numbers, permissions for file paths, etc.), then return the result of the parse function.

// use it in main()
pub fn main() {
  // ...
  const validatedArgs = parseAndValidateArgs(
    // ...
  );
}

pub fn parseAndValidateArgs() { // what is the return type?
  // ...
  const cliArgs = clap.parse(
    // ...
  );

  // validate here

  // then return
  return cliArgs;
}

How do I specify the return type of the parseAndValidateArgs function in the above snippet? Is there a clean and readable way of doing it?

@Hejsil
Copy link
Owner

Hejsil commented Dec 5, 2023

There is clap.Result. It's the function that generates the return type for clap.parse.

@notramo
Copy link
Author

notramo commented Dec 5, 2023

@Hejsil could you provide an example usage in the above snippet? Simply putting it as clap.Result into the return type definition doesn't work. Do I have to use something like @Type(clap.Result)?

@Hejsil
Copy link
Owner

Hejsil commented Dec 5, 2023

Something along the lines of this:

const params = ...;

pub fn parseAndValidateArgs() !clap.Result(clap.Help, params, clap.parsers.default) {
  const cliArgs = try clap.parse(clap.Help, params, clap.parsers.default);

  // validate here

  // then return
  return cliArgs;
}

@notramo
Copy link
Author

notramo commented Dec 5, 2023

It works, thank you.

@notramo notramo closed this as completed Dec 5, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants