skip to content

In a SwiftPM build tool plugin, where should generated Swift files be written, and how do they end up compiled into the target?

level: middleimportance: should knowfreq 30%

answer

  1. not the Sources folder
  2. a directory SwiftPM hands you
  3. declared outputs join the target
  4. pluginWorkDirectoryURL

basics

~20 s

Into the plugin work directory, context.pluginWorkDirectoryURL, listed as the command's outputs. SwiftPM compiles generated .swift outputs into the target the plugin was applied to as if they sat in its source directory, and treats other outputs as resources.

solid answer

~40 s

`PluginContext.pluginWorkDirectoryURL` is a writable directory that SwiftPM gives each plugin for each target it is applied to, and preserves between builds. A build tool plugin builds its output paths there and lists them in `.buildCommand(outputFiles:)`, or points `.prebuildCommand(outputFilesDirectory:)` at a folder there. When the commands have run, SwiftPM compiles every output it recognises as source, such as `.swift`, into the target as if it were in the target's source directory, and treats other files as resources, as if declared with `.process(...)`. Generated code should never go into `Sources/`: the plugin runs sandboxed, the documentation says build tool plugins cannot modify the package's source, and a file written there is also found as an ordinary source and ends up in version control. From tools version 6.0 these APIs take `URL`; the `Path`-based `pluginWorkDirectory` is deprecated.

code

swift · 22 lines
swift
import Foundation
import PackagePlugin

@main
struct SchemaCodegen: BuildToolPlugin {
    func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {
        guard let module = target.sourceModule else { return [] }
        let generator = try context.tool(named: "CodegenTool")
        return module.sourceFiles(withSuffix: "graphql").map { file in
            let base = file.url.deletingPathExtension().lastPathComponent
            let output = context.pluginWorkDirectoryURL
                .appending(path: "\(base)+Schema.swift")
            return .buildCommand(
                displayName: "Generating \(base)+Schema.swift",
                executable: generator.url,
                arguments: [file.url.path(), "-o", output.path()],
                inputFiles: [file.url],
                outputFiles: [output]
            )
        }
    }
}

go deeper

for a junior

Recall that generated files go in context.pluginWorkDirectoryURL, not in Sources, and are compiled into the target automatically.

for a middle

Explain how declared outputs join the target: Swift files compiled as if in the source directory, other files processed as resources.

for a senior

Diagnose a generator whose output the target cannot see, and explain why writing into Sources leads to duplicate builds and stale committed code.

for a principal

Decide whether generated code is a build artifact or checked-in source, and pick a build tool plugin or a command plugin to match.

## The work directory A **build tool plugin** in Swift Package Manager (SwiftPM) is called with a `PluginContext` and a `Target` and returns the commands the build should run. The context carries `pluginWorkDirectoryURL`, which SwiftPM documents as: - **writable** by the plugin and by the commands it constructs; - **owned by the plugin**, which decides what is written under it, whether generated sources or caches; - **preserved between builds**, so a generator can keep a cache there; - **separate per plugin and per target**: the same plugin applied to two targets gets two directories, which keeps their outputs from colliding. In a command-line build the directory sits under `.build/plugins/outputs/`; the exact layout below that is SwiftPM's business, so code must always ask the context for the path rather than build it by hand. ## Declaring outputs The directory only matters because commands declare their outputs inside it: 1. For a `.buildCommand`, compute each output path from the input file's name, append it to `pluginWorkDirectoryURL`, and pass it in `outputFiles:`. Put the same input in `inputFiles:` so the build knows when to rerun the command. 2. For a `.prebuildCommand`, pass a folder inside the work directory as `outputFilesDirectory:`. Whatever files are in that folder after the command runs are its outputs. 3. Pass those same paths in `arguments:`, because the plugin only describes the command; the tool it launches still has to be told where to write. ## How outputs join the target After the commands run, SwiftPM treats their outputs as part of the target the plugin was applied to: | Output | What SwiftPM does with it | |---|---| | A Swift source file such as `User+Schema.swift` | Compiled into the target as if it sat in the target's source directory | | Any other file, such as a JSON or an asset | Treated as a resource, as if listed in the manifest with `.process(...)` | Because generated Swift is compiled into the same module, the rest of the target uses it with no `import`: a function in `Models.swift` can return `UserSchema.lineCount` from a type that exists only in the work directory. Generated resources are processed like any other processed resource, so the target reaches them through its resource bundle. ## Why not write into Sources It is tempting to point a generator at `Sources/AppModels/Generated`. Don't: - The plugin process runs sandboxed, and SwiftPM's documentation says build tool plugins cannot modify the package's source code; the work directory is the location the design gives them. - A file written into `Sources/` is also discovered as an ordinary source on the next build. In a test build with Swift 6.4, a command that wrote there was not stopped, but the next build warned `Skipping duplicate build file` for the generated file. - Generated files in the source tree end up in code review and version control, and go stale whenever someone forgets to rebuild. If a team wants generated code checked in, that is a **command plugin** with the `writeToPackageDirectory` permission, run on purpose, not a build tool plugin. ## Tools-version notes The tools version on the manifest's first line also sets which `PackagePlugin` API a plugin may call. Tools version 6.0 added the `URL`-based API: `pluginWorkDirectoryURL`, `Tool.url`, `File.url`, and the `.buildCommand` and `.prebuildCommand` cases that take `URL` values. The `Path`-based `pluginWorkDirectory`, `Tool.path` and `Path` overloads are deprecated from 6.0. Some members arrived later: `Target.directoryURL` is introduced in 6.1, and a plugin in a 6.0 package that uses it fails to compile with `'directoryURL' is unavailable`. ## Where the tool comes from The command still needs an executable to run. `context.tool(named:)` looks it up among the plugin target's dependencies, an `executableTarget` in the same package, a `binaryTarget`, or an executable product of a dependency, and throws if it cannot find it; the lookup is case-sensitive. For a build command, SwiftPM builds an executable dependency for the host before the command needs it, so the tool in the example can be an ordinary `executableTarget` named `CodegenTool`. Each returned `Command` carries `executable: generator.url`, so the plugin never hard-codes a path into `.build`. ## A quick check After `swift build`, look for the generated file under `.build/plugins/outputs/` and confirm that the target compiles code that refers to it. If the target cannot see a generated type, check that the tool wrote to exactly the path declared in `outputFiles:`; a file written anywhere else is not part of the target.

  • What happens to a generated JSON file that a build command lists among its outputFiles?
    SwiftPM treats any output it does not recognise as source as a resource, as if the manifest had listed it with `.process(...)`. It is processed into the target's resource bundle and reached at runtime through that bundle, the same way a hand-written processed resource is.
  • Why does a plugin that uses target.directoryURL fail to compile in one package but not another?
    A plugin is compiled against the `PackagePlugin` API of its package's tools version. `Target.directoryURL` is introduced in tools version 6.1, so in a 6.0 package the compiler reports `'directoryURL' is unavailable`. Raise the tools version or use the API that version offers.

  • A build tool plugin should write generated files into the target's Sources folder.
  • Generated Swift files have to be imported as a separate module by the target.
  • SwiftPM wipes the plugin work directory before every build, so caches there are useless.
  • Any non-Swift file a build command generates is silently ignored.

Assumes tools version 6.0 or later, where pluginWorkDirectoryURL and the URL-based Command cases replace the deprecated Path API.