Use swift-format as a package plugin

Hi there,

I would like to use the swift-format Package Plugin in a Swift Package.

The Plugin works when I select the target and select "Format Source Code".
However this doesn't work as a build action.

Apply build tool plug-in “Format Source Code” to target “MyFramework” in package “myframework-ios”
internalError("invalid plugin capability command(intent: PackageModel.PluginCommandIntent.sourceCodeFormatting, permissions: [PackageModel.PluginPermission.writeToPackageDirectory(reason: \"This command formats the Swift source files\")])")
Plug-in invocation failed: internalError("invalid plugin capability command(intent: PackageModel.PluginCommandIntent.sourceCodeFormatting, permissions: [PackageModel.PluginPermission.writeToPackageDirectory(reason: \"This command formats the Swift source files\")])")

My guess is that the --allow-writing-to-package-directory is missing by the internal invocation.
Am I missing something or isn't it intended to run those tools as a build action?

swift-tools-version is 5.9
Embedded in Package.swift of my library as

plugins: [
   .plugin(name: "FormatPlugin", package: "swift-format")
]

Thanks in advance.

1 Like

The error message doesn't seem too great, but what it is trying to convey is that you cannot use a command plugin during the build. Only build-tool plugins can be used during the build.

2 Likes

I came across this searching for a way to integrate swift-format's formatting and linting with the Xcode build process - is there anyway as of now to do this or are we stuck with the command line when using apple's swift-format?

I suppose one could create a build tool plugin instead of a command plugin for swift-format, would that work in your case?

That would be great, I would use it for sure!
I found this article describing how to build a Xcode build plugin: Implement Your First Swift Package Build Plugin | by Riccardo Cipolleschi | Better Programming
Some more references from Apple:

There's still this issue, though...

1 Like

IIUC that issue is specific to swift-format itself, not SwiftPM plugins. cc @allevato

Is that still an issue? That post is from 2020, and we merged this PR in 2022 that was supposed to stop overwriting files that weren't actually modified: Don't overwrite files if they are unchanged by myyra · Pull Request #296 · apple/swift-format · GitHub

1 Like