Autocompletion for Swift Package Manager Commands
This blog post will explain how you can leverage autocompletion for Swift Package Manager commands in your shell by using a completion script that can be generated by SwiftPM. This is helpful for people who just started to use Swift Package Manager but also for people who want to speed up their productivity.
I am using the Z shell (ZSH), but most of my explanation will also work if you use another type of shell, e.g. bash.
When you type a command in your shell and hit the
TAB key, a completion is attempted depending on the context. This context includes:
- What command and options have already been typed at the command-line prompt.
- Where the cursor is.
The context is then given to one or more completer functions that attempt to complete what you’ve typed. Each of these completers are tried in order and, if the first one can’t complete the context, the next one will try. When the context can be completed, some possible matches will be displayed and you can choose whatever you want. ... [Source]
Swift Package Manager ships with tooling to generate such a completer.
- bundles the ZSH completion script (generated with Swift 5.1)
- defines aliases for common operations
|Initialize a new package
swift package init
|Fetch package dependencies
swift package fetch
|Update package dependencies
swift package update
|Generates an Xcode project
swift package generate-xcodeproj
|Print the resolved dependency graph
swift package show-dependencies
|Print parsed Package.swift as JSON
swift package dump-package
All you need to do is to add the swiftpm plugin to your plugins array in
What follows was observed when I wrote this article (August 2022), but I eventually contributed to SPM to get this completion-tool fixed in a future version of a Swift release (beyond Swift 5.7)
If you cannot wait the ohmyzsh has already a working auto-completion script reflecting Swift 5.7
A word of caution: The bundled ZSH completion script in the swiftpm plugin was generated with Swift 5.1 and therefore may not include all subcommands or options available in your local installation.
I tried to generate the
_swift completion script with Swift 5.6.1
swift package completion-tool generate-zsh-script > ~/.oh-my-zsh/completions/_swift
but the generated script is incorrect and throws errors during auto-completion :(
I addressed the issue with Apple and hope for a quick resolution.