From 9f5e70e3f309d4938a1044c9d60992f3281cdf77 Mon Sep 17 00:00:00 2001 From: adamXbot <111877622+adamXbot@users.noreply.github.com> Date: Fri, 9 Oct 2026 01:21:59 +1100 Subject: [PATCH] Add zsh, bash and fish tab completion to the privacycommand CLI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `privacycommand completion ` prints a completion script; `--help` gives the one line to add for each shell. Scripts are generated from command tables in privacycommandCLIKit/ShellCompletion, so subcommands, options, risk tiers, installed app names, directories and outdated casks complete the same way in every shell. - The app build writes the three scripts to Contents/Resources/completions, and the cask links them with bash_completion / zsh_completion / fish_completion (Homebrew 4.4.24+). They're generated with the SwiftPM build output rather than the embedded copy: macOS drops what a binary writes into its own freshly built .app on its first run, which left _privacycommand empty. The phase now fails if any script comes out empty. - ShellCompletionTests checks every table entry reaches every shell, that zsh and bash parse the scripts, and what bash completes for fixed inputs. zsh was also checked interactively through a pty, both from fpath and via eval; fish isn't installed here. - The Install Command Line Tool… alert, README, in-app manual, CONTRIBUTING and the source-tree README describe completion setup. README and CONTRIBUTING also stop saying `preview` never runs brew or always exits 0, and CONTRIBUTING's `--min-tier warn` example (which exits 2) now uses `high`. Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 14 +- README.md | 10 +- packaging/homebrew/privacycommand.rb | 5 + privacycommand/README.md | 7 +- privacycommand/Resources/Manual/07-reports.md | 1 + privacycommand/Scripts/embed-cli.sh | 30 +- .../ViewModels/CommandLineToolInstaller.swift | 3 +- .../privacycommandCLI/CompletionCommand.swift | 40 ++ .../Sources/privacycommandCLI/main.swift | 7 +- .../ShellCompletion.swift | 378 ++++++++++++++++++ .../ShellCompletionTests.swift | 124 ++++++ 11 files changed, 608 insertions(+), 11 deletions(-) create mode 100644 privacycommand/Sources/privacycommandCLI/CompletionCommand.swift create mode 100644 privacycommand/Sources/privacycommandCLIKit/ShellCompletion.swift create mode 100644 privacycommand/Tests/privacycommandCLIKitTests/ShellCompletionTests.swift diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 36e5dca..01d0ec6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -87,13 +87,14 @@ arguments it checks your outdated Homebrew casks: ```sh $BIN preview -$BIN preview --all-apps --only-noteworthy --min-tier warn +$BIN preview --all-apps --only-noteworthy --min-tier high $BIN preview --json $BIN preview --fetch firefox # download the incoming build and diff it ``` -`preview` is inform-only: it never runs `brew`, never blocks an update, and -always exits 0. It understands `.dmg` and `.zip` cask artifacts; `.pkg` is +`preview` is inform-only: it runs read-only `brew` queries but never +`brew upgrade`, never blocks an update, and exits 0 whenever it completes (2 +on a usage error or when Homebrew is missing). It understands `.dmg` and `.zip` cask artifacts; `.pkg` is skipped. With `--fetch`, an incoming build is analysed *before* Gatekeeper has cleared it, so a one-off notarization difference can simply be a fresh-download artifact — the output flags this when it happens. @@ -102,6 +103,13 @@ Running `privacycommand` with no arguments opens an interactive browser when stdin and stdout are a terminal, and prints usage otherwise so CI callers do not hang. +`privacycommand completion ` prints a tab-completion script. +The scripts are generated from the command tables in +`Sources/privacycommandCLIKit/ShellCompletion.swift`, so a new subcommand or +flag goes there as well as into the command's help text; `ShellCompletionTests` +checks every table entry reaches every shell and that the scripts parse. The +app build writes them into the bundle for the Homebrew cask to link. + ## What CI runs Two workflows run on every pull request against `main`: diff --git a/README.md b/README.md index dafb175..df17892 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ brew install --cask privacykey/tap/privacycommand **Command line** — the app also carries a command-line tool of the same name, `privacycommand`, which runs the same analyser from Terminal. There are two ways to put it on your `PATH`: -- **Homebrew** — the cask links `privacycommand` for you on install and removes it on uninstall. Nothing else to do. +- **Homebrew** — the cask links `privacycommand` for you on install, along with its zsh, bash and fish tab completion, and removes them on uninstall. Nothing else to do. - **Direct download** — choose **privacycommand ▸ Install Command Line Tool…**. It links the copy inside the app into `/usr/local/bin`, so the tool updates with the app. When that folder needs administrator rights, as it does on most Macs, it shows the `sudo ln -s` command to paste into Terminal instead, with a button that copies it. The same menu item then reads **Uninstall Command Line Tool…** and removes the link. ```sh @@ -70,7 +70,13 @@ privacycommand preview # check outdated Homebrew casks before you upgrad privacycommand --help # every command and flag ``` -`preview` inspects Homebrew casks *before* you update them; it never runs `brew`, never blocks an update, and always exits 0. To build the CLI from source instead, see [CONTRIBUTING.md](CONTRIBUTING.md#the-privacycommand-cli). +**Tab completion** — Homebrew sets it up. Otherwise add one line to your shell's startup file; `privacycommand completion --help` lists them. For zsh, put this in `~/.zshrc` after `compinit`: + +```sh +eval "$(privacycommand completion zsh)" +``` + +`preview` inspects Homebrew casks *before* you update them. It runs read-only `brew` queries but never `brew upgrade`, never blocks an update, and exits 0 whenever it completes. To build the CLI from source instead, see [CONTRIBUTING.md](CONTRIBUTING.md#the-privacycommand-cli). ## Docs diff --git a/packaging/homebrew/privacycommand.rb b/packaging/homebrew/privacycommand.rb index 93526ce..e1d608c 100644 --- a/packaging/homebrew/privacycommand.rb +++ b/packaging/homebrew/privacycommand.rb @@ -25,6 +25,11 @@ # and removes the link on uninstall. DMG installs use the app menu's # Install Command Line Tool… item instead. binary "#{appdir}/privacycommand.app/Contents/Helpers/privacycommand" + # Its tab completion, generated at build time by `privacycommand + # completion `. + bash_completion "#{appdir}/privacycommand.app/Contents/Resources/completions/privacycommand.bash" + zsh_completion "#{appdir}/privacycommand.app/Contents/Resources/completions/_privacycommand" + fish_completion "#{appdir}/privacycommand.app/Contents/Resources/completions/privacycommand.fish" # We're not sandboxed, so quitting the app is enough — no need for # a tighter `quit:` predicate. The in-app Sparkle updater is diff --git a/privacycommand/README.md b/privacycommand/README.md index ad106db..237e07d 100644 --- a/privacycommand/README.md +++ b/privacycommand/README.md @@ -42,8 +42,11 @@ fiddling that earlier versions of this README walked through. The builds the `privacycommand` CLI with SwiftPM for the app's architectures, stamps the app's version into it, copies it to `Contents/Helpers/privacycommand` and signs it with the app's identity and - hardened runtime. The Homebrew cask's `binary` stanza and the app - menu's Install Command Line Tool… item both link to that path. + hardened runtime. It also runs `privacycommand completion ` to + write zsh, bash and fish completion scripts to + `Contents/Resources/completions`. The Homebrew cask's `binary` and + `*_completion` stanzas link those, and the app menu's Install Command + Line Tool… item links the binary. - Sparkle 2 wired in for in-app updates (you have to add it once via **File → Add Package Dependencies…** — see the top-level README). diff --git a/privacycommand/Resources/Manual/07-reports.md b/privacycommand/Resources/Manual/07-reports.md index 8e7ce0c..8e7e96e 100644 --- a/privacycommand/Resources/Manual/07-reports.md +++ b/privacycommand/Resources/Manual/07-reports.md @@ -14,5 +14,6 @@ privacycommand also comes with a command-line tool of the same name, `privacycom - **Installed with Homebrew:** the cask has already put the `privacycommand` command on your `PATH`. - **Installed from the disk image:** choose **privacycommand ▸ Install Command Line Tool…**. It links the copy inside the app into `/usr/local/bin`, so the tool updates with the app. If that folder needs administrator rights, the alert shows the `sudo` command to run in Terminal instead, with a button that copies it. Choose **Uninstall Command Line Tool…** from the same place to remove the link. +- **Tab completion:** Homebrew installs it for zsh, bash and fish. Otherwise run `privacycommand completion --help` for the line to add to your shell's startup file, for example `eval "$(privacycommand completion zsh)"` in `~/.zshrc`. Run privacycommand from the Applications folder before installing the tool: a link into a copy that is still on the disk image stops working when the image is ejected, so the item asks you to move the app first. diff --git a/privacycommand/Scripts/embed-cli.sh b/privacycommand/Scripts/embed-cli.sh index 0b0984f..63ecebc 100755 --- a/privacycommand/Scripts/embed-cli.sh +++ b/privacycommand/Scripts/embed-cli.sh @@ -3,10 +3,14 @@ # privacycommand.app/Contents/Helpers/privacycommand, and sign it with the # app's identity and hardened runtime so the notarized bundle stays valid. # +# Also writes its zsh, bash and fish completion scripts to +# Contents/Resources/completions. +# # Runs as the app target's "Embed command-line tool" build phase. Homebrew's # cask links the embedded binary onto PATH (the `binary` stanza in -# packaging/homebrew/privacycommand.rb); DMG installs link it from the app -# menu's Install Command Line Tool… item. +# packaging/homebrew/privacycommand.rb) and the completions into its +# completion folders; DMG installs link the binary from the app menu's +# Install Command Line Tool… item. set -euo pipefail @@ -78,6 +82,28 @@ chmod 755 "${DEST}/${PRODUCT}" # slice, so unsigned builds still run. xcrun strip -S -x "${DEST}/${PRODUCT}" +# Tab completion for the cask's *_completion stanzas, generated by the CLI +# itself so the scripts always match its options. This runs the SwiftPM build +# rather than the copy just embedded: macOS silently drops what a binary +# writes into its own freshly built .app on its first run, which left +# _privacycommand empty. +GENERATED="${DERIVED_FILE_DIR}/completions" +COMPLETIONS="${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/completions" +mkdir -p "${GENERATED}" "${COMPLETIONS}" +for SHELL_NAME in zsh bash fish; do + case "${SHELL_NAME}" in + zsh) FILE=_privacycommand ;; + bash) FILE=privacycommand.bash ;; + fish) FILE=privacycommand.fish ;; + esac + "${BIN}" completion "${SHELL_NAME}" > "${GENERATED}/${FILE}" + if [[ ! -s "${GENERATED}/${FILE}" ]]; then + echo "error: \`${PRODUCT} completion ${SHELL_NAME}\` printed nothing" >&2 + exit 1 + fi + cp -f "${GENERATED}/${FILE}" "${COMPLETIONS}/${FILE}" +done + # Follow Xcode's signing choice for unsigned builds (App CI). if [[ "${CODE_SIGNING_ALLOWED:-YES}" == "NO" ]]; then echo "Embedded ${PRODUCT} without signing (CODE_SIGNING_ALLOWED=NO)." diff --git a/privacycommand/Sources/privacycommand/ViewModels/CommandLineToolInstaller.swift b/privacycommand/Sources/privacycommand/ViewModels/CommandLineToolInstaller.swift index ac42f59..f49a9a8 100644 --- a/privacycommand/Sources/privacycommand/ViewModels/CommandLineToolInstaller.swift +++ b/privacycommand/Sources/privacycommand/ViewModels/CommandLineToolInstaller.swift @@ -78,7 +78,8 @@ final class CommandLineToolInstaller: ObservableObject { refresh() inform("The command-line tool is installed", "\(tool.link.path) now links to the copy inside privacycommand, so it updates with the app. " - + "Open a new Terminal window and run “privacycommand --help” to get started.") + + "Open a new Terminal window and run “privacycommand --help” to get started. " + + "For tab completion, see “privacycommand completion --help”.") } catch { refresh() report(error, verb: "install") diff --git a/privacycommand/Sources/privacycommandCLI/CompletionCommand.swift b/privacycommand/Sources/privacycommandCLI/CompletionCommand.swift new file mode 100644 index 0000000..30ab049 --- /dev/null +++ b/privacycommand/Sources/privacycommandCLI/CompletionCommand.swift @@ -0,0 +1,40 @@ +import Foundation +import privacycommandCLIKit + +/// `privacycommand completion ` — print a tab-completion script. +/// The scripts themselves are generated by `ShellCompletion`. +enum CompletionCommand { + + static let help = """ + usage: privacycommand completion + + Print a tab-completion script for your shell. A Homebrew install sets these + up for you. Otherwise, add one of these: + + zsh in ~/.zshrc, after `autoload -Uz compinit && compinit`: + eval "$(privacycommand completion zsh)" + bash in ~/.bash_profile: + eval "$(privacycommand completion bash)" + fish run once: + privacycommand completion fish > ~/.config/fish/completions/privacycommand.fish + + Completes subcommands, options, installed app names, risk tiers, and the + outdated casks `preview` would look at. + """ + + static func run(_ argv: [String]) -> Never { + guard let first = argv.first else { die("no shell given.\n\n" + help, code: 2) } + if first == "-h" || first == "--help" { + print(help) + exit(0) + } + guard argv.count == 1 else { + die("completion takes one shell (extra argument: \(argv[1]))", code: 2) + } + guard let shell = ShellCompletion.Shell(rawValue: first) else { + die("unknown shell: \(first) (one of: zsh, bash, fish)", code: 2) + } + print(ShellCompletion.script(for: shell), terminator: "") + exit(0) + } +} diff --git a/privacycommand/Sources/privacycommandCLI/main.swift b/privacycommand/Sources/privacycommandCLI/main.swift index 5963b82..ea783bb 100644 --- a/privacycommand/Sources/privacycommandCLI/main.swift +++ b/privacycommand/Sources/privacycommandCLI/main.swift @@ -10,6 +10,7 @@ import privacycommandCLIKit // privacycommand audit same, explicit // privacycommand -i | interactive force the interactive browser // privacycommand preview [options] preview the apps you're about to update +// privacycommand completion print a zsh, bash or fish completion script // // `` is a path to a .app or an app-name substring matched against // installed apps. See `AuditCommand` / `privacycommand audit --help`. @@ -34,9 +35,11 @@ usage: privacycommand audit same, explicit privacycommand -i, interactive force the interactive browser privacycommand preview [options] preview apps before you update them + privacycommand completion print a tab-completion script (zsh, bash, fish) is a path to a .app or an app-name substring (like `witr`). -Run `privacycommand audit --help` or `privacycommand preview --help` for options. +Run `privacycommand audit --help`, `privacycommand preview --help` or +`privacycommand completion --help` for details. """ private func stdioIsTTY() -> Bool { @@ -55,6 +58,8 @@ case "preview": PreviewCommand.run(Array(arguments.dropFirst())) case "audit": AuditCommand.run(Array(arguments.dropFirst())) +case "completion": + CompletionCommand.run(Array(arguments.dropFirst())) case "-i", "--interactive", "interactive": InteractiveCommand.run() case "--tui-selftest": diff --git a/privacycommand/Sources/privacycommandCLIKit/ShellCompletion.swift b/privacycommand/Sources/privacycommandCLIKit/ShellCompletion.swift new file mode 100644 index 0000000..2e85295 --- /dev/null +++ b/privacycommand/Sources/privacycommandCLIKit/ShellCompletion.swift @@ -0,0 +1,378 @@ +import Foundation + +/// Tab completion for the `privacycommand` CLI in zsh, bash and fish. +/// +/// `privacycommand completion ` prints these scripts, and the release +/// build writes them into the app bundle (`Contents/Resources/completions`) for +/// the Homebrew cask to link. All three are generated from the command tables +/// below, so a new subcommand or flag goes there as well as into the command's +/// help text. +/// +/// What completes: +/// - the subcommands, and the top-level options; +/// - installed app names (the `*.app` names `privacycommand ` matches +/// against) and directories, wherever an app target is expected; +/// - audit options after `audit ` or a bare ``; +/// - preview options, `--min-tier` levels, `--apps-dir` directories, and the +/// outdated cask tokens `brew outdated --cask` lists; +/// - the shell names after `completion`. +public enum ShellCompletion { + + public enum Shell: String, CaseIterable, Sendable { + case zsh, bash, fish + + /// The file name each shell (and Homebrew's cask stanzas) expects. + public var fileName: String { + switch self { + case .zsh: return "_privacycommand" + case .bash: return "privacycommand.bash" + case .fish: return "privacycommand.fish" + } + } + } + + public struct Option: Sendable { + public enum Value: Sendable { + case directory + case choices([String]) + } + + public let short: String? + public let long: String + public let help: String + public let value: Value? + + init(_ short: String?, _ long: String, _ help: String, value: Value? = nil) { + self.short = short + self.long = long + self.help = help + self.value = value + } + + var names: [String] { [short, long].compactMap { $0 } } + } + + public struct Subcommand: Sendable { + public let name: String + public let help: String + } + + public static let command = "privacycommand" + + public static let subcommands: [Subcommand] = [ + Subcommand(name: "audit", help: "static audit of one app"), + Subcommand(name: "preview", help: "preview apps before you update them"), + Subcommand(name: "interactive", help: "open the interactive browser"), + Subcommand(name: "completion", help: "print a tab-completion script"), + ] + + public static let topLevelOptions: [Option] = [ + Option("-h", "--help", "show usage"), + Option("-v", "--version", "print the version"), + Option("-i", "--interactive", "open the interactive browser"), + ] + + public static let auditOptions: [Option] = [ + Option("-s", "--short", "one-line verdict only"), + Option("-t", "--tree", "the app's component tree"), + Option(nil, "--warnings", "only the findings section"), + Option(nil, "--json", "machine-readable JSON"), + Option(nil, "--verbose", "include info-level findings and full lists"), + Option("-x", "--exact", "exact app-name match"), + Option(nil, "--warn-exit", "exit 1 when there are warn or error findings"), + Option(nil, "--no-color", "disable coloured output"), + Option("-h", "--help", "show help"), + ] + + public static let riskTiers = ["low", "medium", "high", "critical"] + + public static let previewOptions: [Option] = [ + Option(nil, "--all-apps", "preview every installed app instead of brew casks"), + Option(nil, "--apps-dir", "preview every app in a folder", value: .directory), + Option(nil, "--fetch", "download each incoming cask and diff it"), + Option(nil, "--min-tier", "only show apps at or above a risk tier", value: .choices(riskTiers)), + Option(nil, "--only-noteworthy", "hide apps with nothing noteworthy"), + Option(nil, "--json", "machine-readable JSON"), + Option("-h", "--help", "show help"), + ] + + /// Folders whose top-level `*.app` names `privacycommand ` matches. + static let appDirectories = ["/Applications", "~/Applications", "/System/Applications"] + + public static func script(for shell: Shell) -> String { + switch shell { + case .zsh: return zsh() + case .bash: return bash() + case .fish: return fish() + } + } + + // MARK: - zsh + + static func zsh() -> String { + func spec(_ o: Option) -> String { + let exclusive = o.names.count > 1 ? "'(\(o.names.joined(separator: " ")))'" : "" + let names = o.names.count > 1 ? "{\(o.names.joined(separator: ","))}" : o.long + var s = "\(exclusive)\(names)'[\(zshEscaped(o.help))]" + switch o.value { + case .none: break + case .directory: s += ":directory:_files -/" + case .choices(let choices): s += ":value:(\(choices.joined(separator: " ")))" + } + return s + "'" + } + let audit = auditOptions.map { " \(spec($0))" }.joined(separator: "\n") + let preview = previewOptions.map { " \(spec($0))" }.joined(separator: "\n") + // Top-level options end the command line: nothing completes after them. + let top = topLevelOptions.map { o -> String in + let names = o.names.count > 1 ? "{\(o.names.joined(separator: ","))}" : o.long + return " '(- *)'\(names)'[\(zshEscaped(o.help))]'" + }.joined(separator: " \\\n") + let commands = subcommands.map { " '\($0.name):\(zshEscaped($0.help))'" }.joined(separator: "\n") + let dirs = appDirectories.joined(separator: " ") + + return """ + #compdef \(command) + # zsh completion for \(command). Generated by `\(command) completion zsh`. + + __\(command)_apps() { + local -a apps + local dir + for dir in \(dirs); do + [[ -d $dir ]] && apps+=( $dir/*.app(N:t:r) ) + done + _wanted apps expl 'installed app' compadd -a apps + } + + __\(command)_targets() { + _alternative \\ + 'apps:installed app:__\(command)_apps' \\ + 'files:app bundle:_files -/' + } + + __\(command)_casks() { + (( $+commands[brew] )) || return 1 + local -a casks + casks=( ${(f)"$(brew outdated --cask --quiet 2>/dev/null)"} ) + _wanted casks expl 'outdated cask' compadd -a casks + } + + _\(command)() { + local curcontext=$curcontext state line ret=1 + local -a audit_opts preview_opts subcmds + audit_opts=( + \(audit) + ) + preview_opts=( + \(preview) + ) + subcmds=( + \(commands) + ) + + _arguments -C \\ + \(top) \\ + '1: :->first' \\ + '*:: :->rest' && ret=0 + + case $state in + first) + _alternative \\ + 'commands:command:{_describe -t commands command subcmds}' \\ + 'targets:app to audit:__\(command)_targets' && ret=0 + ;; + rest) + case $line[1] in + audit) + _arguments -s $audit_opts '1:app to audit:__\(command)_targets' && ret=0 ;; + preview) + _arguments -s $preview_opts '*:outdated cask:__\(command)_casks' && ret=0 ;; + completion) + _arguments '1:shell:(\(Shell.allCases.map(\.rawValue).joined(separator: " ")))' && ret=0 ;; + interactive) ;; + *) + _arguments -s $audit_opts && ret=0 ;; + esac + ;; + esac + return ret + } + + if [[ $funcstack[1] == _\(command) ]]; then + # Autoloaded from fpath (Homebrew, or a site-functions folder). + _\(command) "$@" + elif (( $+functions[compdef] )); then + # Sourced or eval'd from ~/.zshrc, after compinit. + compdef _\(command) \(command) + fi + + """ + } + + // MARK: - bash + + static func bash() -> String { + func words(_ options: [Option]) -> String { + var seen = Set() + return options.flatMap(\.names).filter { seen.insert($0).inserted } + .joined(separator: " ") + } + let dirs = appDirectories.map { $0.replacingOccurrences(of: "~", with: "\"$HOME\"") } + .joined(separator: " ") + let tierWords = riskTiers.joined(separator: " ") + let shells = Shell.allCases.map(\.rawValue).joined(separator: " ") + + return """ + # bash completion for \(command). Generated by `\(command) completion bash`. + # Works with macOS's bash 3.2 and later. + + __\(command)_apps() { + local dir app + for dir in \(dirs); do + [[ -d $dir ]] || continue + for app in "$dir"/*.app; do + [[ -e $app ]] || continue + app=${app##*/} + printf '%s\\n' "${app%.app}" + done + done + } + + # Installed app names plus directories (an .app bundle is a directory). + __\(command)_targets() { + local IFS=$'\\n' + COMPREPLY+=( $(compgen -W "$(__\(command)_apps)" -- "$1") ) + COMPREPLY+=( $(compgen -d -- "$1") ) + } + + _\(command)() { + local cur=${COMP_WORDS[COMP_CWORD]} + local prev=${COMP_WORDS[COMP_CWORD-1]} + local audit_opts="\(words(auditOptions))" + local preview_opts="\(words(previewOptions))" + COMPREPLY=() + + case $prev in + --min-tier) COMPREPLY=( $(compgen -W "\(tierWords)" -- "$cur") ); return 0 ;; + --apps-dir) COMPREPLY=( $(compgen -d -- "$cur") ); return 0 ;; + esac + + if (( COMP_CWORD == 1 )); then + if [[ $cur == -* ]]; then + COMPREPLY=( $(compgen -W "\(words(topLevelOptions + auditOptions))" -- "$cur") ) + else + COMPREPLY=( $(compgen -W "\(subcommands.map(\.name).joined(separator: " "))" -- "$cur") ) + __\(command)_targets "$cur" + fi + return 0 + fi + + case ${COMP_WORDS[1]} in + audit) + if [[ $cur == -* ]]; then + COMPREPLY=( $(compgen -W "$audit_opts" -- "$cur") ) + else + __\(command)_targets "$cur" + fi ;; + preview) + if [[ $cur == -* ]]; then + COMPREPLY=( $(compgen -W "$preview_opts" -- "$cur") ) + elif command -v brew >/dev/null 2>&1; then + COMPREPLY=( $(compgen -W "$(brew outdated --cask --quiet 2>/dev/null)" -- "$cur") ) + fi ;; + completion) + (( COMP_CWORD == 2 )) && COMPREPLY=( $(compgen -W "\(shells)" -- "$cur") ) ;; + interactive|\(topLevelOptions.flatMap(\.names).joined(separator: "|"))) + ;; + *) + [[ $cur == -* ]] && COMPREPLY=( $(compgen -W "$audit_opts" -- "$cur") ) ;; + esac + return 0 + } + + # -o filenames escapes app names with spaces and marks directories. + complete -o filenames -F _\(command) \(command) + + """ + } + + // MARK: - fish + + static func fish() -> String { + let c = command + let dirs = appDirectories.joined(separator: " ") + + func line(_ o: Option, condition: String) -> String { + var s = "complete -c \(c) -n '\(condition)'" + if let short = o.short { s += " -s \(short.dropFirst())" } + s += " -l \(o.long.dropFirst(2))" + switch o.value { + case .none: break + case .directory: s += " -x -a '(__fish_complete_directories (commandline -ct))'" + case .choices(let choices): s += " -x -a '\(choices.joined(separator: " "))'" + } + return s + " -d '\(fishEscaped(o.help))'" + } + + let first = "__fish_use_subcommand" + let audit = "not __fish_use_subcommand; and not __fish_seen_subcommand_from preview completion interactive" + let preview = "__fish_seen_subcommand_from preview" + + let subcommandLines = subcommands.map { + "complete -c \(c) -n '\(first)' -a \($0.name) -d '\(fishEscaped($0.help))'" + } + let topLines = topLevelOptions.map { line($0, condition: first) } + let auditLines = auditOptions.map { line($0, condition: audit) } + let previewLines = previewOptions.map { line($0, condition: preview) } + + return """ + # fish completion for \(c). Generated by `\(c) completion fish`. + + function __\(c)_apps + for dir in \(dirs) + test -d $dir; or continue + for app in $dir/*.app + basename $app .app + end + end + end + + function __\(c)_casks + command -sq brew; and brew outdated --cask --quiet 2>/dev/null + end + + complete -c \(c) -f + + \(subcommandLines.joined(separator: "\n")) + \(topLines.joined(separator: "\n")) + + # An app to audit: the first word, or the word after `audit`. + complete -c \(c) -n '\(first)' -a '(__\(c)_apps)' -d 'installed app' + complete -c \(c) -n '\(first)' -a '(__fish_complete_directories (commandline -ct))' + complete -c \(c) -n '__fish_seen_subcommand_from audit' -a '(__\(c)_apps)' -d 'installed app' + complete -c \(c) -n '__fish_seen_subcommand_from audit' -a '(__fish_complete_directories (commandline -ct))' + \(auditLines.joined(separator: "\n")) + + complete -c \(c) -n '\(preview)' -a '(__\(c)_casks)' -d 'outdated cask' + \(previewLines.joined(separator: "\n")) + + complete -c \(c) -n '__fish_seen_subcommand_from completion' -x -a '\(Shell.allCases.map(\.rawValue).joined(separator: " "))' + + """ + } + + // MARK: - Escaping + + /// Text inside a zsh `_arguments` description: `[`, `]` and `:` are + /// syntax there, and the spec sits inside single quotes. + static func zshEscaped(_ s: String) -> String { + s.replacingOccurrences(of: "'", with: "'\\''") + .replacingOccurrences(of: "[", with: "\\[") + .replacingOccurrences(of: "]", with: "\\]") + .replacingOccurrences(of: ":", with: "\\:") + } + + static func fishEscaped(_ s: String) -> String { + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "'", with: "\\'") + } +} diff --git a/privacycommand/Tests/privacycommandCLIKitTests/ShellCompletionTests.swift b/privacycommand/Tests/privacycommandCLIKitTests/ShellCompletionTests.swift new file mode 100644 index 0000000..714688a --- /dev/null +++ b/privacycommand/Tests/privacycommandCLIKitTests/ShellCompletionTests.swift @@ -0,0 +1,124 @@ +import XCTest +@testable import privacycommandCLIKit + +/// Covers the generated completion scripts: everything in the command tables +/// reaches every shell, the scripts parse, and bash completes the fixed parts +/// of the command line (subcommands, options, tiers, shells). App names and +/// casks depend on the machine, so they're exercised by hand, not here. +final class ShellCompletionTests: XCTestCase { + + private let allOptions = ShellCompletion.topLevelOptions + + ShellCompletion.auditOptions + ShellCompletion.previewOptions + + func testEveryCommandAndOptionReachesEveryShell() { + for shell in ShellCompletion.Shell.allCases { + let script = ShellCompletion.script(for: shell) + for sub in ShellCompletion.subcommands { + XCTAssertTrue(script.contains(sub.name), "\(shell) is missing \(sub.name)") + } + for option in allOptions { + // fish names long options without their dashes (`-l json`). + let long = shell == .fish ? "-l \(option.long.dropFirst(2))" : option.long + XCTAssertTrue(script.contains(long), "\(shell) is missing \(option.long)") + } + for tier in ShellCompletion.riskTiers { + XCTAssertTrue(script.contains(tier), "\(shell) is missing tier \(tier)") + } + } + } + + func testEachScriptRegistersForTheCommand() { + XCTAssertTrue(ShellCompletion.script(for: .zsh).hasPrefix("#compdef privacycommand\n")) + XCTAssertTrue(ShellCompletion.script(for: .zsh).contains("compdef _privacycommand privacycommand")) + XCTAssertTrue(ShellCompletion.script(for: .bash) + .contains("complete -o filenames -F _privacycommand privacycommand")) + XCTAssertTrue(ShellCompletion.script(for: .fish).contains("complete -c privacycommand -f")) + } + + func testFileNamesMatchWhatHomebrewAndEachShellExpect() { + XCTAssertEqual(ShellCompletion.Shell.zsh.fileName, "_privacycommand") + XCTAssertEqual(ShellCompletion.Shell.bash.fileName, "privacycommand.bash") + XCTAssertEqual(ShellCompletion.Shell.fish.fileName, "privacycommand.fish") + } + + func testScriptsParse() throws { + try assertParses(.zsh, with: "/bin/zsh") + try assertParses(.bash, with: "/bin/bash") + guard let fish = ["/opt/homebrew/bin/fish", "/usr/local/bin/fish"] + .first(where: FileManager.default.isExecutableFile) else { return } + try assertParses(.fish, with: fish) + } + + func testBashCompletesTheFixedParts() throws { + let driver = """ + source "$1" + t() { + COMP_WORDS=("$@"); COMP_CWORD=$(( ${#COMP_WORDS[@]} - 1 )) + _privacycommand + printf '%s\\n' "${COMPREPLY[*]}" + } + t privacycommand pre + t privacycommand preview -- + t privacycommand preview --min-tier "" + t privacycommand completion "" + t privacycommand audit --w + t privacycommand SomeApp --s + t privacycommand --version "" + """ + let lines = try run("/bin/bash", ["--norc", "--noprofile", "-s"], scriptFor: .bash, driver: driver) + .split(separator: "\n", omittingEmptySubsequences: false).map(String.init) + XCTAssertEqual(lines.count, 8, "\(lines)") + XCTAssertTrue(lines[0].split(separator: " ").contains("preview")) + XCTAssertEqual(lines[1], "--all-apps --apps-dir --fetch --min-tier --only-noteworthy --json --help") + XCTAssertEqual(lines[2], "low medium high critical") + XCTAssertEqual(lines[3], "zsh bash fish") + XCTAssertEqual(lines[4], "--warnings --warn-exit") + XCTAssertEqual(lines[5], "--short") + XCTAssertEqual(lines[6], "") + } + + // MARK: - Helpers + + private func assertParses(_ shell: ShellCompletion.Shell, with interpreter: String, + file: StaticString = #filePath, line: UInt = #line) throws { + let url = try temporaryScript(for: shell) + let process = Process() + process.executableURL = URL(fileURLWithPath: interpreter) + process.arguments = ["-n", url.path] + let stderr = Pipe() + process.standardError = stderr + try process.run() + process.waitUntilExit() + let message = String(decoding: stderr.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) + XCTAssertEqual(process.terminationStatus, 0, "\(shell): \(message)", file: file, line: line) + } + + /// Runs `driver` on stdin with the shell's script path as `$1`. + private func run(_ interpreter: String, _ arguments: [String], + scriptFor shell: ShellCompletion.Shell, driver: String) throws -> String { + let url = try temporaryScript(for: shell) + let process = Process() + process.executableURL = URL(fileURLWithPath: interpreter) + process.arguments = arguments + [url.path] + process.currentDirectoryURL = url.deletingLastPathComponent() + let stdin = Pipe(), stdout = Pipe() + process.standardInput = stdin + process.standardOutput = stdout + try process.run() + stdin.fileHandleForWriting.write(Data(driver.utf8)) + try stdin.fileHandleForWriting.close() + let output = stdout.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + return String(decoding: output, as: UTF8.self) + } + + private func temporaryScript(for shell: ShellCompletion.Shell) throws -> URL { + let dir = FileManager.default.temporaryDirectory + .appendingPathComponent("ShellCompletionTests-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + addTeardownBlock { try? FileManager.default.removeItem(at: dir) } + let url = dir.appendingPathComponent(shell.fileName) + try ShellCompletion.script(for: shell).write(to: url, atomically: true, encoding: .utf8) + return url + } +}