From e0384be542135130a98ba2326306b19437538f84 Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 14:42:31 +0100 Subject: [PATCH] Add an executable target type A target with `type: executable` renders as `.executableTarget`, its imports resolved like any other target, and gets an `.executable` product instead of a `.library`. A command-line tool can now live in a generated package without a hand-written target in the header, which can't name a generated target: SwiftPM loads the manifest before the plugin runs. --- Plugins/PackageGenerator/AdvancedFeatures.swift | 2 +- Plugins/PackageGenerator/ConfigurationV2.swift | 3 ++- Plugins/PackageGenerator/PackageGeneratorV2.swift | 1 + Plugins/PackageGenerator/ParsedPackage.swift | 5 ++++- Plugins/PackageGenerator/ProductGeneration.swift | 6 +++++- Plugins/PackageGenerator/TargetRendering.swift | 4 ++-- README.md | 4 ++-- .../ProductGenerationTests.swift | 13 ++++++++++++- .../TargetRenderingTests.swift | 10 ++++++++++ 9 files changed, 39 insertions(+), 9 deletions(-) diff --git a/Plugins/PackageGenerator/AdvancedFeatures.swift b/Plugins/PackageGenerator/AdvancedFeatures.swift index 6042222..e07e0db 100644 --- a/Plugins/PackageGenerator/AdvancedFeatures.swift +++ b/Plugins/PackageGenerator/AdvancedFeatures.swift @@ -15,7 +15,7 @@ func generateExportedFiles( let packageDir = context.package.directoryURL - for target in targets where !target.isTest { + for target in targets where !target.isTest && !target.isExecutable { guard !target.dependencies.isEmpty else { continue } let exportedFileName = "exported.swift" diff --git a/Plugins/PackageGenerator/ConfigurationV2.swift b/Plugins/PackageGenerator/ConfigurationV2.swift index ba42293..9bf5354 100644 --- a/Plugins/PackageGenerator/ConfigurationV2.swift +++ b/Plugins/PackageGenerator/ConfigurationV2.swift @@ -116,10 +116,11 @@ struct ConfigurationV2: Codable { case regular case test case macro + case executable var defaultFolder: String { switch self { - case .regular, .macro: return "Sources" + case .regular, .macro, .executable: return "Sources" case .test: return "Tests" } } diff --git a/Plugins/PackageGenerator/PackageGeneratorV2.swift b/Plugins/PackageGenerator/PackageGeneratorV2.swift index 8b18ee6..58445c2 100644 --- a/Plugins/PackageGenerator/PackageGeneratorV2.swift +++ b/Plugins/PackageGenerator/PackageGeneratorV2.swift @@ -59,6 +59,7 @@ struct PackageGeneratorV2 { name: targetSpec.name, isTest: targetSpec.type == .test, isMacro: targetSpec.type == .macro, + isExecutable: targetSpec.type == .executable, dependencies: filtered, path: resolvedPath, fullPath: context.package.directoryURL.appendingPathComponent(resolvedPath).path, diff --git a/Plugins/PackageGenerator/ParsedPackage.swift b/Plugins/PackageGenerator/ParsedPackage.swift index f3d4def..6f3376a 100644 --- a/Plugins/PackageGenerator/ParsedPackage.swift +++ b/Plugins/PackageGenerator/ParsedPackage.swift @@ -4,6 +4,8 @@ public struct ParsedPackage: Codable, CustomStringConvertible { public var name: String public var isTest: Bool public var isMacro: Bool = false + /// An `.executableTarget` with an `.executable` product: set by the plugin from config; not from CLI JSON. + public var isExecutable: Bool = false public var dependencies: [String] public var path: String public var fullPath: String @@ -60,10 +62,11 @@ public struct ParsedPackage: Codable, CustomStringConvertible { return "[\(dependencies.count)|\(localDependencies)] \(name) \(hasResources == false ? "" : "/ hasResources")" } - public init(name: String, isTest: Bool, isMacro: Bool = false, dependencies: [String], path: String, fullPath: String, resources: String? = nil, localDependencies: Int = 0, hasBiggestNumberOfDependencies: Bool = false, exclude: [String] = [], parameters: [String]? = nil, additionalDependencies: [String]? = nil, libraryType: LibraryType? = nil, productName: String? = nil) { + public init(name: String, isTest: Bool, isMacro: Bool = false, isExecutable: Bool = false, dependencies: [String], path: String, fullPath: String, resources: String? = nil, localDependencies: Int = 0, hasBiggestNumberOfDependencies: Bool = false, exclude: [String] = [], parameters: [String]? = nil, additionalDependencies: [String]? = nil, libraryType: LibraryType? = nil, productName: String? = nil) { self.name = name self.isTest = isTest self.isMacro = isMacro + self.isExecutable = isExecutable self.dependencies = dependencies self.path = path self.fullPath = fullPath diff --git a/Plugins/PackageGenerator/ProductGeneration.swift b/Plugins/PackageGenerator/ProductGeneration.swift index 483ba5e..9748a7b 100644 --- a/Plugins/PackageGenerator/ProductGeneration.swift +++ b/Plugins/PackageGenerator/ProductGeneration.swift @@ -5,7 +5,7 @@ import Foundation // Kept free of `PackagePlugin` so the test target can compile this file directly. /// Generates the products `package.products.append(contentsOf: [...])` section. -/// Includes all non-test, non-macro targets sorted alphabetically. +/// Includes all non-test, non-macro targets sorted alphabetically: `.executable` for an executable target, `.library` for the rest. func generateProductsSection( parsedPackages: [ParsedPackage], config: ConfigurationV2 @@ -21,6 +21,10 @@ func generateProductsSection( // The product may be named differently from the target it wraps; `targets:` must // always reference the real target name. let productName = lib.productName ?? config.mappers.targets[lib.path, default: lib.name] + if lib.isExecutable { + lines.append("\(s1).executable(name: \"\(productName)\", targets: [\"\(lib.name)\"])") + continue + } let type = (lib.libraryType ?? config.libraryType).productArgument.map { "\($0), " } ?? "" lines.append("\(s1).library(name: \"\(productName)\", \(type)targets: [\"\(lib.name)\"])") } diff --git a/Plugins/PackageGenerator/TargetRendering.swift b/Plugins/PackageGenerator/TargetRendering.swift index 7e5d190..969a1f4 100644 --- a/Plugins/PackageGenerator/TargetRendering.swift +++ b/Plugins/PackageGenerator/TargetRendering.swift @@ -22,7 +22,7 @@ func pragmaMarkGroupName(_ path: String, fallback: String) -> String { return parts.first.map(String.init) ?? fallback } -/// Renders a single target as a `.target()`, `.testTarget()`, or `.macro()` block. +/// Renders a single target as a `.target()`, `.testTarget()`, `.executableTarget()` or `.macro()` block. /// Matches V1's `fakeTargetToSwiftCode` format exactly. /// /// Resolution priority per import: @@ -42,7 +42,7 @@ func renderSingleTarget( let s2 = String(repeating: " ", count: config.spaces * 2) let s3 = String(repeating: " ", count: config.spaces * 3) - let blockType = target.isMacro ? "macro" : (target.isTest ? "testTarget" : "target") + let blockType = target.isMacro ? "macro" : target.isExecutable ? "executableTarget" : (target.isTest ? "testTarget" : "target") // Build multi-line dependencies section using three-way resolution. var depsStr = "" diff --git a/README.md b/README.md index b6619bb..6ec215c 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,7 @@ packageDirectoryTargets: - path: Sources/Modules targets: - name: ModuleA - type: regular # regular, test, or macro + type: regular # regular, test, macro, or executable path: null # override computed path if needed exclude: ["__Snapshots__", "Mocks"] # exclude patterns parameters: # inline SPM target parameters @@ -112,7 +112,7 @@ packageDirectoryTargets: `additionalDependencies` injects strings verbatim into the target's `dependencies:` array, bypassing import analysis. Use it when a target needs a dependency that isn't imported in source (common with macros, plugins, or transitive requirements). Auto-resolved imports are emitted first (sorted), then `additionalDependencies` in declaration order. -`libraryType` sets the product linkage: `automatic` (default) omits `type:` and lets SwiftPM decide, `dynamic` and `static` emit `.library(name:, type: .dynamic/.static, targets:)`. Set it per target to override the top-level `libraryType`. Ignored for `test` and `macro` targets, which produce no product. +`libraryType` sets the product linkage: `automatic` (default) omits `type:` and lets SwiftPM decide, `dynamic` and `static` emit `.library(name:, type: .dynamic/.static, targets:)`. Set it per target to override the top-level `libraryType`. Ignored for `test` and `macro` targets, which produce no product, and for `executable` targets, which render as `.executableTarget` with an `.executable(name:targets:)` product (named by `productName` when set). `productName` names the generated product differently from the target it wraps, emitting `.library(name: "", targets: [""])`. It takes precedence over a `mappers.targets` entry for the same target. diff --git a/Tests/PackageGeneratorTests/ProductGenerationTests.swift b/Tests/PackageGeneratorTests/ProductGenerationTests.swift index 893a18c..ef2512a 100644 --- a/Tests/PackageGeneratorTests/ProductGenerationTests.swift +++ b/Tests/PackageGeneratorTests/ProductGenerationTests.swift @@ -12,6 +12,7 @@ private func lib( path: String? = nil, isTest: Bool = false, isMacro: Bool = false, + isExecutable: Bool = false, libraryType: LibraryType? = nil, productName: String? = nil ) -> ParsedPackage { @@ -19,6 +20,7 @@ private func lib( name: name, isTest: isTest, isMacro: isMacro, + isExecutable: isExecutable, dependencies: [], path: path ?? "Sources/\(name)", fullPath: "/tmp/\(name)", @@ -36,7 +38,7 @@ private func productLines( generateProductsSection(parsedPackages: packages, config: config) .split(separator: "\n") .map(String.init) - .filter { $0.contains(".library(") } + .filter { $0.contains(".library(") || $0.contains(".executable(") } .map { $0.trimmingCharacters(in: .whitespaces).trimmingCharacters(in: CharacterSet(charactersIn: ",")) } } @@ -66,6 +68,15 @@ struct ProductGenerationRegressionTests { #expect(productLines(packages) == [#".library(name: "Foo", targets: ["Foo"])"#]) } + @Test("An executable target produces an `.executable` product") + func executableTargetProducesAnExecutableProduct() { + let packages = [lib("tool", isExecutable: true, libraryType: .dynamic), lib("Core")] + #expect(productLines(packages) == [ + #".library(name: "Core", targets: ["Core"])"#, + #".executable(name: "tool", targets: ["tool"])"#, + ]) + } + @Test("No library targets yields an empty section") func emptySection() { let out = generateProductsSection(parsedPackages: [], config: ConfigurationV2()) diff --git a/Tests/PackageGeneratorTests/TargetRenderingTests.swift b/Tests/PackageGeneratorTests/TargetRenderingTests.swift index 4d5f3dd..ba08acd 100644 --- a/Tests/PackageGeneratorTests/TargetRenderingTests.swift +++ b/Tests/PackageGeneratorTests/TargetRenderingTests.swift @@ -9,6 +9,7 @@ private func target( path: String? = nil, isTest: Bool = false, isMacro: Bool = false, + isExecutable: Bool = false, dependencies: [String] = [], exclude: [String] = [], parameters: [String]? = nil, @@ -18,6 +19,7 @@ private func target( name: name, isTest: isTest, isMacro: isMacro, + isExecutable: isExecutable, dependencies: dependencies, path: path ?? "Sources/\(name)", fullPath: "/tmp/\(name)", @@ -113,6 +115,14 @@ struct TargetRenderingTests { """) } + @Test("An executable target renders as `.executableTarget` with its resolved imports") + func executableTarget() { + let (text, warnings) = render([target("tool", isExecutable: true, dependencies: ["Core"]), target("Core")]) + #expect(text.contains(" .executableTarget(\n name: \"tool\",\n dependencies: [\n \"Core\"\n ],")) + #expect(text.contains(#".executable(name: "tool", targets: ["tool"])"#)) + #expect(warnings.isEmpty) + } + @Test("An external product wins over an Apple SDK of the same name") func externalProductBeatsSDK() { let (text, warnings) = render(