Skip to content

Commit 6d32ef3

Browse files
committed
Throw error if attempting to generate a zsh completion script for no commands.
Force unwrap first in ZshCompletionsGenerator.swift. Signed-off-by: Ross Goldberg <[email protected]>
1 parent 19e4df1 commit 6d32ef3

File tree

1 file changed

+28
-19
lines changed

1 file changed

+28
-19
lines changed

Sources/ArgumentParser/Completions/ZshCompletionsGenerator.swift

Lines changed: 28 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -12,26 +12,31 @@
1212
extension [ParsableCommand.Type] {
1313
/// Generates a Zsh completion script for the given command.
1414
var zshCompletionScript: String {
15-
"""
16-
#compdef \(first?._commandName ?? "")
15+
// swift-format-ignore: NeverForceUnwrap
16+
// Preconditions:
17+
// - first must be non-empty for a zsh completion script to be of use.
18+
// - first is guaranteed non-empty in the one place where this computed var is used.
19+
let commandName = first!._commandName
20+
return """
21+
#compdef \(commandName)
1722
18-
\(completeFunctionName)() {
19-
local -ar non_empty_completions=("${@:#(|:*)}")
20-
local -ar empty_completions=("${(M)@:#(|:*)}")
21-
_describe '' non_empty_completions -- empty_completions -P $'\\'\\''
22-
}
23+
\(completeFunctionName)() {
24+
local -ar non_empty_completions=("${@:#(|:*)}")
25+
local -ar empty_completions=("${(M)@:#(|:*)}")
26+
_describe '' non_empty_completions -- empty_completions -P $'\\'\\''
27+
}
2328
24-
\(customCompleteFunctionName)() {
25-
local -a completions
26-
completions=("${(@f)"$("${@}")"}")
27-
if [[ "${#completions[@]}" -gt 1 ]]; then
28-
\(completeFunctionName) "${completions[@]:0:-1}"
29-
fi
30-
}
29+
\(customCompleteFunctionName)() {
30+
local -a completions
31+
completions=("${(@f)"$("${@}")"}")
32+
if [[ "${#completions[@]}" -gt 1 ]]; then
33+
\(completeFunctionName) "${completions[@]:0:-1}"
34+
fi
35+
}
3136
32-
\(completionFunctions)\
33-
\(completionFunctionName())
34-
"""
37+
\(completionFunctions)\
38+
\(completionFunctionName())
39+
"""
3540
}
3641

3742
private var completionFunctions: String {
@@ -203,11 +208,15 @@ extension [ParsableCommand.Type] {
203208
}
204209

205210
private var completeFunctionName: String {
206-
"__\(first?._commandName ?? "")_complete"
211+
// swift-format-ignore: NeverForceUnwrap
212+
// Precondition: first is guaranteed to be non-empty
213+
"__\(first!._commandName)_complete"
207214
}
208215

209216
private var customCompleteFunctionName: String {
210-
"__\(first?._commandName ?? "")_custom_complete"
217+
// swift-format-ignore: NeverForceUnwrap
218+
// Precondition: first is guaranteed to be non-empty
219+
"__\(first!._commandName)_custom_complete"
211220
}
212221
}
213222

0 commit comments

Comments
 (0)