nsomar / Guaka

The smartest and most beautiful (POSIX compliant) Command line framework for Swift 🤖

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to properly fail a command?

Ponyboy47 opened this issue · comments

The documentation says to fail a command like so:

let printCommand = Command(usage: "print",
                           parent: rootCommand) { _, _ in
    // Error happened
    printCommand.fail(statusCode: 1, errorMessage: "Some error happaned")
}

However this code in my application results in a compilation error:

let checkConfig = Command(usage: "check",
                          shortMessage: "Validate your config",
                          parent: config,
                          aliases: ["validate"]
                         ) { flags, args in
    // validateConfig is a ConditionalRun used before most other commands to ensure the config is valid
    if validateConfig(flags: flags, args: args) {
        print("The config is valid")
    } else {
        // Error: variable used within its own initial value
        checkConfig.fail(statusCode: 1, errorMessage: "The config is not valid")
    }
}

I'm using the version 0.2.0 on Swift 4.2

Would it be an option to make the fail function into a global Guaka function as opposed to a local function just for commands?

It seems like a design flaw right now because you cannot call fail if your command's run is a closure because you don't have access to self and you can't reference the command variable since the closure is technically part of the instantiation of the command. It seems that it's a part of Command just because it prints the help text automatically.

When I fail a command though I'd prefer to be explicit about the error message, and I'd really just like to be able to call fail the same regardless of whether or not my run is a function or a closure.

Looks like you implemented this in #91. Can I close this?