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
|
//===----------------------------------------------------------*- 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 BashCompletionsGenerator {
/// Generates a Bash completion script for the given command.
static func generateCompletionScript(_ type: ParsableCommand.Type) -> String {
// TODO: Add a check to see if the command is installed where we expect?
let initialFunctionName = [type].completionFunctionName()
return """
#!/bin/bash
\(generateCompletionFunction([type]))
complete -F \(initialFunctionName) \(type._commandName)
"""
}
/// Generates a Bash completion function for the last command in the given list.
fileprivate static func generateCompletionFunction(_ commands: [ParsableCommand.Type]) -> String {
let type = commands.last!
let functionName = commands.completionFunctionName()
// The root command gets a different treatment for the parsing index.
let isRootCommand = commands.count == 1
let dollarOne = isRootCommand ? "1" : "$1"
let subcommandArgument = isRootCommand ? "2" : "$(($1+1))"
// Include 'help' in the list of subcommands for the root command.
var subcommands = type.configuration.subcommands
.filter { $0.configuration.shouldDisplay }
if !subcommands.isEmpty && isRootCommand {
subcommands.append(HelpCommand.self)
}
// Generate the words that are available at the "top level" of this
// command — these are the dash-prefixed names of options and flags as well
// as all the subcommand names.
let completionWords = generateArgumentWords(commands)
+ subcommands.map { $0._commandName }
// Generate additional top-level completions — these are completion lists
// or custom function-based word lists from positional arguments.
let additionalCompletions = generateArgumentCompletions(commands)
// Start building the resulting function code.
var result = "\(functionName)() {\n"
// The function that represents the root command has some additional setup
// that other command functions don't need.
if isRootCommand {
result += """
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
COMPREPLY=()
""".indentingEachLine(by: 4)
}
// Start by declaring a local var for the top-level completions.
// Return immediately if the completion matching hasn't moved further.
result += " opts=\"\(completionWords.joined(separator: " "))\"\n"
for line in additionalCompletions {
result += " opts=\"$opts \(line)\"\n"
}
result += """
if [[ $COMP_CWORD == "\(dollarOne)" ]]; then
COMPREPLY=( $(compgen -W "$opts" -- "$cur") )
return
fi
"""
// Generate the case pattern-matching statements for option values.
// If there aren't any, skip the case block altogether.
let optionHandlers = generateOptionHandlers(commands)
if !optionHandlers.isEmpty {
result += """
case $prev in
\(optionHandlers.indentingEachLine(by: 4))
esac
""".indentingEachLine(by: 4) + "\n"
}
// Build out completions for the subcommands.
if !subcommands.isEmpty {
// Subcommands have their own case statement that delegates out to
// the subcommand completion functions.
result += " case ${COMP_WORDS[\(dollarOne)]} in\n"
for subcommand in subcommands {
result += """
(\(subcommand._commandName))
\(functionName)_\(subcommand._commandName) \(subcommandArgument)
return
;;
"""
.indentingEachLine(by: 8)
}
result += " esac\n"
}
// Finish off the function.
result += """
COMPREPLY=( $(compgen -W "$opts" -- "$cur") )
}
"""
return result +
subcommands
.map { generateCompletionFunction(commands + [$0]) }
.joined()
}
/// Returns the option and flag names that can be top-level completions.
fileprivate static func generateArgumentWords(_ commands: [ParsableCommand.Type]) -> [String] {
commands
.argumentsForHelp(visibility: .default)
.flatMap { $0.bashCompletionWords() }
}
/// Returns additional top-level completions from positional arguments.
///
/// These consist of completions that are defined as `.list` or `.custom`.
fileprivate static func generateArgumentCompletions(_ commands: [ParsableCommand.Type]) -> [String] {
ArgumentSet(commands.last!, visibility: .default, parent: nil)
.compactMap { arg -> String? in
guard arg.isPositional else { return nil }
switch arg.completion.kind {
case .default, .file, .directory:
return nil
case .list(let list):
return list.joined(separator: " ")
case .shellCommand(let command):
return "$(\(command))"
case .custom:
// Generate a call back into the command to retrieve a completions list
let subcommandNames = commands.dropFirst().map { $0._commandName }.joined(separator: " ")
// TODO: Make this work for @Arguments
let argumentName = arg.names.preferredName?.synopsisString
?? arg.help.keys.first?.name ?? "---"
return """
$("${COMP_WORDS[0]}" ---completion \(subcommandNames) -- \(argumentName) "${COMP_WORDS[@]}")
"""
}
}
}
/// Returns the case-matching statements for supplying completions after an option or flag.
fileprivate static func generateOptionHandlers(_ commands: [ParsableCommand.Type]) -> String {
ArgumentSet(commands.last!, visibility: .default, parent: nil)
.compactMap { arg -> String? in
let words = arg.bashCompletionWords()
if words.isEmpty { return nil }
// Flags don't take a value, so we don't provide follow-on completions.
if arg.isNullary { return nil }
return """
\(arg.bashCompletionWords().joined(separator: "|")))
\(arg.bashValueCompletion(commands).indentingEachLine(by: 4))
return
;;
"""
}
.joined(separator: "\n")
}
}
extension ArgumentDefinition {
/// Returns the different completion names for this argument.
fileprivate func bashCompletionWords() -> [String] {
return help.visibility.base == .default
? names.map { $0.synopsisString }
: []
}
/// Returns the bash completions that can follow this argument's `--name`.
fileprivate func bashValueCompletion(_ commands: [ParsableCommand.Type]) -> String {
switch completion.kind {
case .default:
return ""
case .file(_):
// TODO: Use '_filedir' when available
// FIXME: Use the extensions array
return #"COMPREPLY=( $(compgen -f -- "$cur") )"#
case .directory:
return #"COMPREPLY=( $(compgen -d -- "$cur") )"#
case .list(let list):
return #"COMPREPLY=( $(compgen -W "\#(list.joined(separator: " "))" -- "$cur") )"#
case .shellCommand(let command):
return "COMPREPLY=( $(\(command)) )"
case .custom:
// Generate a call back into the command to retrieve a completions list
return #"COMPREPLY=( $(compgen -W "$("${COMP_WORDS[0]}" \#(customCompletionCall(commands)) "${COMP_WORDS[@]}")" -- "$cur") )"#
}
}
}
|