|
| 1 | +//===----------------------------------------------------------*- swift -*-===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift Argument Parser open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2020 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// |
| 10 | +//===----------------------------------------------------------------------===// |
| 11 | + |
| 12 | +struct BashCompletionsGenerator { |
| 13 | + /// Generates a Bash completion script for the given command. |
| 14 | + static func generateCompletionScript(_ type: ParsableCommand.Type) -> String { |
| 15 | + // TODO: Add a check to see if the command is installed where we expect? |
| 16 | + let initialFunctionName = [type].completionFunctionName() |
| 17 | + return """ |
| 18 | + #!/bin/bash |
| 19 | +
|
| 20 | + \(generateCompletionFunction([type])) |
| 21 | +
|
| 22 | + complete -F \(initialFunctionName) \(type._commandName) |
| 23 | + """ |
| 24 | + } |
| 25 | + |
| 26 | + /// Generates a Bash completion function for the last command in the given list. |
| 27 | + fileprivate static func generateCompletionFunction(_ commands: [ParsableCommand.Type]) -> String { |
| 28 | + let type = commands.last! |
| 29 | + let functionName = commands.completionFunctionName() |
| 30 | + |
| 31 | + // The root command gets a different treatment for the parsing index. |
| 32 | + let isRootCommand = commands.count == 1 |
| 33 | + let dollarOne = isRootCommand ? "1" : "$1" |
| 34 | + let subcommandArgument = isRootCommand ? "2" : "$(($1+1))" |
| 35 | + |
| 36 | + // Include 'help' in the list of subcommands for the root command. |
| 37 | + var subcommands = type.configuration.subcommands |
| 38 | + if !subcommands.isEmpty && isRootCommand { |
| 39 | + subcommands.append(HelpCommand.self) |
| 40 | + } |
| 41 | + |
| 42 | + // Generate the words that are available at the "top level" of this |
| 43 | + // command — these are the dash-prefixed names of options and flags as well |
| 44 | + // as all the subcommand names. |
| 45 | + let completionWords = generateArgumentWords(commands) |
| 46 | + + subcommands.map { $0._commandName } |
| 47 | + // FIXME: These shouldn't be hard-coded, since they're overridable |
| 48 | + + ["-h", "--help"] |
| 49 | + |
| 50 | + // Generate additional top-level completions — these are completion lists |
| 51 | + // or custom function-based word lists from positional arguments. |
| 52 | + let additionalCompletions = generateArgumentCompletions(commands) |
| 53 | + |
| 54 | + // Start building the resulting function code. |
| 55 | + var result = "\(functionName)() {\n" |
| 56 | + |
| 57 | + // The function that represents the root command has some additional setup |
| 58 | + // that other command functions don't need. |
| 59 | + if isRootCommand { |
| 60 | + result += """ |
| 61 | + cur="${COMP_WORDS[COMP_CWORD]}" |
| 62 | + prev="${COMP_WORDS[COMP_CWORD-1]}" |
| 63 | + COMPREPLY=() |
| 64 | +
|
| 65 | + """.indentingEachLine(by: 4) |
| 66 | + } |
| 67 | + |
| 68 | + // Start by declaring a local var for the top-level completions. |
| 69 | + // Return immediately if the completion matching hasn't moved further. |
| 70 | + result += " opts=\"\(completionWords.joined(separator: " "))\"\n" |
| 71 | + for line in additionalCompletions { |
| 72 | + result += " opts=\"$opts \(line)\"\n" |
| 73 | + } |
| 74 | + |
| 75 | + result += """ |
| 76 | + if [[ $COMP_CWORD == "\(dollarOne)" ]]; then |
| 77 | + COMPREPLY=( $(compgen -W "$opts" -- "$cur") ) |
| 78 | + return |
| 79 | + fi |
| 80 | +
|
| 81 | + """ |
| 82 | + |
| 83 | + // Generate the case pattern-matching statements for option values. |
| 84 | + // If there aren't any, skip the case block altogether. |
| 85 | + let optionHandlers = generateOptionHandlers(commands) |
| 86 | + if !optionHandlers.isEmpty { |
| 87 | + result += """ |
| 88 | + case $prev in |
| 89 | + \(optionHandlers.indentingEachLine(by: 4)) |
| 90 | + esac |
| 91 | + """.indentingEachLine(by: 4) + "\n" |
| 92 | + } |
| 93 | + |
| 94 | + // Build out completions for the subcommands. |
| 95 | + if !subcommands.isEmpty { |
| 96 | + // Subcommands have their own case statement that delegates out to |
| 97 | + // the subcommand completion functions. |
| 98 | + result += " case ${COMP_WORDS[\(dollarOne)]} in\n" |
| 99 | + for subcommand in subcommands { |
| 100 | + result += """ |
| 101 | + (\(subcommand._commandName)) |
| 102 | + \(functionName)_\(subcommand._commandName) \(subcommandArgument) |
| 103 | + return |
| 104 | + ;; |
| 105 | + |
| 106 | + """ |
| 107 | + .indentingEachLine(by: 8) |
| 108 | + } |
| 109 | + result += " esac\n" |
| 110 | + } |
| 111 | + |
| 112 | + // Finish off the function. |
| 113 | + result += """ |
| 114 | + COMPREPLY=( $(compgen -W "$opts" -- "$cur") ) |
| 115 | + } |
| 116 | +
|
| 117 | + """ |
| 118 | + |
| 119 | + return result + |
| 120 | + subcommands |
| 121 | + .map { generateCompletionFunction(commands + [$0]) } |
| 122 | + .joined() |
| 123 | + } |
| 124 | + |
| 125 | + /// Returns the option and flag names that can be top-level completions. |
| 126 | + fileprivate static func generateArgumentWords(_ commands: [ParsableCommand.Type]) -> [String] { |
| 127 | + ArgumentSet(commands.last!) |
| 128 | + .flatMap { $0.bashCompletionWords() } |
| 129 | + } |
| 130 | + |
| 131 | + /// Returns additional top-level completions from positional arguments. |
| 132 | + /// |
| 133 | + /// These consist of completions that are defined as `.list` or `.custom`. |
| 134 | + fileprivate static func generateArgumentCompletions(_ commands: [ParsableCommand.Type]) -> [String] { |
| 135 | + ArgumentSet(commands.last!) |
| 136 | + .compactMap { arg -> String? in |
| 137 | + guard arg.isPositional else { return nil } |
| 138 | + |
| 139 | + switch arg.completion.kind { |
| 140 | + case .default, .file, .directory: |
| 141 | + return nil |
| 142 | + case .list(let list): |
| 143 | + return list.joined(separator: " ") |
| 144 | + case .shellCommand(let command): |
| 145 | + return "$(\(command))" |
| 146 | + case .custom: |
| 147 | + // Generate a call back into the command to retrieve a completions list |
| 148 | + let commandName = commands.first!._commandName |
| 149 | + let subcommandNames = commands.dropFirst().map { $0._commandName }.joined(separator: " ") |
| 150 | + // TODO: Make this work for @Arguments |
| 151 | + let argumentName = arg.preferredNameForSynopsis?.synopsisString |
| 152 | + ?? arg.help.keys.first?.rawValue ?? "---" |
| 153 | + |
| 154 | + return """ |
| 155 | + $(\(commandName) ---completion \(subcommandNames) -- \(argumentName) "$COMP_WORDS") |
| 156 | + """ |
| 157 | + } |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + /// Returns the case-matching statements for supplying completions after an option or flag. |
| 162 | + fileprivate static func generateOptionHandlers(_ commands: [ParsableCommand.Type]) -> String { |
| 163 | + ArgumentSet(commands.last!) |
| 164 | + .compactMap { arg -> String? in |
| 165 | + let words = arg.bashCompletionWords() |
| 166 | + if words.isEmpty { return nil } |
| 167 | + |
| 168 | + // Flags don't take a value, so we don't provide follow-on completions. |
| 169 | + if arg.isNullary { return nil } |
| 170 | + |
| 171 | + return """ |
| 172 | + \(arg.bashCompletionWords().joined(separator: "|"))) |
| 173 | + \(arg.bashValueCompletion(commands).indentingEachLine(by: 4)) |
| 174 | + return |
| 175 | + ;; |
| 176 | + """ |
| 177 | + } |
| 178 | + .joined(separator: "\n") |
| 179 | + } |
| 180 | +} |
| 181 | + |
| 182 | +extension ArgumentDefinition { |
| 183 | + /// Returns the different completion names for this argument. |
| 184 | + fileprivate func bashCompletionWords() -> [String] { |
| 185 | + names.map { $0.synopsisString } |
| 186 | + } |
| 187 | + |
| 188 | + /// Returns the bash completions that can follow this argument's `--name`. |
| 189 | + fileprivate func bashValueCompletion(_ commands: [ParsableCommand.Type]) -> String { |
| 190 | + switch completion.kind { |
| 191 | + case .default: |
| 192 | + return "" |
| 193 | + |
| 194 | + case .file(_): |
| 195 | + // TODO: Use '_filedir' when available |
| 196 | + // FIXME: Use the extensions array |
| 197 | + return #"COMPREPLY=( $(compgen -f -- "$cur") )"# |
| 198 | + |
| 199 | + case .directory: |
| 200 | + return #"COMPREPLY=( $(compgen -d -- "$cur") )"# |
| 201 | + |
| 202 | + case .list(let list): |
| 203 | + return #"COMPREPLY=( $(compgen -W "\#(list.joined(separator: " "))" -- "$cur") )"# |
| 204 | + |
| 205 | + case .shellCommand(let command): |
| 206 | + return "COMPREPLY=( $(\(command)) )" |
| 207 | + |
| 208 | + case .custom: |
| 209 | + // Generate a call back into the command to retrieve a completions list |
| 210 | + let commandName = commands.first!._commandName |
| 211 | + return #"COMPREPLY=( $(compgen -W "$(\#(commandName) \#(customCompletionCall(commands)) "$COMP_WORDS")" -- "$cur") )"# |
| 212 | + } |
| 213 | + } |
| 214 | +} |
0 commit comments