Autocompletion for Swift Package Manager Commands

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.

Auto-completion Swift 5.1

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.

Documentation SPM

If you are using Oh My Zsh, community-driven framework for managing your zsh configuration, then the installation can be even simplified. Oh My Zsh comes with a plugin that

  • bundles the ZSH completion script (generated with Swift 5.1)
  • defines aliases for common operations
AliasDescriptionCommand
spiInitialize a new packageswift package init
spfFetch package dependenciesswift package fetch
spuUpdate package dependenciesswift package update
spxGenerates an Xcode projectswift package generate-xcodeproj
spsPrint the resolved dependency graphswift package show-dependencies
spdPrint parsed Package.swift as JSONswift package dump-package

All you need to do is to add the swiftpm plugin to your plugins array in ~/.zshrc:

plugins=(... swiftpm)

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.

Did you find this article valuable?

Support Marco Eidinger by becoming a sponsor. Any amount is appreciated!