spring-projects / spring-shell

Spring based shell
http://projects.spring.io/spring-shell/
Apache License 2.0
724 stars 394 forks source link

How to code a very simple case #1114

Closed fgrazi closed 1 month ago

fgrazi commented 1 month ago

I'm trying to use the Shell, but I'm confused by the documentation and how to specify command arguments and options. Here is a really simple example.

I need a "generate-key" command that receives:

@ShellMethod(key = "create-key",
      value = "Create a new pair of private and public keys"
  )
  public String createKey(
      @Option(required = true, arity = CommandRegistration.OptionArity.EXACTLY_ONE) String id,
      @Option(longNames = "--pass", required = false) String passphrase,
      @Option(longNames = "--duration", required = false) String duration

  ) {
    return MessageFormat.format("id: {0}, passphrase: {1}, duration: {2}", id, passphrase, duration);
  }

As you can see, the code does nothing, simply echoes the argument and parameters. So you can quickly reproduce the case.

Maybe am I doing something wrong? Please let me know. Let's see some cases:

First attempt: command only:

shell:>create-key
Missing mandatory option '--id'
Missing mandatory option '--passphrase'
Missing mandatory option '--duration'

This is wrong:

  1. Only the id argument is missing, but the message says that also the options are missing.
  2. The positional parameter shall not be preceded by --id, as shown.
  3. The passphrase is preceded by "--pass" and not "--passphrase". "passphrase" is the name of the variable that the user shall not know.

So I make a second test supplying only the positional argument:

shell:>create-key zorro
id: zorro, passphrase: null, duration: null

Perfect! worked as expected. Now let's try an option:

shell:>create-key zorro --pass  garcia
id: zorro, passphrase: --pass, duration: garcia

Wrong! I would expect:

id: zorro, passphrase: garcia, duration: null

Now let's try all options:

shell:>create-key zorro --pass garcia --duration 120
id: zorro, passphrase: --pass, duration: 120

Wrong again: the passphrase is "garcia", not "--pass".

And finally, if I precede the options (as usual in Unix):

shell:>create-key --pass garcia --duration 120 zorro
Unrecognised option '--pass'

I get the unrecognized option "--pass".

I can't find a simple guide that explains how to code for this specific case, so I must be doing something wrong.

Can you kindly explain how options and arguments are recognized and parsed?

Thanks indeed.