skip to content

In Swift Package Manager, how does a build tool plugin differ from a command plugin in when it runs and what it may do?

level: middleimportance: should knowfreq 40%

answer

  1. two extension points
  2. returns commands vs does the work
  3. applied to a target vs invoked by verb
  4. createBuildCommands vs performCommand

basics

~20 s

A build tool plugin is applied to a target and called during builds; it only returns commands that the build runs. A command plugin runs when invoked as swift package <verb>, does the work itself, and may request write or network permissions.

solid answer

~40 s

SwiftPM has two plugin capabilities. A **build tool plugin**, declared with `capability: .buildTool()`, conforms to `BuildToolPlugin` and implements `createBuildCommands(context:target:)`. It is applied to targets with `plugins:`, is called before the build plans those targets, and only *returns* `.buildCommand` or `.prebuildCommand` values; the build runs them, and generated files land in the plugin's work directory. A **command plugin**, declared with `.command(intent:permissions:)`, conforms to `CommandPlugin` and implements `performCommand(context:arguments:)`. It is unrelated to the build graph: it runs when someone types `swift package <verb>`, receives the arguments after the verb, and does the work itself, often by launching a tool and optionally asking SwiftPM to build or test through `packageManager`. Only a command plugin can declare `writeToPackageDirectory` or network permissions, so formatting source in place is a command plugin's job.

code

swift · 29 lines
swift
// swift-tools-version: 6.0
import PackageDescription

let package = Package(
    name: "APIClient",
    products: [
        .library(name: "AppModels", targets: ["AppModels"]),
    ],
    targets: [
        .executableTarget(name: "CodegenTool"),
        // Runs during every build of a target that lists it.
        .plugin(
            name: "SchemaCodegen",
            capability: .buildTool(),
            dependencies: ["CodegenTool"]
        ),
        // Runs only when someone types `swift package format-source-code`.
        .plugin(
            name: "FormatSources",
            capability: .command(
                intent: .sourceCodeFormatting(),
                permissions: [
                    .writeToPackageDirectory(reason: "Rewrites Swift files in place")
                ]
            )
        ),
        .target(name: "AppModels", plugins: ["SchemaCodegen"]),
    ]
)

go deeper

for a junior

Recall the pair: build tool plugins run during a build of the target they are applied to, command plugins run when you type swift package and a verb.

for a middle

Explain both entry points and capabilities, that a build tool plugin only returns commands, and that only command plugins declare intents and permissions.

for a senior

Pick the right kind for a real need, generated code versus in-place formatting, and explain what the sandbox and the missing permissions force on each.

for a principal

Decide which checks belong in every build and which stay on demand, weighing build time and developer friction against keeping the repository consistent.

