Skip to content

Commit

Permalink
Print shell completion with an exeption rather than calling echo dire…
Browse files Browse the repository at this point in the history
…ctly
  • Loading branch information
ajalt committed Oct 31, 2019
1 parent 425b282 commit b6bdb01
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# Changelog

## [Unreleased]
### Changed
- Shell completion code is now printed by throwing a `PrintCompletionMessage` (a subclass of `PrintMessage`) rather than calling `echo` directly.

## [2.2.0] - 2019-09-25
### Added
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,7 @@ abstract class CliktCommand(
}
val envval = System.getenv(envvar) ?: return
val completion = CompletionGenerator.generateCompletion(command = this, zsh = "zsh" in envval)
echo(completion, lineSeparator = "\n")
exitProcess(1)
throw PrintCompletionMessage(completion, forceUnixLineEndings = true)
}

/**
Expand Down Expand Up @@ -232,6 +231,10 @@ abstract class CliktCommand(
} catch (e: PrintHelpMessage) {
echo(e.command.getFormattedHelp())
exitProcess(0)
} catch (e: PrintCompletionMessage) {
val s = if (e.forceUnixLineEndings) "\n" else context.console.lineSeparator
echo(e.message, lineSeparator = s)
exitProcess(0)
} catch (e: PrintMessage) {
echo(e.message)
exitProcess(0)
Expand Down
12 changes: 11 additions & 1 deletion clikt/src/main/kotlin/com/github/ajalt/clikt/core/exceptions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,17 @@ class PrintHelpMessage(val command: CliktCommand) : CliktError()
*
* Execution should be immediately halted without an error.
*/
class PrintMessage(message: String) : CliktError(message)
open class PrintMessage(message: String) : CliktError(message)

/**
* An exception that indicates that shell completion code should be printed.
*
* Execution should be immediately halted without an error.
*
* @param forceUnixLineEndings if true, all line endings in the message should be `\n`, regardless
* of the current operating system.
*/
class PrintCompletionMessage(message: String, val forceUnixLineEndings: Boolean): PrintMessage(message)

/**
* An internal exception that signals a usage error.
Expand Down

0 comments on commit b6bdb01

Please sign in to comment.