/
ZshCompletionsGenerator.swift
196 lines (165 loc) · 5.51 KB
/
ZshCompletionsGenerator.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
//===----------------------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Argument Parser open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
struct ZshCompletionsGenerator {
/// Generates a Zsh completion script for the given command.
static func generateCompletionScript(_ type: ParsableCommand.Type) -> String {
let initialFunctionName = [type].completionFunctionName()
return """
#compdef \(type._commandName)
local context state state_descr line
_\(type._commandName.zshEscapingCommandName())_commandname=$words[1]
typeset -A opt_args
\(generateCompletionFunction([type]))
_custom_completion() {
local completions=("${(@f)$($*)}")
_describe '' completions
}
\(initialFunctionName)
"""
}
static func generateCompletionFunction(_ commands: [ParsableCommand.Type]) -> String {
let type = commands.last!
let functionName = commands.completionFunctionName()
let isRootCommand = commands.count == 1
var args = generateCompletionArguments(commands)
var subcommands = type.configuration.subcommands
.filter { $0.configuration.shouldDisplay }
var subcommandHandler = ""
if !subcommands.isEmpty {
args.append("'(-): :->command'")
args.append("'(-)*:: :->arg'")
if isRootCommand {
subcommands.append(HelpCommand.self)
}
let subcommandModes = subcommands.map {
"""
'\($0._commandName):\($0.configuration.abstract.zshEscaped())'
"""
.indentingEachLine(by: 12)
}
let subcommandArgs = subcommands.map {
"""
(\($0._commandName))
\(functionName)_\($0._commandName)
;;
"""
.indentingEachLine(by: 12)
}
subcommandHandler = """
case $state in
(command)
local subcommands
subcommands=(
\(subcommandModes.joined(separator: "\n"))
)
_describe "subcommand" subcommands
;;
(arg)
case ${words[1]} in
\(subcommandArgs.joined(separator: "\n"))
esac
;;
esac
"""
.indentingEachLine(by: 4)
}
let functionText = """
\(functionName)() {
integer ret=1
local -a args
args+=(
\(args.joined(separator: "\n").indentingEachLine(by: 8))
)
_arguments -w -s -S $args[@] && ret=0
\(subcommandHandler)
return ret
}
"""
return functionText +
subcommands
.map { generateCompletionFunction(commands + [$0]) }
.joined()
}
static func generateCompletionArguments(_ commands: [ParsableCommand.Type]) -> [String] {
commands
.argumentsForHelp(visibility: .default)
.compactMap { $0.zshCompletionString(commands) }
}
}
extension String {
fileprivate func zshEscapingSingleQuotes() -> String {
self.replacingOccurrences(of: "'", with: #"'"'"'"#)
}
fileprivate func zshEscapingMetacharacters() -> String {
self.replacingOccurrences(of: #"[\\\[\]]"#, with: #"\\$0"#, options: .regularExpression)
}
fileprivate func zshEscaped() -> String {
self.zshEscapingSingleQuotes().zshEscapingMetacharacters()
}
fileprivate func zshEscapingCommandName() -> String {
self.replacingOccurrences(of: "-", with: "_")
}
}
extension ArgumentDefinition {
var zshCompletionAbstract: String {
guard !help.abstract.isEmpty else { return "" }
return "[\(help.abstract.zshEscaped())]"
}
func zshCompletionString(_ commands: [ParsableCommand.Type]) -> String? {
guard help.visibility.base == .default else { return nil }
var inputs: String
switch update {
case .unary:
inputs = ":\(valueName):\(zshActionString(commands))"
case .nullary:
inputs = ""
}
let line: String
switch names.count {
case 0:
line = ""
case 1:
line = """
\(names[0].synopsisString)\(zshCompletionAbstract)
"""
default:
let synopses = names.map { $0.synopsisString }
line = """
(\(synopses.joined(separator: " ")))'\
{\(synopses.joined(separator: ","))}\
'\(zshCompletionAbstract)
"""
}
return "'\(line)\(inputs)'"
}
/// Returns the zsh "action" for an argument completion string.
func zshActionString(_ commands: [ParsableCommand.Type]) -> String {
switch completion.kind {
case .default:
return ""
case .file(let extensions):
let pattern = extensions.isEmpty
? ""
: " -g '\(extensions.map { "*." + $0 }.joined(separator: " "))'"
return "_files\(pattern.zshEscaped())"
case .directory:
return "_files -/"
case .list(let list):
return "(" + list.joined(separator: " ") + ")"
case .shellCommand(let command):
return "{local -a list; list=(${(f)\"$(\(command))\"}); _describe '''' list}"
case .custom:
// Generate a call back into the command to retrieve a completions list
let commandName = commands.first!._commandName.zshEscapingCommandName()
return "{_custom_completion $_\(commandName)_commandname \(customCompletionCall(commands)) $words}"
}
}
}