Skip to content

Instantly share code, notes, and snippets.

@tonyarnold
Last active April 13, 2025 04:29
Show Gist options
  • Save tonyarnold/9ce276cb6cd3c0e4933c070e1ab5ecac to your computer and use it in GitHub Desktop.
Save tonyarnold/9ce276cb6cd3c0e4933c070e1ab5ecac to your computer and use it in GitHub Desktop.
// swift-tools-version: 6.1
import PackageDescription
let package = Package(
name: "SwiftFormatPlugin",
products: [
.plugin(name: "SwiftFormatPlugin", targets: ["SwiftFormatPlugin"])
],
targets: [
.plugin(name: "SwiftFormatPlugin", capability: .buildTool)
]
)
import Foundation
import PackagePlugin
@main
struct SwiftFormatPlugin: BuildToolPlugin {
func createBuildCommands(context: PluginContext, target: Target) async throws -> [Command] {
guard let sourceFiles = target.sourceModule?.sourceFiles else { return [] }
let tool = try context.tool(named: "swift-format")
let paths = sourceFiles.map(\.url)
.filter { $0.pathExtension == "swift" }
.map{ $0.path(percentEncoded: false) }
return [
.prebuildCommand(
displayName: "Checking the format of Swift files in \(target.name)",
executable: tool.url,
arguments: ["lint", "--parallel", "--no-color-diagnostics"] + paths,
outputFilesDirectory: context.pluginWorkDirectoryURL
)
]
}
}
#if canImport(XcodeProjectPlugin)
import XcodeProjectPlugin
extension SwiftFormatPlugin: XcodeBuildToolPlugin {
func createBuildCommands(context: XcodePluginContext, target: XcodeTarget) throws -> [Command] {
let tool = try context.tool(named: "swift-format")
let paths = target.inputFiles.map(\.url)
.filter { $0.pathExtension == "swift" }
.map{ $0.path(percentEncoded: false) }
return [
.prebuildCommand(
displayName: "Checking the format of Swift files in \(target.displayName)",
executable: tool.url,
arguments: ["lint", "--parallel", "--no-color-diagnostics"] + paths,
outputFilesDirectory: context.pluginWorkDirectoryURL
)
]
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment