From b6bdb013a747f15c9188625d045c28c2cbf7a5ff Mon Sep 17 00:00:00 2001 From: AJ Date: Wed, 30 Oct 2019 17:52:49 -0700 Subject: [PATCH] Print shell completion with an exeption rather than calling echo directly --- CHANGELOG.md | 2 ++ .../com/github/ajalt/clikt/core/CliktCommand.kt | 7 +++++-- .../kotlin/com/github/ajalt/clikt/core/exceptions.kt | 12 +++++++++++- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 454f91687..15ef6ea92 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/clikt/src/main/kotlin/com/github/ajalt/clikt/core/CliktCommand.kt b/clikt/src/main/kotlin/com/github/ajalt/clikt/core/CliktCommand.kt index 50dfdb084..69eccaf65 100644 --- a/clikt/src/main/kotlin/com/github/ajalt/clikt/core/CliktCommand.kt +++ b/clikt/src/main/kotlin/com/github/ajalt/clikt/core/CliktCommand.kt @@ -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) } /** @@ -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) diff --git a/clikt/src/main/kotlin/com/github/ajalt/clikt/core/exceptions.kt b/clikt/src/main/kotlin/com/github/ajalt/clikt/core/exceptions.kt index dc3db67a8..e78cd95c6 100644 --- a/clikt/src/main/kotlin/com/github/ajalt/clikt/core/exceptions.kt +++ b/clikt/src/main/kotlin/com/github/ajalt/clikt/core/exceptions.kt @@ -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.