## Two extension points Swift Package Manager (SwiftPM) lets a package extend it with **plugins**: Swift code, written against the `PackagePlugin` module, that SwiftPM compiles into an executable for the host machine and runs as a separate process. A plugin target declares one **capability**, and the capability decides when SwiftPM calls the plugin, which entry point it calls, and what the plugin may do. | | Build tool plugin | Command plugin | |---|---|---| | Capability | `.buildTool()` | `.command(intent:permissions:)` | | Protocol | `BuildToolPlugin` | `CommandPlugin` | | Entry point | `createBuildCommands(context:target:)` | `performCommand(context:arguments:)` | | Triggered by | building a target that lists it in `plugins:` | `swift package <verb>`, or an IDE action | | Scope | one target per call | the whole package, narrowed by arguments | | Who does the work | the commands it returns, run by the build | the plugin itself | | May modify package sources | no | yes, with `writeToPackageDirectory` and approval | ## The build tool plugin: a command factory A build tool plugin is applied to a target. SwiftPM calls it after resolving the package graph and before the build system creates its dependency graph, and calls it again when the target or the build parameters change. The plugin receives a `PluginContext` and the `Target`, and returns an array of `Command` values: - `.buildCommand(...)` joins the build graph with declared input and output files and runs only when an output is missing or out of date. - `.prebuildCommand(...)` runs before every build and writes into an output directory whose contents become the outputs. The plugin does not run the generator itself; SwiftPM's documentation stresses that it only constructs the command lines that the build runs later. The documentation also says build tool plugins cannot modify the package's source code, so generated files go into the plugin's work directory and SwiftPM compiles them into the target. ## The command plugin: an action on demand A command plugin is a user action that has nothing to do with the build graph. It declares an **intent**: 1. `.documentationGeneration()`, invoked as `swift package generate-documentation`; 2. `.sourceCodeFormatting()`, invoked as `swift package format-source-code`; 3. `.custom(verb:description:)` for anything else, invoked as `swift package <verb>`. SwiftPM passes every argument after the verb to `performCommand(context:arguments:)`; `ArgumentExtractor` helps parse conventions such as `--target AppModels`, because a plugin can import Foundation and the standard libraries but not other packages' libraries. The plugin does its work directly, usually by launching a tool from `context.tool(named:)` with `Process`. Through the `packageManager` property it can also ask SwiftPM to `build(_:parameters:)`, `test(_:parameters:)` or `getSymbolGraph(for:options:)`. A command plugin also declares **permissions**. `.writeToPackageDirectory(reason:)` lets it rewrite source files, and `.allowNetworkConnections(scope:reason:)` (tools version 5.9 and later) lets it reach the network; SwiftPM grants either only after approval, given at a prompt or with a command-line flag. ## What both kinds share The two capabilities differ in timing and power, but the runtime around them is the same: - SwiftPM compiles the plugin's sources into an executable for the host and runs it as a **separate process** that talks to SwiftPM through messages. - On platforms that support it, that process runs in a **sandbox** that blocks network access and writes outside a few allowed locations, including a temporary directory and the plugin's work directory. - Both entry points are `async throws`. A thrown error marks the invocation as failed and is shown to the user, and the `Diagnostics` API (`Diagnostics.error`, `.warning`, `.remark`) reports problems, optionally with a file and line. - Both find their tools with `context.tool(named:)`, which looks up a named executable that the plugin target depends on, such as an executable target, a binary target or another package's executable product. ## How to choose - The output must exist for the target to compile, on every build: a **build tool plugin** (generated models, resource bundles, version constants). - A person or CI job decides when it runs, or it must change files in the repository: a **command plugin** (formatting, documentation, a release checklist). - It must reach the network: a **command plugin** with an approved network permission; a build tool plugin has no permission to declare. - It should check code on every build: a build tool plugin can return a command that only reads sources, while fixing those sources in place is a command plugin's job. ## In Xcode Xcode ships a module, `XcodeProjectPlugin`, that extends the same API to Xcode project targets: a plugin conforms to `XcodeBuildToolPlugin` or `XcodeCommandPlugin` inside `#if canImport(XcodeProjectPlugin)` and receives an `XcodePluginContext`. When targets are chosen in Xcode's interface, Xcode passes their names as `--target` arguments to a command plugin, the same convention the command line uses. The short version for an interview: a build tool plugin says *what the build should run* for one target; a command plugin *is* the action, run on request, with the permissions it asked for.

  • Can a command plugin build or test the package it runs on?
    Yes. `CommandPlugin` exposes a `packageManager` property whose `build(_:parameters:)`, `test(_:parameters:)` and `getSymbolGraph(for:options:)` ask SwiftPM to do that work and return the results, such as built artifacts or test outcomes. A build tool plugin has no such service; it only returns commands.
  • How does one plugin support both Swift packages and Xcode project targets?
    Implement the `PackagePlugin` entry point, then add a conformance to `XcodeBuildToolPlugin` or `XcodeCommandPlugin` inside `#if canImport(XcodeProjectPlugin)`. Xcode provides that module and calls the variant that takes an `XcodePluginContext` and, for build tools, an `XcodeTarget`; outside Xcode the conditional code is skipped.

  • A build tool plugin runs the code generator itself inside createBuildCommands.
  • A command plugin runs automatically as part of swift build.
  • A build tool plugin can declare writeToPackageDirectory to update checked-in files.
  • Plugins can import any library from the package's dependencies, such as an argument parser.