skip to content

A SwiftPM build tool plugin generates Swift types from a GraphQL schema; when should it return .buildCommand rather than .prebuildCommand, and what does each cost?

level: seniorimportance: should knowfreq 25%

answer

  1. known names vs unknown names
  2. in the build graph vs before it
  3. every build pays for prebuild
  4. prebuild tools must be prebuilt

basics

~20 s

Return .buildCommand when output names follow from input paths alone: it joins the build graph and reruns only when needed. Use .prebuildCommand only when names depend on file contents; it runs before every build and needs a binary-target tool.

solid answer

~50 s

A `.buildCommand` declares `inputFiles:` and `outputFiles:`, so the build schedules it like any other step and reruns it only when an output is missing or an input changed. Its output paths may depend on input *paths* but must not depend on reading input *contents*. If the generator writes one `User.graphql` → `User+Schema.swift` file per input, that fits. If it reads one schema and writes a file per type it finds, the names are unknown until it runs, so it needs `.prebuildCommand(outputFilesDirectory:)`: SwiftPM runs it before every build and takes whatever is in that directory as outputs. That costs time on every incremental build, so the tool must cache, writing only changed files and deleting stale ones. A prebuild command also cannot use a tool built from source: SwiftPM stops with `a prebuild command cannot use executables built from source`, so the tool must come from a `binaryTarget` artifact bundle.

code

swift · 20 lines
swift
import PackagePlugin

@main
struct SchemaTypes: BuildToolPlugin {
    func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {
        guard let module = target.sourceModule,
              let schema = module.sourceFiles(withSuffix: "graphqls").first
        else { return [] }
        // Which types the schema declares is unknown until the tool reads it.
        let outputDir = context.pluginWorkDirectoryURL.appending(path: "Generated")
        return [
            .prebuildCommand(
                displayName: "Generating types from \(schema.url.lastPathComponent)",
                executable: try context.tool(named: "graphql-gen").url,
                arguments: [schema.url.path(), outputDir.path()],
                outputFilesDirectory: outputDir
            )
        ]
    }
}

go deeper

for a junior

Recall the rule of thumb: build commands for known output names, prebuild commands only when names are unknown until the tool runs.

for a middle

Explain how a build command's declared inputs and outputs let the build skip it, and why a prebuild command runs every time.

for a senior

Diagnose the binary-target error, restructure a generator so its outputs are predictable, and make a prebuild tool cache and clean up after itself.

for a principal

Treat prebuild commands as a build-time budget: every incremental build pays for them, so push generators toward predictable names.

## Two kinds of command A **build tool plugin** in Swift Package Manager (SwiftPM) returns an array of `Command` values from `createBuildCommands(context:target:)`. It can mix two kinds: | | `.buildCommand` | `.prebuildCommand` | |---|---|---| | Declares | `inputFiles:` and `outputFiles:` | `outputFilesDirectory:` | | When it runs | During the build, when an output is missing or out of date | Unconditionally, before every build | | Output names | Known before it runs; may depend on input paths, not on input contents | Whatever is in the directory afterwards | | Tool it may run | An executable target, an executable product or a binary target | A binary target only | | Incremental cost | Skipped when nothing changed | Paid on every build | SwiftPM's documentation states the preference directly: create a build command whenever the paths of all inputs and outputs are known before the command runs, and a prebuild command only when the output names are not. ## The GraphQL case The same generator can land on either side, depending on how its output is named. - **One output per input file.** The schema is split into `User.graphql`, `Order.graphql` and so on, and the generator writes `User+Schema.swift` for `User.graphql`. The plugin can compute every output path from the input path, so it returns one `.buildCommand` per file. Editing `Order.graphql` reruns one command; editing a Swift file reruns none. - **Outputs named by contents.** One `schema.graphqls` file declares `type User`, `type Order` and more, and the generator writes one Swift file per declared type. The plugin cannot know the file names without parsing the schema, and the documentation says output paths of a build command must not depend on reading input contents. This is the case `.prebuildCommand` exists for. A third option often beats both: have the generator write **one** file with a fixed name, such as `Schema+Types.swift`, holding every type. The name is known again, so a `.buildCommand` works and the per-build cost disappears. ## The binary-tool rule for prebuild Prebuild commands run before the build starts, so nothing has been compiled yet, including any tool built from source. If the plugin depends on an `executableTarget` and returns a prebuild command, planning stops: ``` error: a prebuild command cannot use executables built from source, including executable target 'CodegenTool' ``` The fix is to ship the generator prebuilt: an **artifact bundle** (an `.artifactbundle` directory with an `info.json` that lists the executable per platform triple), declared with `.binaryTarget(name:path:)` or `.binaryTarget(name:url:checksum:)` and listed in the plugin's `dependencies`. Build commands have no such limit; SwiftPM builds executable dependencies for the host before running them. ## Keeping a prebuild command cheap Because the command runs on every build, the documentation tells the tool to do its own caching. In practice: - Write a file only when its contents changed, so unchanged files keep their timestamps and the build can treat them as unchanged. - Delete files for types that no longer exist; anything left in the directory is still compiled. - Keep the output directory inside `context.pluginWorkDirectoryURL`, which SwiftPM preserves between builds, and give each command its own subfolder. - Keep the tool's startup fast; a slow launch is paid on every incremental build, even when nothing changed. ## A decision checklist 1. Can the plugin name every output from the input paths alone? Use `.buildCommand`. 2. Can the generator be changed to write fixed file names? Change it, then use `.buildCommand`. 3. Otherwise use `.prebuildCommand`, ship the tool as a binary target, and make the tool skip unchanged writes. One plugin may return both kinds; the build incorporates the build commands into its graph and runs the prebuild commands after the plugin runs but before the build starts. ## Reading the cost in practice The difference shows up in incremental builds, the ones developers run dozens of times a day. With build commands, touching an unrelated Swift file reruns no generator at all, because the build sees that every declared output exists and none of its declared inputs changed. With a prebuild command, the same edit still launches the tool, which re-reads the schema and compares its outputs before the compiler starts. On a small schema that is noise; on a large one, or with a tool that starts slowly, it becomes a delay on every build in every module that applies the plugin. That cost, multiplied by the number of targets, is what an interviewer wants a senior candidate to name.

  • Does a build command need exactly one output file per input file?
    No. SwiftPM's documentation says build commands need no one-to-one correspondence; a command may examine the target and produce several outputs, or none. The constraint is only that the output paths are known before it runs and do not depend on reading the inputs' contents.
  • How do you ship a prebuilt generator for a prebuild command?
    Package it as an artifact bundle: a `.artifactbundle` directory whose `info.json` lists the executable and the platform triples each variant supports. Declare it with `.binaryTarget(name:path:)` locally or `.binaryTarget(name:url:checksum:)` remotely, add it to the plugin target's dependencies, and find it with `context.tool(named:)`.
  • What happens to a generated file whose schema type was removed, in a prebuild output directory?
    It is still compiled, because every file in the directory after the command runs counts as an output. The tool must delete files it no longer produces; otherwise removed types keep compiling and can collide with new code.

  • Prebuild commands are faster because they run before the build instead of during it.
  • A build command may read the schema first to decide its output file names.
  • A prebuild command can use any executable target from the same package as its tool.
  • SwiftPM caches prebuild results, so the tool does not need to skip unchanged writes.

Assumes tools version 6.0 or later, where the Command cases take URL values; the Path-based buildCommand and prebuildCommand overloads are deprecated from 6.0.