jatoben/CommandLine

Either / or

niklassaers opened this issue · 3 comments

Hi,
thanks for the project! :-)

I would like three cases of flow through my command line app:

--version => output version and end
--help => output help info and end
all others -> normal flow

I've got the all others flow under control based on your examples. :-)

The --help kind of works, since failing will output the help ;-)

The --version I don't know how I should implement

Any suggestions for how I can add different set of valid requirement combinations?

Cheers

Nik

Hi @niklassaers!

Heres one way of doing it:

import CommandLine

let cli = CommandLine()

let help = BoolOption(shortFlag: "h", longFlag: "help",
                    helpMessage: "Prints a help message.")
let version = BoolOption(shortFlag: “v”, longFlag: “version”,
                    helpMessage: "Prints version.")

cli.addOptions(help, version)

do {
  try cli.parse()
} catch {
  cli.printUsage(error)
  exit(EX_USAGE)
}

// Give precedence to help flag
if help.value {
    cli.printUsage()
    exit(EX_OK)
} else if version.value {
    print("<APP_VERSION>")
    exit(EX_OK)
}

// Normal flow - rest of app logic

So this would work in the following manner:

example        # No options - normal flow
example -h     # Prints help and exits
example -v     # Prints version and exits
example -vh    # Prints help and exits since we gave it precedence

Hope that helps! For more detail, here are two examples of tools using CommandLine [1], [2].

Cool, thank you very much for the code example. :-)

np! :)