File: ArgumentParserShellCompletion.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (294 lines) | stat: -rw-r--r-- 9,987 bytes parent folder | download
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
/*
 This source file is part of the Swift.org open source project

 Copyright 2016 Apple Inc. and the Swift project authors
 Licensed under Apache License v2.0 with Runtime Library Exception

 See http://swift.org/LICENSE.txt for license information
 See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/

import Foundation
import TSCBasic

fileprivate let removeDefaultRegex = try! NSRegularExpression(pattern: "\\[default: .+?\\]", options: [])

// deprecated 2/2021
@available(*, deprecated, message: "use swift-argument-parser instead")
extension ArgumentParser {

    /// Generates part of a completion script for the given shell.
    ///
    /// These aren't complete scripts, as some setup code is required. See
    /// `Sources/Commands/Completions+bash.swift` and
    /// `Sources/Commands/Completions+zsh.swift` for example usage.
    public func generateCompletionScript(for shell: Shell, on stream: WritableByteStream) {
        guard let commandName = commandName else { abort() }
        let name = "_\(commandName.replacingOccurrences(of: " ", with: "_"))"

        switch shell {
        case .bash:
            // Information about how to include this function in a completion script.
            stream.send("""
                # Generates completions for \(commandName)
                #
                # Parameters
                # - the start position of this parser; set to 1 if unknown

                """)
            generateBashSwiftTool(name: name, on: stream)

        case .zsh:
            // Information about how to include this function in a completion script.
            stream.send("""
                # Generates completions for \(commandName)
                #
                # In the final compdef file, set the following file header:
                #
                #     #compdef \(name)
                #     local context state state_descr line
                #     typeset -A opt_args

                """)

            generateZshSwiftTool(name: name, on: stream)
        }
        stream.flush()
    }

    // MARK: - BASH

    fileprivate func generateBashSwiftTool(name: String, on stream: WritableByteStream) {
        stream.send("""
            function \(name)
            {

            """)

        // Suggest positional arguments. Beware that this forces positional arguments
        // before options. For example [swift package pin <TAB>] expects a name as the
        // first argument. So no options (like --all) will be suggested. However after
        // the positional argument; [swift package pin MyPackage <TAB>] will list them
        // just fine.
        for (index, argument) in positionalArguments.enumerated() {
            stream.send("    if [[ $COMP_CWORD == $(($1+\(index))) ]]; then\n")
            generateBashCompletion(argument, on: stream)
            stream.send("    fi\n")
        }

        // Suggest subparsers in addition to other arguments.
        stream.send("    if [[ $COMP_CWORD == $1 ]]; then\n")
        var completions = [String]()
        for (subName, _) in subparsers {
            completions.append(subName)
        }
        for option in optionArguments {
            completions.append(option.name)
            if let shortName = option.shortName {
                completions.append(shortName)
            }
        }
        stream.send("""
                    COMPREPLY=( $(compgen -W "\(completions.joined(separator: " "))" -- $cur) )
                    return
                fi

            """)

        // Suggest completions based on previous word.
        generateBashCasePrev(on: stream)

        // Forward completions to subparsers.
        stream.send("    case ${COMP_WORDS[$1]} in\n")
        for (subName, _) in subparsers {
            stream.send("""
                        (\(subName))
                            \(name)_\(subName) $(($1+1))
                            return
                        ;;

                """)
        }
        stream.send("    esac\n")

        // In all other cases (no positional / previous / subparser), suggest
        // this parsers completions.
        stream.send("""
                COMPREPLY=( $(compgen -W "\(completions.joined(separator: " "))" -- $cur) )
            }


            """)

        for (subName, subParser) in subparsers {
            subParser.generateBashSwiftTool(name: "\(name)_\(subName)", on: stream)
        }
    }

    fileprivate func generateBashCasePrev(on stream: WritableByteStream) {
        stream.send("    case $prev in\n")
        for argument in optionArguments {
            let flags = [argument.name] + (argument.shortName.map({ [$0] }) ?? [])
            stream.send("        (\(flags.joined(separator: "|")))\n")
            generateBashCompletion(argument, on: stream)
            stream.send("        ;;\n")
        }
        stream.send("    esac\n")
    }

    fileprivate func generateBashCompletion(_ argument: AnyArgument, on stream: WritableByteStream) {
        switch argument.completion {
        case .none:
            // return; no value to complete
            stream.send("            return\n")
        case .unspecified:
            break
        case .values(let values):
            let x = values.map({ $0.value }).joined(separator: " ")
            stream.send("""
                            COMPREPLY=( $(compgen -W "\(x)" -- $cur) )
                            return

                """)
        case .filename:
            stream.send("""
                            _filedir
                            return

                """)
        case .function(let name):
            stream.send("""
                            \(name)
                            return

                """)
        }
    }

    // MARK: - ZSH

    private func generateZshSwiftTool(name: String, on stream: WritableByteStream) {
        // Completions are provided by zsh's _arguments builtin.
        stream.send("""
            \(name)() {
                arguments=(

            """)
        for argument in positionalArguments {
            stream.send("        \"")
            generateZshCompletion(argument, on: stream)
            stream.send("\"\n")
        }
        for argument in optionArguments {
            generateZshArgument(argument, on: stream)
        }

        // Use a simple state-machine when dealing with sub parsers.
        if subparsers.count > 0 {
            stream.send("""
                        '(-): :->command'
                        '(-)*:: :->arg'

                """)
        }

        stream.send("""
                )
                _arguments $arguments && return

            """)

        // Handle the state set by the state machine.
        if subparsers.count > 0 {
            stream.send("""
                    case $state in
                        (command)
                            local modes
                            modes=(

                """)
            for (subName, subParser) in subparsers {
                stream.send("""
                                    '\(subName):\(subParser.overview)'

                    """)
            }
            stream.send("""
                            )
                            _describe "mode" modes
                            ;;
                        (arg)
                            case ${words[1]} in

                """)
            for (subName, _) in subparsers {
                stream.send("""
                                    (\(subName))
                                        \(name)_\(subName)
                                        ;;

                    """)
            }
            stream.send("""
                            esac
                            ;;
                    esac

                """)
        }
       stream.send("}\n\n")

        for (subName, subParser) in subparsers {
            subParser.generateZshSwiftTool(name: "\(name)_\(subName)", on: stream)
        }
    }

    /// Generates an option argument for `_arguments`, complete with description and completion values.
    fileprivate func generateZshArgument(_ argument: AnyArgument, on stream: WritableByteStream) {
        stream.send("        \"")
        switch argument.shortName {
        case .none: stream.send("\(argument.name)")
        case let shortName?: stream.send("(\(argument.name) \(shortName))\"{\(argument.name),\(shortName)}\"")
        }

        let description = removeDefaultRegex
            .replace(in: argument.usage ?? "", with: "")
            .replacingOccurrences(of: "\"", with: "\\\"")
            .replacingOccurrences(of: "[", with: "\\[")
            .replacingOccurrences(of: "]", with: "\\]")
        stream.send("[\(description)]")

        generateZshCompletion(argument, on: stream)
        stream.send("\"\n")
    }

    /// Generates completion values, as part of an item for `_arguments`.
    fileprivate func generateZshCompletion(_ argument: AnyArgument, on stream: WritableByteStream) {
        let message = removeDefaultRegex
            .replace(in: argument.usage ?? " ", with: "")
            .replacingOccurrences(of: "\"", with: "\\\"")

        switch argument.completion {
        case .none: stream.send(":\(message): ")
        case .unspecified: break
        case .filename: stream.send(":\(message):_files")
        case let .values(values):
            stream.send(": :{_values ''")
            for (value, description) in values {
                stream.send(" '\(value)[\(description)]'")
            }
            stream.send("}")
        case .function(let name): stream.send(":\(message):\(name)")
        }
    }
}

fileprivate extension NSRegularExpression {
    func replace(`in` original: String, with replacement: String) -> String {
        return stringByReplacingMatches(
            in: original,
            options: [],
            range: NSRange(location: 0, length: original.count),
            withTemplate: replacement)
    }
}