Skip to content

Commit b6bdb01

Browse files
committed
Print shell completion with an exeption rather than calling echo directly
1 parent 425b282 commit b6bdb01

File tree

3 files changed

+18
-3
lines changed

3 files changed

+18
-3
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
# Changelog
22

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

57
## [2.2.0] - 2019-09-25
68
### Added

clikt/src/main/kotlin/com/github/ajalt/clikt/core/CliktCommand.kt

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,7 @@ abstract class CliktCommand(
9393
}
9494
val envval = System.getenv(envvar) ?: return
9595
val completion = CompletionGenerator.generateCompletion(command = this, zsh = "zsh" in envval)
96-
echo(completion, lineSeparator = "\n")
97-
exitProcess(1)
96+
throw PrintCompletionMessage(completion, forceUnixLineEndings = true)
9897
}
9998

10099
/**
@@ -232,6 +231,10 @@ abstract class CliktCommand(
232231
} catch (e: PrintHelpMessage) {
233232
echo(e.command.getFormattedHelp())
234233
exitProcess(0)
234+
} catch (e: PrintCompletionMessage) {
235+
val s = if (e.forceUnixLineEndings) "\n" else context.console.lineSeparator
236+
echo(e.message, lineSeparator = s)
237+
exitProcess(0)
235238
} catch (e: PrintMessage) {
236239
echo(e.message)
237240
exitProcess(0)

clikt/src/main/kotlin/com/github/ajalt/clikt/core/exceptions.kt

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,17 @@ class PrintHelpMessage(val command: CliktCommand) : CliktError()
3030
*
3131
* Execution should be immediately halted without an error.
3232
*/
33-
class PrintMessage(message: String) : CliktError(message)
33+
open class PrintMessage(message: String) : CliktError(message)
34+
35+
/**
36+
* An exception that indicates that shell completion code should be printed.
37+
*
38+
* Execution should be immediately halted without an error.
39+
*
40+
* @param forceUnixLineEndings if true, all line endings in the message should be `\n`, regardless
41+
* of the current operating system.
42+
*/
43+
class PrintCompletionMessage(message: String, val forceUnixLineEndings: Boolean): PrintMessage(message)
3444

3545
/**
3646
* An internal exception that signals a usage error.

0 commit comments

Comments
 (0)