From 3f9e2218c4b8a937039c1935165082116e0d1d26 Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 02:44:31 +0100 Subject: [PATCH 1/8] Extract the pure rendering and graph code from PackagePlugin Move renderSingleTarget, generateTargetsSection and the dependency graph metrics into PackagePlugin-free files that report warnings through a closure, and add renderPackageContent for the whole generated text. The tests now link them and cover the rendered file byte for byte. Output is unchanged. --- .github/copilot-instructions.md | 8 +- CODING_STANDARDS.md | 6 +- Package.resolved | 20 +-- .../PackageGenerator/AdvancedFeatures.swift | 71 -------- Plugins/PackageGenerator/CodeGeneration.swift | 158 +--------------- .../PackageGenerator/DependencyGraph.swift | 76 ++++++++ Plugins/PackageGenerator/ImportAnalysis.swift | 11 +- .../PackageGenerator/PackageGeneratorV2.swift | 2 +- .../PackageGenerator/TargetRendering.swift | 168 +++++++++++++++++ .../Shared/AppleSDKs.swift | 1 + .../Shared/DependencyGraph.swift | 1 + .../Shared/ImportAnalysis.swift | 1 + .../Shared/TargetRendering.swift | 1 + .../TargetRenderingTests.swift | 169 ++++++++++++++++++ 14 files changed, 439 insertions(+), 254 deletions(-) create mode 100644 Plugins/PackageGenerator/DependencyGraph.swift create mode 100644 Plugins/PackageGenerator/TargetRendering.swift create mode 120000 Tests/PackageGeneratorTests/Shared/AppleSDKs.swift create mode 120000 Tests/PackageGeneratorTests/Shared/DependencyGraph.swift create mode 120000 Tests/PackageGeneratorTests/Shared/ImportAnalysis.swift create mode 120000 Tests/PackageGeneratorTests/Shared/TargetRendering.swift create mode 100644 Tests/PackageGeneratorTests/TargetRenderingTests.swift diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 84c6baa..7786f59 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -44,8 +44,10 @@ diff Package.swift Package_generated.swift | Config load | `ConfigLoader.swift` | Finds `packageGenerator.{yaml,yml,json}`, converts YAML via `yaml-converter` subprocess, decodes into `ConfigurationV2` | | 2 — Discovery | `TargetResolution.swift` | `resolveTargetPaths` (shortest-path logic), `linkTestTargets` (strips "Tests" suffix), `discoverExternalDeps` (reads SPM graph), `runCLI` (invokes `package-generator-cli`) | | 3 — Import Analysis | `ImportAnalysis.swift` | `filterImports` — drops self-imports and explicit exclusions; Apple SDK filtering is intentionally **deferred** to render phase | -| 4 — Code Generation | `CodeGeneration.swift` | `renderSingleTarget`, `generateProductsSection`, `generateTargetsSection`, `writeOutput` | -| 5 — Advanced Features | `AdvancedFeatures.swift` | `generateExportedFiles`, `detectUnusedTargets`, `computeDependencyWeight` | +| 4 — Code Generation | `TargetRendering.swift`, `ProductGeneration.swift`, `CodeGeneration.swift` | pure `renderSingleTarget`, `generateTargetsSection`, `generateProductsSection`, `renderPackageContent`; `writeOutput` writes the file | +| 5 — Advanced Features | `AdvancedFeatures.swift`, `DependencyGraph.swift` | `generateExportedFiles`, `detectUnusedTargets`; pure `computeDependencyWeight`, `analyzeDependencyGraph` | + +Files with no `PackagePlugin` import are symlinked into `Tests/PackageGeneratorTests/Shared` (and `Benchmarks/Benchmarks/GeneratorBenchmarks/Shared`) so the tests and benchmarks compile them; they report warnings through a closure instead of `Diagnostics`. Entry point: `Plugin.swift` → `PackageGeneratorV2.generate(config:context:)` @@ -91,7 +93,7 @@ additionalDependencies: - '.product(name: "PreviewSnapshots", package: "swiftui-preview-snapshots")' ``` -### Dependency Resolution Priority (in `renderSingleTarget`) +### Dependency Resolution Priority (in `renderSingleTarget`, `TargetRendering.swift`) 1. `externalDeps` map → `.product(name:package:)` reference 2. `allLocalTargetNames` set → `"TargetName"` string literal 3. Apple SDK built-in list (`AppleSDKs.swift`) → silently skipped diff --git a/CODING_STANDARDS.md b/CODING_STANDARDS.md index 120ccb2..5af5070 100644 --- a/CODING_STANDARDS.md +++ b/CODING_STANDARDS.md @@ -7,10 +7,10 @@ Read during review. The mechanical part is enforced by the `Architecture/` packa - **One pipeline, top-level phase functions.** `Plugin.swift` loads the config and calls `PackageGeneratorV2.generate`, which runs the phases in order: discovery (`TargetResolution.swift`), import - filtering (`ImportAnalysis.swift`), rendering (`CodeGeneration.swift`, `ProductGeneration.swift`) and the optional - extras (`AdvancedFeatures.swift`). A phase is a free function at file scope, not a method on a new type. + filtering (`ImportAnalysis.swift`), rendering (`TargetRendering.swift`, `ProductGeneration.swift`, written by + `CodeGeneration.swift`) and the optional extras (`AdvancedFeatures.swift`, `DependencyGraph.swift`). A phase is a free function at file scope, not a method on a new type. - **Pure core, thin shell.** Code that turns a configuration and a list of `ParsedPackage` into text does not import - `PackagePlugin`: it takes values and returns values. Only + `PackagePlugin`: it takes values and returns values, and reports warnings through a closure the caller passes. Only the shell (config loading, path discovery, running `package-generator-cli`, writing files, `Diagnostics`) touches `PackagePlugin`, the file system or a process. - **The tests compile the real files.** A `.plugin` target cannot be imported, so `Tests/PackageGeneratorTests/Shared` diff --git a/Package.resolved b/Package.resolved index 3c5f9b7..ebb3e60 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,24 +1,6 @@ { - "originHash" : "26819863d48f9421393ae409005078e7d93732a7aee92f62128be1367f62fe9b", + "originHash" : "ea179dd2eb469ce0e0dc6830f3014cfef290e2a60486bf64b81ac7997c96f174", "pins" : [ - { - "identity" : "swift-argument-parser", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-argument-parser.git", - "state" : { - "revision" : "626b5b7b2f45e1b0b1c6f4a309296d1d21d7311b", - "version" : "1.7.1" - } - }, - { - "identity" : "swift-syntax", - "kind" : "remoteSourceControl", - "location" : "https://github.com/swiftlang/swift-syntax", - "state" : { - "revision" : "9de99a78f099e59caf2b2beec65a4c45d54b2081", - "version" : "603.0.1" - } - }, { "identity" : "yams", "kind" : "remoteSourceControl", diff --git a/Plugins/PackageGenerator/AdvancedFeatures.swift b/Plugins/PackageGenerator/AdvancedFeatures.swift index 0504c51..6042222 100644 --- a/Plugins/PackageGenerator/AdvancedFeatures.swift +++ b/Plugins/PackageGenerator/AdvancedFeatures.swift @@ -91,74 +91,3 @@ func detectUnusedTargets( } } } - -/// Computes dependency weights for each target. -/// Returns a dictionary with total and local dependency counts. -/// Marks the target with the highest number of local dependencies. -func computeDependencyWeight( - _ targets: [ParsedPackage] -) -> [String: (total: Int, local: Int, isHeaviest: Bool)] { - var weights: [String: (total: Int, local: Int, isHeaviest: Bool)] = [:] - - let localTargetNames = Set(targets.map { $0.name }) - var maxLocalDeps = 0 - var heaviestTarget: String? = nil - - // First pass: compute weights - for target in targets { - let totalDeps = target.dependencies.count - let localDeps = target.dependencies.filter { localTargetNames.contains($0) }.count - - weights[target.name] = (total: totalDeps, local: localDeps, isHeaviest: false) - - if localDeps > maxLocalDeps { - maxLocalDeps = localDeps - heaviestTarget = target.name - } - } - - // Second pass: mark heaviest - if let heaviest = heaviestTarget { - weights[heaviest]?.isHeaviest = true - } - - return weights -} - -/// Analyzes the dependency graph and provides architectural insights. -/// (Helper for understanding module coupling) -func analyzeDependencyGraph(_ targets: [ParsedPackage]) -> DependencyGraphAnalysis { - let localTargetNames = Set(targets.map { $0.name }) - - var analysis = DependencyGraphAnalysis() - - for target in targets { - let localDeps = target.dependencies.filter { localTargetNames.contains($0) } - - if localDeps.isEmpty && !target.isTest { - analysis.leafNodes.append(target.name) - } - - if target.dependencies.count > 5 { - analysis.heavyNodes.append((target.name, target.dependencies.count)) - } - - analysis.totalDependencies += target.dependencies.count - } - - return analysis -} - -// MARK: - Supporting Types - -struct DependencyGraphAnalysis { - var leafNodes: [String] = [] - var heavyNodes: [(String, Int)] = [] - var totalDependencies: Int = 0 - - var averageDependenciesPerTarget: Double { - guard !leafNodes.isEmpty || !heavyNodes.isEmpty else { return 0 } - let targetCount = leafNodes.count + heavyNodes.count - return targetCount > 0 ? Double(totalDependencies) / Double(targetCount) : 0 - } -} diff --git a/Plugins/PackageGenerator/CodeGeneration.swift b/Plugins/PackageGenerator/CodeGeneration.swift index 60a53c1..8943fab 100644 --- a/Plugins/PackageGenerator/CodeGeneration.swift +++ b/Plugins/PackageGenerator/CodeGeneration.swift @@ -19,142 +19,6 @@ func injectHeader( } } -/// Returns the pragma-mark group name for a target path. -/// Group name = second path component after Sources/ or Tests/. -func pragmaMarkGroupName(_ path: String, fallback: String) -> String { - let parts = path.split(separator: "/").map(String.init) - guard !parts.isEmpty else { return fallback } - - if parts.count >= 2, parts[0] == "Sources" || parts[0] == "Tests" { - return parts[1] - } - if let idx = parts.firstIndex(of: "Sources"), parts.count > idx + 1 { - return parts[idx + 1] - } - if let idx = parts.firstIndex(of: "Tests"), parts.count > idx + 1 { - return parts[idx + 1] - } - return parts.first ?? fallback -} - -/// Renders a single target as a `.target()`, `.testTarget()`, or `.macro()` block. -/// Matches V1's `fakeTargetToSwiftCode` format exactly. -/// -/// Resolution priority per import: -/// 1. In `externalDeps` → `.product(name:package:)` reference -/// 2. In `allLocalTargetNames` → `"TargetName"` string literal -/// 3. In Apple SDK built-in list → silently skipped -/// 4. Otherwise → warning emitted, dep skipped -func renderSingleTarget( - _ target: ParsedPackage, - config: ConfigurationV2, - externalDeps: [String: String], - allLocalTargetNames: Set, - leafWeights: [String: (total: Int, local: Int, isHeaviest: Bool)] -) -> String { - let s1 = String(repeating: " ", count: config.spaces) - 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 appleExclusions = Set(appleDefaultSDKs) - - // Build multi-line dependencies section using three-way resolution. - var depsStr = "" - let extraDeps = target.additionalDependencies ?? [] - if !target.dependencies.isEmpty || !extraDeps.isEmpty { - var resolvedLines: [String] = [] - for dep in target.dependencies { - if let extDep = externalDeps[dep] { - resolvedLines.append(extDep) - } else if allLocalTargetNames.contains(dep) { - resolvedLines.append("\"\(dep)\"") - } else if appleExclusions.contains(dep) { - // Known Apple SDK or user-excluded framework — skip silently. - } else { - Diagnostics.emit(.warning, "Dropped unresolved import '\(dep)'. If it's a system framework, ignore this.") - } - } - let allLines = resolvedLines.sorted().map { "\(s3)\($0)" } - + extraDeps.map { "\(s3)\($0)" } - if !allLines.isEmpty { - depsStr = "\n\(s2)dependencies: [\n" + allLines.joined(separator: ",\n") + "\n\(s2)]," - } - } - - // Leaf info comment (inline after name, before dependencies) - var leafComment = "" - if config.leafInfo, let w = leafWeights[target.name] { - let emoji = w.isHeaviest ? "|🚛" : "" - leafComment = "// [\(w.total)|\(w.local)\(emoji)]" - } - - // Extra parameters after path (verbatim from config's targetsParameters) - var extraParams = "" - - // Structured exclude list - let sortedExcludes = target.exclude.sorted() - if !sortedExcludes.isEmpty { - let excLines = sortedExcludes.map { "\(s3)\"\($0)\"" }.joined(separator: ",\n") - extraParams += ",\n\(s2)exclude: [\n\(excLines)\n\(s2)]" - } - - // Remaining parameters (resources:, swiftSettings:, etc.) rendered verbatim - for param in target.parameters ?? [] { - let trimmed = param.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { continue } - extraParams += ",\n\(s2)\(trimmed)" - } - - return "\(s1).\(blockType)(\n\(s2)name: \"\(target.name)\",\(leafComment)\(depsStr)\n\(s2)path: \"\(target.path)\"\(extraParams)\n\(s1))" -} - -/// Generates the targets `package.targets.append(contentsOf: [...])` section -/// with optional pragma-mark grouping. -func generateTargetsSection( - parsedPackages: [ParsedPackage], - config: ConfigurationV2, - externalDeps: [String: String], - leafWeights: [String: (total: Int, local: Int, isHeaviest: Bool)] -) -> String { - let sorted = parsedPackages.sorted { a, b in - let ag = pragmaMarkGroupName(a.path, fallback: a.name) - let bg = pragmaMarkGroupName(b.path, fallback: b.name) - if ag != bg { return ag < bg } - let ao = typeOrder(a) - let bo = typeOrder(b) - if ao != bo { return ao < bo } - return a.name < b.name - } - - let allLocalTargetNames = Set(parsedPackages.map { $0.name }) - - var output = "// MARK: - Products\npackage.targets.append(contentsOf: [\n" - var last = "" - var lastGroup = "" - - for target in sorted { - if !last.isEmpty { - output += last + ",\n" - } - if config.pragmaMark { - let group = pragmaMarkGroupName(target.path, fallback: target.name) - if group != lastGroup { - output += "// MARK: -\n" - output += "// MARK: \(group)\n" - lastGroup = group - } - } - last = renderSingleTarget(target, config: config, externalDeps: externalDeps, allLocalTargetNames: allLocalTargetNames, leafWeights: leafWeights) - } - - if !last.isEmpty { - output += last + "\n" - } - output += "])\n" - return output -} - /// Writes the complete generated output to Package.swift (or Package_generated.swift for dry runs). func writeOutput( _ headerContent: String, @@ -170,13 +34,13 @@ func writeOutput( let outputFile = packageDir.appendingPathComponent(outputName) let nonTestCount = parsedPackages.filter { !$0.isTest }.count - let productsSection = generateProductsSection(parsedPackages: parsedPackages, config: config) - let targetsSection = generateTargetsSection(parsedPackages: parsedPackages, config: config, externalDeps: externalDeps, leafWeights: leafWeights) - - let finalContent = headerContent - + (config.includePackageCountMark ? "// MARK: - Generated \(nonTestCount) packages\n\n" : "") - + productsSection - + targetsSection + let finalContent = headerContent + renderPackageContent( + parsedPackages, + config: config, + externalDeps: externalDeps, + leafWeights: leafWeights, + warn: { Diagnostics.emit(.warning, $0) } + ) do { try finalContent.write(to: outputFile, atomically: true, encoding: .utf8) @@ -190,11 +54,3 @@ func writeOutput( Diagnostics.emit(.error, "Failed to write output file: \(error)") } } - -// MARK: - Helpers - -private func typeOrder(_ target: ParsedPackage) -> Int { - if target.isTest { return 1 } - return 0 // regular and macro targets sort together alphabetically -} - diff --git a/Plugins/PackageGenerator/DependencyGraph.swift b/Plugins/PackageGenerator/DependencyGraph.swift new file mode 100644 index 0000000..3f81ab7 --- /dev/null +++ b/Plugins/PackageGenerator/DependencyGraph.swift @@ -0,0 +1,76 @@ +import Foundation + +// MARK: - Phase 5: Dependency graph metrics +// +// Kept free of `PackagePlugin` so the test target and the benchmarks can compile this file directly. + +/// Computes dependency weights for each target. +/// Returns a dictionary with total and local dependency counts. +/// Marks the target with the highest number of local dependencies. +func computeDependencyWeight( + _ targets: [ParsedPackage] +) -> [String: (total: Int, local: Int, isHeaviest: Bool)] { + var weights: [String: (total: Int, local: Int, isHeaviest: Bool)] = [:] + + let localTargetNames = Set(targets.map { $0.name }) + var maxLocalDeps = 0 + var heaviestTarget: String? = nil + + // First pass: compute weights + for target in targets { + let totalDeps = target.dependencies.count + let localDeps = target.dependencies.filter { localTargetNames.contains($0) }.count + + weights[target.name] = (total: totalDeps, local: localDeps, isHeaviest: false) + + if localDeps > maxLocalDeps { + maxLocalDeps = localDeps + heaviestTarget = target.name + } + } + + // Second pass: mark heaviest + if let heaviest = heaviestTarget { + weights[heaviest]?.isHeaviest = true + } + + return weights +} + +/// Analyzes the dependency graph and provides architectural insights. +/// (Helper for understanding module coupling) +func analyzeDependencyGraph(_ targets: [ParsedPackage]) -> DependencyGraphAnalysis { + let localTargetNames = Set(targets.map { $0.name }) + + var analysis = DependencyGraphAnalysis() + + for target in targets { + let localDeps = target.dependencies.filter { localTargetNames.contains($0) } + + if localDeps.isEmpty && !target.isTest { + analysis.leafNodes.append(target.name) + } + + if target.dependencies.count > 5 { + analysis.heavyNodes.append((target.name, target.dependencies.count)) + } + + analysis.totalDependencies += target.dependencies.count + } + + return analysis +} + +// MARK: - Supporting Types + +struct DependencyGraphAnalysis { + var leafNodes: [String] = [] + var heavyNodes: [(String, Int)] = [] + var totalDependencies: Int = 0 + + var averageDependenciesPerTarget: Double { + guard !leafNodes.isEmpty || !heavyNodes.isEmpty else { return 0 } + let targetCount = leafNodes.count + heavyNodes.count + return targetCount > 0 ? Double(totalDependencies) / Double(targetCount) : 0 + } +} diff --git a/Plugins/PackageGenerator/ImportAnalysis.swift b/Plugins/PackageGenerator/ImportAnalysis.swift index c3aef28..81bd0d0 100644 --- a/Plugins/PackageGenerator/ImportAnalysis.swift +++ b/Plugins/PackageGenerator/ImportAnalysis.swift @@ -1,5 +1,4 @@ import Foundation -import PackagePlugin // MARK: - Phase 3: Import Analysis @@ -8,12 +7,14 @@ import PackagePlugin /// Apple SDK filtering is deferred to the rendering phase so that external package /// products whose names collide with Apple SDK names (e.g. "Charts") are never /// silently discarded before we've had a chance to look them up in externalDeps. -/// Returns a sorted list for deterministic output. +/// Returns a sorted list for deterministic output. `remark` receives a message for each excluded import. +/// +/// Kept free of `PackagePlugin` so the test target and the benchmarks can compile this file directly. func filterImports( rawImports: [String], targetName: String, exclusions: ConfigurationV2.Exclusions, - verbose: Bool + remark: ((String) -> Void)? = nil ) -> [String] { let importExclusions = Set(exclusions.imports) var filtered: [String] = [] @@ -24,9 +25,7 @@ func filterImports( // Skip explicit import exclusions if importExclusions.contains(importName) { - if verbose { - Diagnostics.emit(.remark, "Skipped excluded import: \(importName)") - } + remark?("Skipped excluded import: \(importName)") continue } diff --git a/Plugins/PackageGenerator/PackageGeneratorV2.swift b/Plugins/PackageGenerator/PackageGeneratorV2.swift index aa5af66..8b18ee6 100644 --- a/Plugins/PackageGenerator/PackageGeneratorV2.swift +++ b/Plugins/PackageGenerator/PackageGeneratorV2.swift @@ -52,7 +52,7 @@ struct PackageGeneratorV2 { rawImports: rawImports, targetName: targetSpec.name, exclusions: config.exclusions, - verbose: config.verbosePlugin + remark: config.verbosePlugin ? { Diagnostics.emit(.remark, $0) } : nil ) let parsed = ParsedPackage( diff --git a/Plugins/PackageGenerator/TargetRendering.swift b/Plugins/PackageGenerator/TargetRendering.swift new file mode 100644 index 0000000..3ecfc3c --- /dev/null +++ b/Plugins/PackageGenerator/TargetRendering.swift @@ -0,0 +1,168 @@ +import Foundation + +// MARK: - Phase 4: Target rendering +// +// Kept free of `PackagePlugin` so the test target and the benchmarks can compile this file directly. + +/// Returns the pragma-mark group name for a target path. +/// Group name = second path component after Sources/ or Tests/. +func pragmaMarkGroupName(_ path: String, fallback: String) -> String { + let parts = path.split(separator: "/").map(String.init) + guard !parts.isEmpty else { return fallback } + + if parts.count >= 2, parts[0] == "Sources" || parts[0] == "Tests" { + return parts[1] + } + if let idx = parts.firstIndex(of: "Sources"), parts.count > idx + 1 { + return parts[idx + 1] + } + if let idx = parts.firstIndex(of: "Tests"), parts.count > idx + 1 { + return parts[idx + 1] + } + return parts.first ?? fallback +} + +/// Renders a single target as a `.target()`, `.testTarget()`, or `.macro()` block. +/// Matches V1's `fakeTargetToSwiftCode` format exactly. +/// +/// Resolution priority per import: +/// 1. In `externalDeps` → `.product(name:package:)` reference +/// 2. In `allLocalTargetNames` → `"TargetName"` string literal +/// 3. In Apple SDK built-in list → silently skipped +/// 4. Otherwise → warning emitted, dep skipped +func renderSingleTarget( + _ target: ParsedPackage, + config: ConfigurationV2, + externalDeps: [String: String], + allLocalTargetNames: Set, + leafWeights: [String: (total: Int, local: Int, isHeaviest: Bool)], + warn: (String) -> Void +) -> String { + let s1 = String(repeating: " ", count: config.spaces) + 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 appleExclusions = Set(appleDefaultSDKs) + + // Build multi-line dependencies section using three-way resolution. + var depsStr = "" + let extraDeps = target.additionalDependencies ?? [] + if !target.dependencies.isEmpty || !extraDeps.isEmpty { + var resolvedLines: [String] = [] + for dep in target.dependencies { + if let extDep = externalDeps[dep] { + resolvedLines.append(extDep) + } else if allLocalTargetNames.contains(dep) { + resolvedLines.append("\"\(dep)\"") + } else if appleExclusions.contains(dep) { + // Known Apple SDK or user-excluded framework — skip silently. + } else { + warn("Dropped unresolved import '\(dep)'. If it's a system framework, ignore this.") + } + } + let allLines = resolvedLines.sorted().map { "\(s3)\($0)" } + + extraDeps.map { "\(s3)\($0)" } + if !allLines.isEmpty { + depsStr = "\n\(s2)dependencies: [\n" + allLines.joined(separator: ",\n") + "\n\(s2)]," + } + } + + // Leaf info comment (inline after name, before dependencies) + var leafComment = "" + if config.leafInfo, let w = leafWeights[target.name] { + let emoji = w.isHeaviest ? "|🚛" : "" + leafComment = "// [\(w.total)|\(w.local)\(emoji)]" + } + + // Extra parameters after path (verbatim from config's targetsParameters) + var extraParams = "" + + // Structured exclude list + let sortedExcludes = target.exclude.sorted() + if !sortedExcludes.isEmpty { + let excLines = sortedExcludes.map { "\(s3)\"\($0)\"" }.joined(separator: ",\n") + extraParams += ",\n\(s2)exclude: [\n\(excLines)\n\(s2)]" + } + + // Remaining parameters (resources:, swiftSettings:, etc.) rendered verbatim + for param in target.parameters ?? [] { + let trimmed = param.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { continue } + extraParams += ",\n\(s2)\(trimmed)" + } + + return "\(s1).\(blockType)(\n\(s2)name: \"\(target.name)\",\(leafComment)\(depsStr)\n\(s2)path: \"\(target.path)\"\(extraParams)\n\(s1))" +} + +/// Generates the targets `package.targets.append(contentsOf: [...])` section +/// with optional pragma-mark grouping. +func generateTargetsSection( + parsedPackages: [ParsedPackage], + config: ConfigurationV2, + externalDeps: [String: String], + leafWeights: [String: (total: Int, local: Int, isHeaviest: Bool)], + warn: (String) -> Void +) -> String { + let sorted = parsedPackages.sorted { a, b in + let ag = pragmaMarkGroupName(a.path, fallback: a.name) + let bg = pragmaMarkGroupName(b.path, fallback: b.name) + if ag != bg { return ag < bg } + let ao = typeOrder(a) + let bo = typeOrder(b) + if ao != bo { return ao < bo } + return a.name < b.name + } + + let allLocalTargetNames = Set(parsedPackages.map { $0.name }) + + var output = "// MARK: - Products\npackage.targets.append(contentsOf: [\n" + var last = "" + var lastGroup = "" + + for target in sorted { + if !last.isEmpty { + output += last + ",\n" + } + if config.pragmaMark { + let group = pragmaMarkGroupName(target.path, fallback: target.name) + if group != lastGroup { + output += "// MARK: -\n" + output += "// MARK: \(group)\n" + lastGroup = group + } + } + last = renderSingleTarget(target, config: config, externalDeps: externalDeps, allLocalTargetNames: allLocalTargetNames, leafWeights: leafWeights, warn: warn) + } + + if !last.isEmpty { + output += last + "\n" + } + output += "])\n" + return output +} + +/// The generated file without its header: the optional package count mark, then the products and targets sections. +func renderPackageContent( + _ parsedPackages: [ParsedPackage], + config: ConfigurationV2, + externalDeps: [String: String], + leafWeights: [String: (total: Int, local: Int, isHeaviest: Bool)], + warn: (String) -> Void +) -> String { + let nonTestCount = parsedPackages.filter { !$0.isTest }.count + let productsSection = generateProductsSection(parsedPackages: parsedPackages, config: config) + let targetsSection = generateTargetsSection(parsedPackages: parsedPackages, config: config, externalDeps: externalDeps, leafWeights: leafWeights, warn: warn) + + return (config.includePackageCountMark ? "// MARK: - Generated \(nonTestCount) packages\n\n" : "") + + productsSection + + targetsSection +} + +// MARK: - Helpers + +private func typeOrder(_ target: ParsedPackage) -> Int { + if target.isTest { return 1 } + return 0 // regular and macro targets sort together alphabetically +} + diff --git a/Tests/PackageGeneratorTests/Shared/AppleSDKs.swift b/Tests/PackageGeneratorTests/Shared/AppleSDKs.swift new file mode 120000 index 0000000..495c947 --- /dev/null +++ b/Tests/PackageGeneratorTests/Shared/AppleSDKs.swift @@ -0,0 +1 @@ +../../../Plugins/PackageGenerator/AppleSDKs.swift \ No newline at end of file diff --git a/Tests/PackageGeneratorTests/Shared/DependencyGraph.swift b/Tests/PackageGeneratorTests/Shared/DependencyGraph.swift new file mode 120000 index 0000000..b9e49dc --- /dev/null +++ b/Tests/PackageGeneratorTests/Shared/DependencyGraph.swift @@ -0,0 +1 @@ +../../../Plugins/PackageGenerator/DependencyGraph.swift \ No newline at end of file diff --git a/Tests/PackageGeneratorTests/Shared/ImportAnalysis.swift b/Tests/PackageGeneratorTests/Shared/ImportAnalysis.swift new file mode 120000 index 0000000..5185b83 --- /dev/null +++ b/Tests/PackageGeneratorTests/Shared/ImportAnalysis.swift @@ -0,0 +1 @@ +../../../Plugins/PackageGenerator/ImportAnalysis.swift \ No newline at end of file diff --git a/Tests/PackageGeneratorTests/Shared/TargetRendering.swift b/Tests/PackageGeneratorTests/Shared/TargetRendering.swift new file mode 120000 index 0000000..dade111 --- /dev/null +++ b/Tests/PackageGeneratorTests/Shared/TargetRendering.swift @@ -0,0 +1 @@ +../../../Plugins/PackageGenerator/TargetRendering.swift \ No newline at end of file diff --git a/Tests/PackageGeneratorTests/TargetRenderingTests.swift b/Tests/PackageGeneratorTests/TargetRenderingTests.swift new file mode 100644 index 0000000..4d5f3dd --- /dev/null +++ b/Tests/PackageGeneratorTests/TargetRenderingTests.swift @@ -0,0 +1,169 @@ +import Foundation +import Testing + +// Rendering of the targets section and of the whole generated file. The sources are the plugin's own files, linked +// under `Shared/`. + +private func target( + _ name: String, + path: String? = nil, + isTest: Bool = false, + isMacro: Bool = false, + dependencies: [String] = [], + exclude: [String] = [], + parameters: [String]? = nil, + additionalDependencies: [String]? = nil +) -> ParsedPackage { + ParsedPackage( + name: name, + isTest: isTest, + isMacro: isMacro, + dependencies: dependencies, + path: path ?? "Sources/\(name)", + fullPath: "/tmp/\(name)", + exclude: exclude, + parameters: parameters, + additionalDependencies: additionalDependencies + ) +} + +private func render( + _ targets: [ParsedPackage], + config: ConfigurationV2 = ConfigurationV2(), + externalDeps: [String: String] = [:] +) -> (text: String, warnings: [String]) { + var warnings: [String] = [] + let text = renderPackageContent( + targets, + config: config, + externalDeps: externalDeps, + leafWeights: computeDependencyWeight(targets), + warn: { warnings.append($0) } + ) + return (text, warnings) +} + +@Suite("Target rendering") +struct TargetRenderingTests { + + @Test("A whole file renders byte for byte") + func wholeFile() { + // Given + let targets = [ + target("Feature", path: "Sources/Features/Feature", dependencies: ["Charts", "Core", "SwiftUI"], + exclude: ["b", "a"], parameters: [" resources: [.process(\"R\")] ", ""], + additionalDependencies: [#""Extra""#]), + target("Core", path: "Sources/Core/Core"), + target("CoreTests", path: "Tests/Core/CoreTests", isTest: true, dependencies: ["Core", "Nimble"]), + target("Macros", path: "Sources/Core/Macros", isMacro: true), + ] + let externalDeps = ["Charts": #".product(name: "Charts", package: "swift-charts")"#] + + // When + let (text, warnings) = render(targets, config: ConfigurationV2(pragmaMark: true), externalDeps: externalDeps) + + // Then + #expect(warnings == ["Dropped unresolved import 'Nimble'. If it's a system framework, ignore this."]) + #expect(text == """ + // MARK: - Generated 3 packages + + // MARK: - Targets + package.products.append(contentsOf: [ + .library(name: "Core", targets: ["Core"]), + .library(name: "Feature", targets: ["Feature"]) + ]) + + // MARK: - Products + package.targets.append(contentsOf: [ + // MARK: - + // MARK: Core + .target( + name: "Core", + path: "Sources/Core/Core" + ), + .macro( + name: "Macros", + path: "Sources/Core/Macros" + ), + .testTarget( + name: "CoreTests", + dependencies: [ + "Core" + ], + path: "Tests/Core/CoreTests" + ), + // MARK: - + // MARK: Features + .target( + name: "Feature", + dependencies: [ + "Core", + .product(name: "Charts", package: "swift-charts"), + "Extra" + ], + path: "Sources/Features/Feature", + exclude: [ + "a", + "b" + ], + resources: [.process("R")] + ) + ]) + + """) + } + + @Test("An external product wins over an Apple SDK of the same name") + func externalProductBeatsSDK() { + let (text, warnings) = render( + [target("App", dependencies: ["Charts"])], + externalDeps: ["Charts": #".product(name: "Charts", package: "swift-charts")"#]) + #expect(text.contains(#".product(name: "Charts", package: "swift-charts")"#)) + #expect(warnings.isEmpty) + } + + @Test("Apple SDKs are skipped silently and unknown imports are dropped with a warning") + func sdkAndUnknownImports() { + let (text, warnings) = render([target("App", dependencies: ["SwiftUI", "Unknown"])]) + #expect(!text.contains("dependencies:")) + #expect(warnings == ["Dropped unresolved import 'Unknown'. If it's a system framework, ignore this."]) + } + + @Test("Leaf info marks the target with the most local dependencies") + func leafInfo() { + let (text, _) = render( + [target("A"), target("B", dependencies: ["A"]), target("C", dependencies: ["A", "B", "SwiftUI"])], + config: ConfigurationV2(leafInfo: true)) + #expect(text.contains(#"name: "A",// [0|0]"#)) + #expect(text.contains(#"name: "B",// [1|1]"#)) + #expect(text.contains(#"name: "C",// [3|2|🚛]"#)) + } + + @Test("Indentation follows `spaces` and the package count mark can be omitted") + func spacesAndCountMark() { + let (text, _) = render([target("A")], config: ConfigurationV2(includePackageCountMark: false, spaces: 4)) + #expect(text.hasPrefix("// MARK: - Targets\n")) + #expect(text.contains(" .target(\n name: \"A\",")) + } + + @Test("Pragma mark group names come from the folder after Sources or Tests") + func groupNames() { + #expect(pragmaMarkGroupName("Sources/Core/Core", fallback: "x") == "Core") + #expect(pragmaMarkGroupName("Packages/App/Sources/Feature/Feature", fallback: "x") == "Feature") + #expect(pragmaMarkGroupName("Packages/App/Tests/FeatureTests", fallback: "x") == "FeatureTests") + #expect(pragmaMarkGroupName("Modules/Thing", fallback: "x") == "Modules") + #expect(pragmaMarkGroupName("", fallback: "x") == "x") + } + + @Test("filterImports drops self-imports and exclusions, keeps SDKs, and sorts") + func filtering() { + var remarks: [String] = [] + let filtered = filterImports( + rawImports: ["Zed", "App", "SwiftUI", "Hidden", "Core"], + targetName: "App", + exclusions: .init(imports: ["Hidden"]), + remark: { remarks.append($0) }) + #expect(filtered == ["Core", "SwiftUI", "Zed"]) + #expect(remarks == ["Skipped excluded import: Hidden"]) + } +} From 4d317c4017ef98e54dddd789bad4b0f37667d7c3 Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 02:51:21 +0100 Subject: [PATCH 2/8] Add package-benchmark benchmarks for the generator core A separate Benchmarks/ package links the plugin's PackagePlugin-free files and measures config decoding, import filtering, the dependency graph and rendering on a synthetic 1,000-target project. Includes the p50 and hotspots tools and scripts/profile.sh. CI builds the benchmarks. --- .github/workflows/ci.yml | 6 + .../ArchitectureTests/ArchitectureRules.swift | 2 +- .../Tests/ArchitectureTests/Rules.swift | 13 +- .../Tests/ArchitectureTests/Support.swift | 36 ++-- .../GeneratorBenchmarks.swift | 161 ++++++++++++++++++ .../Shared/AppleSDKs.swift | 1 + .../Shared/ConfigurationV2.swift | 1 + .../Shared/DependencyGraph.swift | 1 + .../Shared/ImportAnalysis.swift | 1 + .../Shared/ParsedPackage.swift | 1 + .../Shared/ProductGeneration.swift | 1 + .../Shared/TargetRendering.swift | 1 + Benchmarks/Package.resolved | 78 +++++++++ Benchmarks/Package.swift | 31 ++++ Benchmarks/Tools/Hotspots/main.swift | 89 ++++++++++ Benchmarks/Tools/P50/main.swift | 54 ++++++ Benchmarks/scripts/profile.sh | 23 +++ CODING_STANDARDS.md | 4 +- docs/architecture-rules.md | 6 +- 19 files changed, 482 insertions(+), 28 deletions(-) create mode 100644 Benchmarks/Benchmarks/GeneratorBenchmarks/GeneratorBenchmarks.swift create mode 120000 Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/AppleSDKs.swift create mode 120000 Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/ConfigurationV2.swift create mode 120000 Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/DependencyGraph.swift create mode 120000 Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/ImportAnalysis.swift create mode 120000 Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/ParsedPackage.swift create mode 120000 Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/ProductGeneration.swift create mode 120000 Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/TargetRendering.swift create mode 100644 Benchmarks/Package.resolved create mode 100644 Benchmarks/Package.swift create mode 100644 Benchmarks/Tools/Hotspots/main.swift create mode 100644 Benchmarks/Tools/P50/main.swift create mode 100755 Benchmarks/scripts/profile.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c81956b..0ed3aa1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,3 +30,9 @@ jobs: run: swift test - name: Architecture rules run: swift test --package-path Architecture + - name: Build benchmarks + # Built, not run: shared runners are too noisy to compare timings. jemalloc is off so the runner needs no + # Homebrew package; run them locally as docs/performance.md describes. + env: + BENCHMARK_DISABLE_JEMALLOC: "true" + run: swift build --package-path Benchmarks diff --git a/Architecture/Tests/ArchitectureTests/ArchitectureRules.swift b/Architecture/Tests/ArchitectureTests/ArchitectureRules.swift index db99704..c077363 100644 --- a/Architecture/Tests/ArchitectureTests/ArchitectureRules.swift +++ b/Architecture/Tests/ArchitectureTests/ArchitectureRules.swift @@ -9,7 +9,7 @@ struct ArchitectureRules { @Test func testSourcesLinkThePluginFiles() throws { let sources = try SharedSource.all(in: repository()) - #expect(sources.count >= 3) + #expect(sources.count >= 10) expectNone(Detect.unlinkedTestSources(sources), rule: .testSourcesLinkThePluginFiles) } diff --git a/Architecture/Tests/ArchitectureTests/Rules.swift b/Architecture/Tests/ArchitectureTests/Rules.swift index 59e25ef..9a01318 100644 --- a/Architecture/Tests/ArchitectureTests/Rules.swift +++ b/Architecture/Tests/ArchitectureTests/Rules.swift @@ -3,12 +3,13 @@ import LLMCheck extension Rule { static let testSourcesLinkThePluginFiles = Rule( id: "test-sources-link-the-plugin-files", - title: "Every Swift file in `Tests/PackageGeneratorTests/Shared` is a symbolic link into `Plugins/PackageGenerator`.", + title: "Every Swift file in the tests' and benchmarks' `Shared` folders is a symbolic link into `Plugins/PackageGenerator`.", category: .structure, rationale: """ - A `.plugin` target cannot be imported, so the test target compiles the plugin's own files through \ - symbolic links (CODING_STANDARDS.md, "The tests compile the real files"). A copy, or a link to anywhere \ - else, would let the tests pass against code the plugin no longer runs. + A `.plugin` target cannot be imported, so the test target and the benchmarks compile the plugin's own \ + files through symbolic links in `Tests/PackageGeneratorTests/Shared` and \ + `Benchmarks/Benchmarks/GeneratorBenchmarks/Shared` (CODING_STANDARDS.md, "The tests compile the real \ + files"). A copy, or a link to anywhere else, would test and measure code the plugin no longer runs. """, howToFix: """ Replace the file with a relative link: \ @@ -23,8 +24,8 @@ extension Rule { title: "A plugin file the tests link imports only Foundation.", category: .structure, rationale: """ - The generator's pure core (CODING_STANDARDS.md, "Pure core, thin shell") is compiled by the plugin and by \ - the test target, which cannot import `PackagePlugin`. Yams, the package's only dependency, belongs to \ + The generator's pure core (CODING_STANDARDS.md, "Pure core, thin shell") is compiled by the plugin, the \ + test target and the benchmarks; the last two cannot import `PackagePlugin`. Yams, the package's only dependency, belongs to \ `yaml-converter`, not the plugin. """, howToFix: """ diff --git a/Architecture/Tests/ArchitectureTests/Support.swift b/Architecture/Tests/ArchitectureTests/Support.swift index dc8240e..13ada31 100644 --- a/Architecture/Tests/ArchitectureTests/Support.swift +++ b/Architecture/Tests/ArchitectureTests/Support.swift @@ -5,10 +5,11 @@ import LLMCheck /// shared by all suites, which Swift Testing runs in parallel. func repository() throws -> Codebase { try Codebase() } -/// Where the test target compiles the plugin's pure files from. A `.plugin` target cannot be imported. -let sharedTestSourcesFolder = "Tests/PackageGeneratorTests/Shared" +/// Where the test target and the benchmarks compile the plugin's pure files from. A `.plugin` target cannot be +/// imported. +let sharedSourceFolders = ["Tests/PackageGeneratorTests/Shared", "Benchmarks/Benchmarks/GeneratorBenchmarks/Shared"] -/// A Swift file in `sharedTestSourcesFolder`, and where it points when it is a symbolic link. +/// A Swift file in one of `sharedSourceFolders`, and where it points when it is a symbolic link. struct SharedSource: Sendable { /// From the repository root, like `Tests/PackageGeneratorTests/Shared/ParsedPackage.swift`. let relativePath: String @@ -16,22 +17,25 @@ struct SharedSource: Sendable { /// when the file is a regular file. let destination: String? - /// The Swift files in `sharedTestSourcesFolder` of `codebase`, read from the file system: `Codebase` excludes the - /// folder so that the rules read each file once, under its real path. + /// The Swift files in `sharedSourceFolders` of `codebase`, read from the file system: `Codebase` excludes the + /// folders so that the rules read each file once, under its real path. static func all(in codebase: Codebase) throws -> [SharedSource] { let fileManager = FileManager.default - let folder = codebase.root.appendingPathComponent(sharedTestSourcesFolder) - return try fileManager.contentsOfDirectory(atPath: folder.path).sorted() - .filter { $0.hasSuffix(".swift") } - .map { name in - let link = folder.appendingPathComponent(name) - let target = try? fileManager.destinationOfSymbolicLink(atPath: link.path) - let destination = target.map { - URL(fileURLWithPath: $0, relativeTo: folder).standardizedFileURL.path - .replacingOccurrences(of: codebase.root.standardizedFileURL.path + "/", with: "") + let root = codebase.root.standardizedFileURL.path + "/" + return try sharedSourceFolders.flatMap { relativeFolder in + let folder = codebase.root.appendingPathComponent(relativeFolder) + return try fileManager.contentsOfDirectory(atPath: folder.path).sorted() + .filter { $0.hasSuffix(".swift") } + .map { name in + let link = folder.appendingPathComponent(name) + let target = try? fileManager.destinationOfSymbolicLink(atPath: link.path) + let destination = target.map { + URL(fileURLWithPath: $0, relativeTo: folder).standardizedFileURL.path + .replacingOccurrences(of: root, with: "") + } + return SharedSource(relativePath: "\(relativeFolder)/\(name)", destination: destination) } - return SharedSource(relativePath: "\(sharedTestSourcesFolder)/\(name)", destination: destination) - } + } } } diff --git a/Benchmarks/Benchmarks/GeneratorBenchmarks/GeneratorBenchmarks.swift b/Benchmarks/Benchmarks/GeneratorBenchmarks/GeneratorBenchmarks.swift new file mode 100644 index 0000000..841f7a8 --- /dev/null +++ b/Benchmarks/Benchmarks/GeneratorBenchmarks/GeneratorBenchmarks.swift @@ -0,0 +1,161 @@ +import Benchmark +import Foundation + +// The plugin's PackagePlugin-free files are compiled into this target through the links in `Shared/`. What they +// measure is the part of a run the plugin does itself; scanning sources for imports is package-generator-cli's work. + +/// A synthetic modular app: `groups` folders of `perGroup` library targets, each with a test target, so +/// `2 × groups × perGroup` targets. Imports mix local targets, external products, Apple SDKs and an unknown module, +/// like a real heavily modularized app. +struct SyntheticProject { + let config: ConfigurationV2 + /// The configuration as the plugin reads it from disk, with some parameters in the legacy `targetsParameters`. + let configJSON: Data + /// What package-generator-cli reports for each target: unsorted, with self-imports and an excluded import. + let rawImports: [(name: String, isTest: Bool, imports: [String])] + /// `ParsedPackage`s after `filterImports`, as `PackageGeneratorV2` builds them. + let packages: [ParsedPackage] + let externalDeps: [String: String] + + init(groups: Int = 25, perGroup: Int = 20) { + var random = SplitMix64(seed: 42) + let externalProducts = (0..<40).map { "Vendor\($0)" } + externalDeps = Dictionary( + uniqueKeysWithValues: externalProducts.enumerated().map { index, product in + (product, ".product(name: \"\(product)\", package: \"vendor-package-\(index % 12)\")") + }) + let sdks = ["Foundation", "SwiftUI", "UIKit", "Combine", "CoreData", "MapKit", "Charts", "OSLog", "os"] + let exclusions = ConfigurationV2.Exclusions(imports: ["LegacyAnalytics"], targets: []) + + var directoryGroups: [ConfigurationV2.DirectoryGroup] = [] + var rawImports: [(name: String, isTest: Bool, imports: [String])] = [] + var legacyParameters: [String: [String]] = [:] + var localNames: [String] = [] + + for group in 0..() + rawImports.append((name, false, imports.filter { seen.insert($0).inserted })) + rawImports.append((testName, true, [name, "XCTest", "Foundation", externalProducts[index % 40]])) + + specs.append( + .init( + name: name, + path: "Sources/Feature\(group)/\(name)", + exclude: index % 4 == 0 ? ["README.md", "__Snapshots__"] : nil, + parameters: index % 3 == 0 ? ["resources: [.process(\"Resources\")]"] : nil, + additionalDependencies: index % 5 == 0 + ? [".product(name: \"Dependencies\", package: \"swift-dependencies\")"] : nil)) + specs.append(.init(name: testName, type: .test, path: "Tests/Feature\(group)/\(testName)")) + if index % 2 == 0 { + legacyParameters[name] = ["swiftSettings: [.enableUpcomingFeature(\"ExistentialAny\")]"] + } + localNames.append(name) + } + directoryGroups.append(.init(path: "Sources/Feature\(group)", targets: specs)) + } + + config = ConfigurationV2( + pragmaMark: true, spaces: 2, leafInfo: true, unusedThreshold: 0, + packageDirectoryTargets: directoryGroups, + mappers: .init(imports: ["Vendor0": ".product(name: \"Vendor0\", package: \"vendor-zero\")"]), + exclusions: exclusions) + + var object = try! JSONSerialization.jsonObject(with: JSONEncoder().encode(config)) as! [String: Any] + object["targetsParameters"] = legacyParameters + configJSON = try! JSONSerialization.data(withJSONObject: object) + + self.rawImports = rawImports + let specs = Dictionary( + uniqueKeysWithValues: directoryGroups.flatMap(\.targets).map { ($0.name, $0) }) + packages = rawImports.map { entry in + let spec = specs[entry.name]! + return ParsedPackage( + name: entry.name, + isTest: entry.isTest, + dependencies: filterImports(rawImports: entry.imports, targetName: entry.name, exclusions: exclusions), + path: spec.path!, + fullPath: "/project/" + spec.path!, + exclude: spec.exclude ?? [], + parameters: spec.parameters, + additionalDependencies: spec.additionalDependencies) + } + } +} + +/// A seeded generator, so every run measures the same project. +struct SplitMix64: RandomNumberGenerator { + var state: UInt64 + init(seed: UInt64) { state = seed } + mutating func next() -> UInt64 { + state &+= 0x9E37_79B9_7F4A_7C15 + var z = state + z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9 + z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB + return z ^ (z >> 31) + } + mutating func next(below upperBound: Int) -> Int { Int(next() % UInt64(upperBound)) } +} + +let benchmarks: @Sendable () -> Void = { + Benchmark.defaultConfiguration = .init( + metrics: [.wallClock, .cpuTotal, .mallocCountTotal, .peakMemoryResident, .retainCount], + // Exact counts and microseconds, so a change of a few percent shows up in a comparison. + timeUnits: .microseconds, + units: [.mallocCountTotal: .count, .retainCount: .count], + maxDuration: .seconds(2), + maxIterations: 1_000 + ) + + let project = SyntheticProject() + let plain = ConfigurationV2(packageDirectoryTargets: project.config.packageDirectoryTargets) + + Benchmark("Decode config, 1,000 targets") { _ in + blackHole(try JSONDecoder().decode(ConfigurationV2.self, from: project.configJSON)) + } + + Benchmark("Filter imports, 1,000 targets") { _ in + for entry in project.rawImports { + blackHole( + filterImports( + rawImports: entry.imports, targetName: entry.name, exclusions: project.config.exclusions)) + } + } + + Benchmark("Dependency graph, 1,000 targets") { _ in + blackHole(computeDependencyWeight(project.packages)) + blackHole(analyzeDependencyGraph(project.packages)) + } + + Benchmark("Render products, 1,000 targets") { _ in + blackHole(generateProductsSection(parsedPackages: project.packages, config: project.config)) + } + + Benchmark("Render Package.swift, 1,000 targets") { _ in + let weights = computeDependencyWeight(project.packages) + var warnings = 0 + blackHole( + renderPackageContent( + project.packages, config: project.config, externalDeps: project.externalDeps, leafWeights: weights, + warn: { _ in warnings += 1 })) + blackHole(warnings) + } + + Benchmark("Render Package.swift, 1,000 targets, default settings") { _ in + var warnings = 0 + blackHole( + renderPackageContent( + project.packages, config: plain, externalDeps: project.externalDeps, leafWeights: [:], + warn: { _ in warnings += 1 })) + blackHole(warnings) + } +} diff --git a/Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/AppleSDKs.swift b/Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/AppleSDKs.swift new file mode 120000 index 0000000..674d08e --- /dev/null +++ b/Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/AppleSDKs.swift @@ -0,0 +1 @@ +../../../../Plugins/PackageGenerator/AppleSDKs.swift \ No newline at end of file diff --git a/Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/ConfigurationV2.swift b/Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/ConfigurationV2.swift new file mode 120000 index 0000000..1265093 --- /dev/null +++ b/Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/ConfigurationV2.swift @@ -0,0 +1 @@ +../../../../Plugins/PackageGenerator/ConfigurationV2.swift \ No newline at end of file diff --git a/Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/DependencyGraph.swift b/Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/DependencyGraph.swift new file mode 120000 index 0000000..4a31860 --- /dev/null +++ b/Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/DependencyGraph.swift @@ -0,0 +1 @@ +../../../../Plugins/PackageGenerator/DependencyGraph.swift \ No newline at end of file diff --git a/Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/ImportAnalysis.swift b/Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/ImportAnalysis.swift new file mode 120000 index 0000000..e902dec --- /dev/null +++ b/Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/ImportAnalysis.swift @@ -0,0 +1 @@ +../../../../Plugins/PackageGenerator/ImportAnalysis.swift \ No newline at end of file diff --git a/Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/ParsedPackage.swift b/Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/ParsedPackage.swift new file mode 120000 index 0000000..8ef22d6 --- /dev/null +++ b/Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/ParsedPackage.swift @@ -0,0 +1 @@ +../../../../Plugins/PackageGenerator/ParsedPackage.swift \ No newline at end of file diff --git a/Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/ProductGeneration.swift b/Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/ProductGeneration.swift new file mode 120000 index 0000000..17d8216 --- /dev/null +++ b/Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/ProductGeneration.swift @@ -0,0 +1 @@ +../../../../Plugins/PackageGenerator/ProductGeneration.swift \ No newline at end of file diff --git a/Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/TargetRendering.swift b/Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/TargetRendering.swift new file mode 120000 index 0000000..0baf774 --- /dev/null +++ b/Benchmarks/Benchmarks/GeneratorBenchmarks/Shared/TargetRendering.swift @@ -0,0 +1 @@ +../../../../Plugins/PackageGenerator/TargetRendering.swift \ No newline at end of file diff --git a/Benchmarks/Package.resolved b/Benchmarks/Package.resolved new file mode 100644 index 0000000..a96f1f3 --- /dev/null +++ b/Benchmarks/Package.resolved @@ -0,0 +1,78 @@ +{ + "originHash" : "bbb121f6c6eda0185c0b80898eda3df2fad6d0e0553c5481b39fe01b97f4cb14", + "pins" : [ + { + "identity" : "hdrhistogram-swift", + "kind" : "remoteSourceControl", + "location" : "https://github.com/HdrHistogram/hdrhistogram-swift.git", + "state" : { + "revision" : "c2e1210df04b4fff47e53f2f9dad9cc45ae15d63", + "version" : "0.2.0" + } + }, + { + "identity" : "malloc-interposer", + "kind" : "remoteSourceControl", + "location" : "https://github.com/ordo-one/malloc-interposer.git", + "state" : { + "revision" : "977dc0639b742ecd05ac03fecc53664095821a5d", + "version" : "1.6.1" + } + }, + { + "identity" : "package-benchmark", + "kind" : "remoteSourceControl", + "location" : "https://github.com/ordo-one/package-benchmark.git", + "state" : { + "revision" : "ca4a9d300fc15d38132853c2e30462337b33c43f", + "version" : "1.38.1" + } + }, + { + "identity" : "swift-argument-parser", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-argument-parser.git", + "state" : { + "revision" : "6a52f3251125d74daf04fcbd5e6f08a75d074382", + "version" : "1.8.2" + } + }, + { + "identity" : "swift-atomics", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-atomics.git", + "state" : { + "revision" : "0442cb5a3f98ab802acb777929fdb446bda11a34", + "version" : "1.3.1" + } + }, + { + "identity" : "swift-numerics", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-numerics", + "state" : { + "revision" : "0c0290ff6b24942dadb83a929ffaaa1481df04a2", + "version" : "1.1.1" + } + }, + { + "identity" : "swift-system", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-system.git", + "state" : { + "revision" : "640e5755b5826f4437eaeedd366fd776737db62c", + "version" : "1.9.0" + } + }, + { + "identity" : "texttable", + "kind" : "remoteSourceControl", + "location" : "https://github.com/ordo-one/TextTable.git", + "state" : { + "revision" : "a27a07300cf4ae322e0079ca0a475c5583dd575f", + "version" : "0.0.2" + } + } + ], + "version" : 3 +} diff --git a/Benchmarks/Package.swift b/Benchmarks/Package.swift new file mode 100644 index 0000000..ffb51c7 --- /dev/null +++ b/Benchmarks/Package.swift @@ -0,0 +1,31 @@ +// swift-tools-version: 6.1 +import PackageDescription + +// PackageGeneratorPlugin's benchmarks, on ordo-one/package-benchmark (https://www.swift.org/blog/benchmarks/). +// A separate package so the plugin's dependencies stay Yams alone. A `.plugin` target cannot be imported, so +// `GeneratorBenchmarks/Shared` links the plugin's PackagePlugin-free files, like the test target does. +// Run from the repository root: `swift package --package-path Benchmarks benchmark`. +let package = Package( + name: "Benchmarks", + platforms: [.macOS(.v15)], + dependencies: [ + .package(url: "https://github.com/ordo-one/package-benchmark.git", from: "1.38.0") + ], + targets: [ + .executableTarget( + name: "GeneratorBenchmarks", + dependencies: [ + .product(name: "Benchmark", package: "package-benchmark") + ], + path: "Benchmarks/GeneratorBenchmarks", + swiftSettings: [.swiftLanguageMode(.v6)], + plugins: [ + .plugin(name: "BenchmarkPlugin", package: "package-benchmark") + ] + ), + // Reads two `benchmark --format markdown` outputs and prints each benchmark's p50 before and after. + .executableTarget(name: "p50", path: "Tools/P50"), + // Reads an exported Time Profiler table and prints the hottest functions (scripts/profile.sh). + .executableTarget(name: "hotspots", path: "Tools/Hotspots"), + ] +) diff --git a/Benchmarks/Tools/Hotspots/main.swift b/Benchmarks/Tools/Hotspots/main.swift new file mode 100644 index 0000000..55ba7c0 --- /dev/null +++ b/Benchmarks/Tools/Hotspots/main.swift @@ -0,0 +1,89 @@ +import Foundation + +// Usage: swift run --package-path Benchmarks hotspots profile.xml [count] +// profile.xml is `xcrun xctrace export --xpath '…/table[@schema="time-profile"]'` (scripts/profile.sh writes it). +// Prints the functions with the most samples of their own (self) and the generator functions with the most samples +// under them (inclusive). package-benchmark's ARC counting hooks are left out: they exist only while measuring. + +/// Reads the rows of an exported time-profile table. Frames and backtraces are written once and then referenced +/// by id, so both are remembered. +final class ProfileReader: NSObject, XMLParserDelegate { + var frameNames: [String: String] = [:] + var backtraces: [String: [String]] = [:] + var samples: [[String]] = [] + private var current: [String]? + private var currentID: String? + + func parser( + _ parser: XMLParser, didStartElement element: String, namespaceURI: String?, qualifiedName: String?, + attributes: [String: String] = [:] + ) { + switch element { + case "tagged-backtrace", "backtrace": + if let ref = attributes["ref"] { + samples.append(backtraces[ref] ?? []) + } else { + current = [] + currentID = attributes["id"] + } + case "frame" where current != nil: + if let ref = attributes["ref"] { + current?.append(frameNames[ref] ?? "?") + } else { + let name = attributes["name"] ?? "?" + if let id = attributes["id"] { frameNames[id] = name } + current?.append(name) + } + default: + break + } + } + + func parser(_ parser: XMLParser, didEndElement element: String, namespaceURI: String?, qualifiedName: String?) { + guard element == "tagged-backtrace" || element == "backtrace", let frames = current else { return } + if let currentID { backtraces[currentID] = frames } + samples.append(frames) + current = nil + currentID = nil + } +} + +let arguments = CommandLine.arguments +guard arguments.count >= 2, let parser = XMLParser(contentsOf: URL(fileURLWithPath: arguments[1])) else { + print("usage: hotspots [count]") + exit(2) +} +let count = arguments.count > 2 ? Int(arguments[2]) ?? 20 : 20 +let reader = ProfileReader() +parser.delegate = reader +guard parser.parse() else { + print("could not read \(arguments[1]): \(parser.parserError.map { "\($0)" } ?? "unknown error")") + exit(1) +} + +/// The generator's own functions and types: the plugin files the benchmarks compile. +let generator = + /GeneratorBenchmarks|ConfigurationV2|ParsedPackage|render[A-Z]|generate[A-Z]|filterImports|pragmaMarkGroupName|computeDependencyWeight|analyzeDependencyGraph|typeOrder/ +let measuring = /ARCStatsProducer|_swift_(retain|release)_(adapter|hook)|MallocInterposer/ +func short(_ name: String) -> String { String(name.prefix { $0 != "(" }.suffix(110)) } + +var selfSamples: [String: Int] = [:] +var inclusiveSamples: [String: Int] = [:] +var total = 0 +for frames in reader.samples where !frames.isEmpty { + guard !frames.contains(where: { $0.contains(measuring) }) else { continue } + total += 1 + selfSamples[short(frames[0]), default: 0] += 1 + for name in Set(frames.map(short)) where name.contains(generator) { + inclusiveSamples[name, default: 0] += 1 + } +} +func report(_ title: String, _ counts: [String: Int], of total: Int) { + print(title) + for (name, samples) in counts.sorted(by: { $0.value > $1.value }).prefix(count) { + print(String(format: "%5.1f%% ", 100 * Double(samples) / Double(max(total, 1))) + name) + } +} +print("\(total) samples") +report("Self", selfSamples, of: total) +report("Inclusive (generator functions)", inclusiveSamples, of: total) diff --git a/Benchmarks/Tools/P50/main.swift b/Benchmarks/Tools/P50/main.swift new file mode 100644 index 0000000..7e89788 --- /dev/null +++ b/Benchmarks/Tools/P50/main.swift @@ -0,0 +1,54 @@ +import Foundation + +// Usage: swift run --package-path Benchmarks p50 before.md after.md +// Each file is the output of `swift package --package-path Benchmarks benchmark --format markdown --no-progress`. + +/// A benchmark's p50 wall clock in microseconds and p50 malloc count. +struct Medians { + var wallClock: Double? + var mallocs: Double? +} + +func medians(inFile path: String) throws -> [(name: String, medians: Medians)] { + let text = try String(contentsOfFile: path, encoding: .utf8) + // A row: | Time (wall clock) (μs) * | p0 | p25 | p50 | … The unit is absent for plain counts. + let row = + /^\|\s*(Malloc \(total\)|Time \(wall clock\))\s*(?:\(([^)]*)\))?\s*\*?\s*\|\s*[\d,]+\s*\|\s*[\d,]+\s*\|\s*([\d,]+)/ + let scale: [String: Double] = ["ns": 1e-3, "μs": 1, "us": 1, "ms": 1e3, "s": 1e6, "K": 1e3, "M": 1e6] + var result: [(name: String, medians: Medians)] = [] + for line in text.split(separator: "\n") { + if line.hasPrefix("### ") { + let name = line.dropFirst(4).replacingOccurrences(of: " metrics", with: "") + result.append((name, Medians())) + } else if let match = line.firstMatch(of: row), !result.isEmpty { + let value = + Double(match.3.replacingOccurrences(of: ",", with: ""))! * (match.2.map { scale[String($0)] ?? 1 } ?? 1) + if match.1 == "Malloc (total)" { + result[result.count - 1].medians.mallocs = result[result.count - 1].medians.mallocs ?? value + } else { + result[result.count - 1].medians.wallClock = result[result.count - 1].medians.wallClock ?? value + } + } + } + return result +} + +let arguments = CommandLine.arguments +guard arguments.count == 3 else { + print("usage: p50 ") + exit(2) +} +let before = Dictionary( + try medians(inFile: arguments[1]).map { ($0.name, $0.medians) }, uniquingKeysWith: { a, _ in a }) +func cell(_ old: Double?, _ new: Double?, _ format: String) -> String { + guard let new else { return "" } + guard let old else { return String(format: format, new) } + return String(format: "\(format) → \(format) (%.2fx)", old, new, new / old) +} +print("| Benchmark | Wall clock p50 (µs) | Mallocs p50 |") +print("|---|---|---|") +for (name, after) in try medians(inFile: arguments[2]) { + let old = before[name] + print( + "| \(name) | \(cell(old?.wallClock, after.wallClock, "%.1f")) | \(cell(old?.mallocs, after.mallocs, "%.0f")) |") +} diff --git a/Benchmarks/scripts/profile.sh b/Benchmarks/scripts/profile.sh new file mode 100755 index 0000000..a17fc9c --- /dev/null +++ b/Benchmarks/scripts/profile.sh @@ -0,0 +1,23 @@ +#!/bin/sh +# Profiles one benchmark with Instruments' Time Profiler and prints its hottest functions. +# Usage, from the repository root: Benchmarks/scripts/profile.sh 'Render Package.swift, 1,000 targets' [count] +# The name is the benchmark's, matched exactly. The trace is kept in Benchmarks/.build/profiles to open in Instruments. +set -eu + +name=$1 +count=${2:-20} +package=$(cd "$(dirname "$0")/.." && pwd) +swift build --package-path "$package" -c release --product GeneratorBenchmarks +swift build --package-path "$package" -c release --product hotspots +bin=$(swift build --package-path "$package" -c release --show-bin-path) + +out="$package/.build/profiles" +mkdir -p "$out" +trace="$out/$(echo "$name" | tr -c 'A-Za-z0-9' '-').trace" +rm -rf "$trace" +# Instruments symbolicates only a binary launched by its absolute path. +xcrun xctrace record --quiet --template 'Time Profiler' --output "$trace" --launch -- \ + "$bin/GeneratorBenchmarks" --filter "^$name\$" +xcrun xctrace export --input "$trace" \ + --xpath '/trace-toc/run[@number="1"]/data/table[@schema="time-profile"]' > "$trace.xml" +"$bin/hotspots" "$trace.xml" "$count" diff --git a/CODING_STANDARDS.md b/CODING_STANDARDS.md index 5af5070..8b01a9a 100644 --- a/CODING_STANDARDS.md +++ b/CODING_STANDARDS.md @@ -14,8 +14,8 @@ Read during review. The mechanical part is enforced by the `Architecture/` packa the shell (config loading, path discovery, running `package-generator-cli`, writing files, `Diagnostics`) touches `PackagePlugin`, the file system or a process. - **The tests compile the real files.** A `.plugin` target cannot be imported, so `Tests/PackageGeneratorTests/Shared` - holds symbolic links to the pure files in `Plugins/PackageGenerator`, never copies. A file that gains a - `PackagePlugin` import can no longer be linked there. + and `Benchmarks/Benchmarks/GeneratorBenchmarks/Shared` hold symbolic links to the pure files in + `Plugins/PackageGenerator`, never copies. A file that gains a `PackagePlugin` import can no longer be linked there. - **Swift 6 language mode.** All code compiles under strict concurrency (`swiftLanguageModes: [.v6]`). ## Behaviour that users rely on diff --git a/docs/architecture-rules.md b/docs/architecture-rules.md index 7d425c6..89600f6 100644 --- a/docs/architecture-rules.md +++ b/docs/architecture-rules.md @@ -6,9 +6,9 @@ The mechanical part of `CODING_STANDARDS.md`, enforced by the `Architecture/` pa The pure core and the plugin shell. Read before you add an `import` or a file to `Plugins`. -### Every Swift file in `Tests/PackageGeneratorTests/Shared` is a symbolic link into `Plugins/PackageGenerator`. +### Every Swift file in the tests' and benchmarks' `Shared` folders is a symbolic link into `Plugins/PackageGenerator`. -`test-sources-link-the-plugin-files`: A `.plugin` target cannot be imported, so the test target compiles the plugin's own files through symbolic links (CODING_STANDARDS.md, "The tests compile the real files"). A copy, or a link to anywhere else, would let the tests pass against code the plugin no longer runs. +`test-sources-link-the-plugin-files`: A `.plugin` target cannot be imported, so the test target and the benchmarks compile the plugin's own files through symbolic links in `Tests/PackageGeneratorTests/Shared` and `Benchmarks/Benchmarks/GeneratorBenchmarks/Shared` (CODING_STANDARDS.md, "The tests compile the real files"). A copy, or a link to anywhere else, would test and measure code the plugin no longer runs. **How to fix:** Replace the file with a relative link: `ln -s ../../../Plugins/PackageGenerator/Name.swift Tests/PackageGeneratorTests/Shared/Name.swift`. @@ -26,7 +26,7 @@ Shared/ParsedPackage.swift -> ../../../Plugins/PackageGenerator/ParsedPackage.sw ### A plugin file the tests link imports only Foundation. -`core-files-import-only-foundation`: The generator's pure core (CODING_STANDARDS.md, "Pure core, thin shell") is compiled by the plugin and by the test target, which cannot import `PackagePlugin`. Yams, the package's only dependency, belongs to `yaml-converter`, not the plugin. +`core-files-import-only-foundation`: The generator's pure core (CODING_STANDARDS.md, "Pure core, thin shell") is compiled by the plugin, the test target and the benchmarks; the last two cannot import `PackagePlugin`. Yams, the package's only dependency, belongs to `yaml-converter`, not the plugin. **How to fix:** Keep `PackagePlugin` in the shell: take the value the core needs as a parameter, and report warnings through a closure the caller passes (it calls `Diagnostics.emit`). From 890a70204e5e9a5e02b727356191c8f7bb8277f8 Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 03:06:34 +0100 Subject: [PATCH 3/8] Render Package.swift 5x faster with 4x fewer allocations Compute each target's pragma-mark group once instead of in the sort comparator, build the Apple SDK set once instead of per target, and count local dependencies without building arrays. Output is byte for byte the same. Document the benchmarks and results in docs/performance.md. --- .../Tests/ArchitectureTests/Detect.swift | 4 +- .../ArchitectureTests/DetectorTests.swift | 6 +- .../Tests/ArchitectureTests/Rules.swift | 4 +- Plugins/PackageGenerator/AppleSDKs.swift | 3 + .../PackageGenerator/DependencyGraph.swift | 6 +- .../PackageGenerator/TargetRendering.swift | 41 ++++----- docs/architecture-rules.md | 4 +- docs/performance.md | 88 +++++++++++++++++++ 8 files changed, 124 insertions(+), 32 deletions(-) create mode 100644 docs/performance.md diff --git a/Architecture/Tests/ArchitectureTests/Detect.swift b/Architecture/Tests/ArchitectureTests/Detect.swift index 008b3e3..9933169 100644 --- a/Architecture/Tests/ArchitectureTests/Detect.swift +++ b/Architecture/Tests/ArchitectureTests/Detect.swift @@ -44,9 +44,9 @@ enum Detect { return directories + toolPaths } - /// `appleDefaultSDKs` referenced inside a function named `filterImports`. + /// `appleDefaultSDKs` or `appleDefaultSDKSet` referenced inside a function named `filterImports`. static func earlySDKFiltering(in scope: Scope) -> [Match] { - scope.references(to: "appleDefaultSDKs").filter { match in + scope.references(to: "appleDefaultSDKs", "appleDefaultSDKSet").filter { match in sequence(first: match.node, next: \.parent).contains { $0.as(FunctionDeclSyntax.self)?.name.text == "filterImports" } diff --git a/Architecture/Tests/ArchitectureTests/DetectorTests.swift b/Architecture/Tests/ArchitectureTests/DetectorTests.swift index 655c556..179771e 100644 --- a/Architecture/Tests/ArchitectureTests/DetectorTests.swift +++ b/Architecture/Tests/ArchitectureTests/DetectorTests.swift @@ -72,13 +72,13 @@ import Testing in: scope( """ func filterImports(rawImports: [String]) -> [String] { - rawImports.filter { !appleDefaultSDKs.contains($0) } + rawImports.filter { !appleDefaultSDKs.contains($0) && !appleDefaultSDKSet.contains($0) } } func renderSingleTarget() { - let appleExclusions = Set(appleDefaultSDKs) + let skipped = appleDefaultSDKSet.contains(dep) } """)) - #expect(found.map(\.location.line) == [2]) + #expect(found.map(\.location.line) == [2, 2]) } @Test func xcTestImportsAreFound() { diff --git a/Architecture/Tests/ArchitectureTests/Rules.swift b/Architecture/Tests/ArchitectureTests/Rules.swift index 9a01318..e2fe09f 100644 --- a/Architecture/Tests/ArchitectureTests/Rules.swift +++ b/Architecture/Tests/ArchitectureTests/Rules.swift @@ -77,7 +77,7 @@ extension Rule { static let appleSDKFilteringIsDeferred = Rule( id: "apple-sdk-filtering-is-deferred", - title: "`filterImports` does not consult `appleDefaultSDKs`.", + title: "`filterImports` does not consult `appleDefaultSDKs` or `appleDefaultSDKSet`.", category: .output, rationale: """ Imports are matched to external products and local targets before Apple SDKs are skipped. Filtering SDK \ @@ -93,7 +93,7 @@ extension Rule { rawImports.filter { !appleDefaultSDKs.contains($0) } """, goodExample: """ - } else if appleSDKs.contains(dep) { + } else if appleDefaultSDKSet.contains(dep) { // Known Apple SDK: skip silently, after externalDeps and local targets were checked. """ ) diff --git a/Plugins/PackageGenerator/AppleSDKs.swift b/Plugins/PackageGenerator/AppleSDKs.swift index 9cf9dd6..da75c1c 100644 --- a/Plugins/PackageGenerator/AppleSDKs.swift +++ b/Plugins/PackageGenerator/AppleSDKs.swift @@ -274,3 +274,6 @@ let appleDefaultSDKs = [ "os", "simd" ] + +/// `appleDefaultSDKs` as a set, built once: rendering looks every unresolved import up in it. +let appleDefaultSDKSet = Set(appleDefaultSDKs) diff --git a/Plugins/PackageGenerator/DependencyGraph.swift b/Plugins/PackageGenerator/DependencyGraph.swift index 3f81ab7..8b243a6 100644 --- a/Plugins/PackageGenerator/DependencyGraph.swift +++ b/Plugins/PackageGenerator/DependencyGraph.swift @@ -19,7 +19,7 @@ func computeDependencyWeight( // First pass: compute weights for target in targets { let totalDeps = target.dependencies.count - let localDeps = target.dependencies.filter { localTargetNames.contains($0) }.count + let localDeps = target.dependencies.count(where: localTargetNames.contains) weights[target.name] = (total: totalDeps, local: localDeps, isHeaviest: false) @@ -45,9 +45,9 @@ func analyzeDependencyGraph(_ targets: [ParsedPackage]) -> DependencyGraphAnalys var analysis = DependencyGraphAnalysis() for target in targets { - let localDeps = target.dependencies.filter { localTargetNames.contains($0) } + let hasLocalDeps = target.dependencies.contains(where: localTargetNames.contains) - if localDeps.isEmpty && !target.isTest { + if !hasLocalDeps && !target.isTest { analysis.leafNodes.append(target.name) } diff --git a/Plugins/PackageGenerator/TargetRendering.swift b/Plugins/PackageGenerator/TargetRendering.swift index 3ecfc3c..7e5d190 100644 --- a/Plugins/PackageGenerator/TargetRendering.swift +++ b/Plugins/PackageGenerator/TargetRendering.swift @@ -7,19 +7,19 @@ import Foundation /// Returns the pragma-mark group name for a target path. /// Group name = second path component after Sources/ or Tests/. func pragmaMarkGroupName(_ path: String, fallback: String) -> String { - let parts = path.split(separator: "/").map(String.init) + let parts = path.split(separator: "/") guard !parts.isEmpty else { return fallback } if parts.count >= 2, parts[0] == "Sources" || parts[0] == "Tests" { - return parts[1] + return String(parts[1]) } if let idx = parts.firstIndex(of: "Sources"), parts.count > idx + 1 { - return parts[idx + 1] + return String(parts[idx + 1]) } if let idx = parts.firstIndex(of: "Tests"), parts.count > idx + 1 { - return parts[idx + 1] + return String(parts[idx + 1]) } - return parts.first ?? fallback + return parts.first.map(String.init) ?? fallback } /// Renders a single target as a `.target()`, `.testTarget()`, or `.macro()` block. @@ -43,7 +43,6 @@ func renderSingleTarget( let s3 = String(repeating: " ", count: config.spaces * 3) let blockType = target.isMacro ? "macro" : (target.isTest ? "testTarget" : "target") - let appleExclusions = Set(appleDefaultSDKs) // Build multi-line dependencies section using three-way resolution. var depsStr = "" @@ -55,7 +54,7 @@ func renderSingleTarget( resolvedLines.append(extDep) } else if allLocalTargetNames.contains(dep) { resolvedLines.append("\"\(dep)\"") - } else if appleExclusions.contains(dep) { + } else if appleDefaultSDKSet.contains(dep) { // Known Apple SDK or user-excluded framework — skip silently. } else { warn("Dropped unresolved import '\(dep)'. If it's a system framework, ignore this.") @@ -104,15 +103,16 @@ func generateTargetsSection( leafWeights: [String: (total: Int, local: Int, isHeaviest: Bool)], warn: (String) -> Void ) -> String { - let sorted = parsedPackages.sorted { a, b in - let ag = pragmaMarkGroupName(a.path, fallback: a.name) - let bg = pragmaMarkGroupName(b.path, fallback: b.name) - if ag != bg { return ag < bg } - let ao = typeOrder(a) - let bo = typeOrder(b) - if ao != bo { return ao < bo } - return a.name < b.name - } + // Each target's group name is computed once, not on every comparison of the sort. + let sorted = parsedPackages + .map { (group: pragmaMarkGroupName($0.path, fallback: $0.name), target: $0) } + .sorted { a, b in + if a.group != b.group { return a.group < b.group } + let ao = typeOrder(a.target) + let bo = typeOrder(b.target) + if ao != bo { return ao < bo } + return a.target.name < b.target.name + } let allLocalTargetNames = Set(parsedPackages.map { $0.name }) @@ -120,12 +120,12 @@ func generateTargetsSection( var last = "" var lastGroup = "" - for target in sorted { + for (group, target) in sorted { if !last.isEmpty { - output += last + ",\n" + output += last + output += ",\n" } if config.pragmaMark { - let group = pragmaMarkGroupName(target.path, fallback: target.name) if group != lastGroup { output += "// MARK: -\n" output += "// MARK: \(group)\n" @@ -136,7 +136,8 @@ func generateTargetsSection( } if !last.isEmpty { - output += last + "\n" + output += last + output += "\n" } output += "])\n" return output diff --git a/docs/architecture-rules.md b/docs/architecture-rules.md index 89600f6..c86f07f 100644 --- a/docs/architecture-rules.md +++ b/docs/architecture-rules.md @@ -86,7 +86,7 @@ Good: let packageIdentity = dependency.package.id ``` -### `filterImports` does not consult `appleDefaultSDKs`. +### `filterImports` does not consult `appleDefaultSDKs` or `appleDefaultSDKSet`. `apple-sdk-filtering-is-deferred`: Imports are matched to external products and local targets before Apple SDKs are skipped. Filtering SDK names out earlier silently drops a package product that shares a name with an SDK, like `Charts` (CODING_STANDARDS.md, "Apple SDK filtering happens at render time"). @@ -102,7 +102,7 @@ func filterImports(rawImports: [String], …) -> [String] { Good: ```swift -} else if appleSDKs.contains(dep) { +} else if appleDefaultSDKSet.contains(dep) { // Known Apple SDK: skip silently, after externalDeps and local targets were checked. ``` diff --git a/docs/performance.md b/docs/performance.md new file mode 100644 index 0000000..67633a6 --- /dev/null +++ b/docs/performance.md @@ -0,0 +1,88 @@ +# Measuring and profiling + +The benchmarks live in `Benchmarks/`, a separate package on [package-benchmark](https://github.com/ordo-one/package-benchmark), +so the plugin never depends on it. Run everything from the repository root. package-benchmark uses jemalloc to count +allocations (`brew install jemalloc`); set `BENCHMARK_DISABLE_JEMALLOC=true` to build without it. + +## What is measured + +A command plugin cannot be imported, so `Benchmarks/Benchmarks/GeneratorBenchmarks/Shared` links the plugin's +`PackagePlugin`-free files (the same ones the test target links; see `docs/architecture-rules.md`). The benchmarks run +them on a synthetic modular app of 1,000 targets: 25 folders of 20 library targets, each with a test target, and +about 15 imports per library mixing local targets, external products, Apple SDKs, an excluded import and an unknown +module. + +| Benchmark | What it runs | +|---|---| +| Decode config, 1,000 targets | `JSONDecoder` on `ConfigurationV2`, with half the targets' parameters in the legacy `targetsParameters` | +| Filter imports, 1,000 targets | `filterImports` for every target | +| Dependency graph, 1,000 targets | `computeDependencyWeight` and `analyzeDependencyGraph` | +| Render products, 1,000 targets | `generateProductsSection` | +| Render Package.swift, 1,000 targets | `renderPackageContent` with `pragmaMark` and `leafInfo` on: the whole generated file | +| Render Package.swift, 1,000 targets, default settings | the same with the default configuration | + +Not measured: finding target folders on disk, running `package-generator-cli` (which reads the sources and extracts +their imports, and is benchmarked in its own repository) and the YAML-to-JSON conversion in `yaml-converter`. Those +are process launches and file system work rather than code in this repository. + +## Measure a change + +Save `main`'s numbers before you change code, then compare the same harness after: + +```sh +swift package --package-path Benchmarks benchmark --format markdown --no-progress > .build/before.md +# … change the code … +swift package --package-path Benchmarks benchmark --format markdown --no-progress > .build/after.md +swift run --package-path Benchmarks -c release p50 .build/before.md .build/after.md +``` + +`p50` prints a Markdown table of each benchmark's median wall clock and mallocs, before → after, ready for the pull +request. Malloc and retain counts are deterministic; wall clock moves by 10 to 20 % between runs on a busy machine, so +rerun a benchmark before trusting a small change. + +- `--filter` takes one regular expression per flag and runs the benchmarks that match any of them: repeat the flag + (`--filter 'Decode.*' --filter 'Render products.*'`) rather than writing `A|B`. +- `benchmark baseline update` / `baseline compare` are package-benchmark's own thresholds and stay available; `p50` is + for reading the difference at a glance. +- The generated text must not change. `Tests/PackageGeneratorTests/TargetRenderingTests.swift` checks a whole file + byte for byte; for a larger check, render the synthetic project before and after and `cmp` the two. + +## Profile a benchmark + +```sh +Benchmarks/scripts/profile.sh 'Render Package.swift, 1,000 targets' 25 +``` + +It runs that one benchmark under Instruments' Time Profiler and prints: + +- **Self**: the functions the samples were in. Standard library entries here say what kind of work dominates + (`Hasher.combine` is hashing, `_stringCompareWithSmolCheck` string comparison, `_xzm_malloc` allocation). +- **Inclusive**: the generator's functions with the most samples under them, which says whose work it is. + +The trace stays in `Benchmarks/.build/profiles/` to open in Instruments. package-benchmark's ARC and malloc counting +hooks run only while measuring, so the report leaves out samples inside them. + +## What has paid off + +Rendering a 1,000-target `Package.swift`, before → after (Apple silicon, release build, p50): + +| Benchmark | Wall clock p50 (µs) | Mallocs p50 | +|---|---|---| +| Render Package.swift, 1,000 targets | 42,598 → 8,552 (0.20x) | 154,605 → 35,631 (0.23x) | +| Render Package.swift, 1,000 targets, default settings | 38,273 → 8,372 (0.22x) | 147,124 → 35,537 (0.24x) | +| Dependency graph, 1,000 targets | 1,213 → 834 (0.69x) | 5,003 → 29 (0.01x) | +| Decode config, Filter imports, Render products | unchanged (code untouched; ±15 % run-to-run noise) | unchanged | + +Released in 1.0.6. The rendered text is byte for byte the same (checked with `cmp` on the 1.1 MB synthetic output, and +end to end by running the plugin on a sample package from `main` and from the change). + +- **Compute a sort key once, not in the comparator.** `generateTargetsSection` sorted the targets by pragma-mark group + and called `pragmaMarkGroupName` (a `split` and a `String` per path component) twice per comparison: half of all + rendering time. The group is now computed once per target and reused for the `// MARK:` lines. +- **Build a constant set once.** `renderSingleTarget` built `Set(appleDefaultSDKs)`, about 270 strings hashed, for + every target. `appleDefaultSDKSet` is a global built on first use. +- **Count instead of filtering into an array.** The dependency graph metrics built an array of local dependencies per + target only to count it or check that it was empty; `count(where:)` and `contains(where:)` allocate nothing. + +What is left in rendering is string building in `renderSingleTarget`, about 8 µs per target. A run of the plugin is +dominated by `package-generator-cli` reading sources, so further work here buys little. From f5c4fd549bcc0a041c043a30e7fabc17dd759ca4 Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 03:06:49 +0100 Subject: [PATCH 4/8] Drop the release note from performance.md until a release exists --- docs/performance.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/performance.md b/docs/performance.md index 67633a6..6c0c7d1 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -73,7 +73,7 @@ Rendering a 1,000-target `Package.swift`, before → after (Apple silicon, relea | Dependency graph, 1,000 targets | 1,213 → 834 (0.69x) | 5,003 → 29 (0.01x) | | Decode config, Filter imports, Render products | unchanged (code untouched; ±15 % run-to-run noise) | unchanged | -Released in 1.0.6. The rendered text is byte for byte the same (checked with `cmp` on the 1.1 MB synthetic output, and +The rendered text is byte for byte the same (checked with `cmp` on the 1.1 MB synthetic output, and end to end by running the plugin on a sample package from `main` and from the change). - **Compute a sort key once, not in the comparator.** `generateTargetsSection` sorted the targets by pragma-mark group From 454db9831c1970f257decf311869e30e7c6b95c0 Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 03:08:21 +0100 Subject: [PATCH 5/8] Add a GitHub Pages landing page site/index.html explains the plugin and its companion CLI, with a real config, the output it produces, and the install snippet for 1.0.5. .github/workflows/pages.yml deploys site/ from main. --- .github/workflows/pages.yml | 41 +++++ site/index.html | 358 ++++++++++++++++++++++++++++++++++++ 2 files changed, 399 insertions(+) create mode 100644 .github/workflows/pages.yml create mode 100644 site/index.html diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml new file mode 100644 index 0000000..deef31c --- /dev/null +++ b/.github/workflows/pages.yml @@ -0,0 +1,41 @@ +name: Pages + +# Publishes site/, the project's landing page, to GitHub Pages when it changes on main. +on: + push: + branches: [main] + paths: [site/**, .github/workflows/pages.yml] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: pages + cancel-in-progress: false + +jobs: + deploy: + name: Deploy + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Configure Pages + uses: actions/configure-pages@v5 + - name: Upload site + uses: actions/upload-pages-artifact@v3 + with: + path: site + - name: Deploy + id: deployment + uses: actions/deploy-pages@v4 diff --git a/site/index.html b/site/index.html new file mode 100644 index 0000000..04fbf06 --- /dev/null +++ b/site/index.html @@ -0,0 +1,358 @@ + + + + + +Package Generator · Package.swift that writes itself + + + + + + + + + + + + +
+
+
+
    +
  • SwiftPM command plugin
  • +
  • Xcode & command line
  • +
  • Swift 6.2
  • +
  • MIT
  • +
+

A Package.swift that writes itself.

+

Package Generator reads the imports in every target of a heavily modularized Swift project and writes the targets, test targets, products and dependencies of your Package.swift. You keep a short YAML file; the plugin keeps the manifest in step with the code.

+ +
+
+
packageGenerator.yaml
+
pragmaMark: true
+spaces: 2
+
+packageDirectoryTargets:
+  - path: Sources/Core
+    targets:
+      - name: Core
+      - name: CoreTests
+        type: test
+
+  - path: Sources/Features
+    targets:
+      - name: Auth
+        parameters:
+          - 'resources: [.process("Resources")]'
+      - name: AuthTests
+        type: test
+
+
+
+ +
+
+

Why

+

Modularizing is easy.
Keeping the manifest right is not.

+

Splitting an app into dozens or hundreds of SwiftPM targets pays off in build times, previews and boundaries. Then every new import means editing a dependencies: array by hand, and the manifest drifts from the code.

+
+
1 import

is one more line to add to Package.swift, in the right target, with the right .product(name:package:) identity.

+
0 drift

The plugin derives dependencies from the source, so a removed import disappears from the manifest on the next run.

+
1 file

to review: a YAML or JSON config listing folders and targets. Paths, test pairing and product names are inferred.

+
+
+
+ +
+
+

How it works

+

Two tools, one command.

+

Package Generator is a pair: this plugin, which you add to your package, and Package Generator CLI, the binary it runs to read your sources. The plugin downloads the CLI for you as a SwiftPM binary target.

+
+
+
This repository
+

Package Generator plugin

+
    +
  • Finds packageGenerator.yaml, .yml or .json and resolves each target's folder.
  • +
  • Maps every import to a local target, an external product from your dependencies, or an Apple SDK.
  • +
  • Renders products and targets, sorted and grouped, and writes Package.swift.
  • +
+
+
+ +

Package Generator CLI

+
    +
  • Parses every Swift file of every target with swift-syntax.
  • +
  • Reports each target's imports to the plugin as JSON.
  • +
  • Ships as an arm64 macOS artifact bundle; you never install or call it yourself.
  • +
+
+
+
+

Describe

List your folders and targets in packageGenerator.yaml. Add per-target parameters, exclusions or product names where you need them.

+

Run

Right-click your package in Xcode and choose Package Generator, or run the command below in a terminal or on CI.

+

Review

Set dryRun: true to write Package_generated.swift and diff it first. Output is deterministic, so diffs stay small.

+
+
+
+

Sources/Features/Auth/Login.swift

+
Login.swift
+
import Core
+import ComposableArchitecture
+import SwiftUI
+
+// …
+

Terminal

+
zsh
+
swift package plugin \
+  --allow-writing-to-package-directory \
+  package-generator
+
+
+

Generated Package.swift (excerpt)

+
Package.swift
+
// MARK: - Generated 2 packages
+
+// MARK: - Targets
+package.products.append(contentsOf: [
+  .library(name: "Auth", targets: ["Auth"]),
+  .library(name: "Core", targets: ["Core"])
+])
+
+// MARK: - Products
+package.targets.append(contentsOf: [
+// … the Core group: Core, CoreTests …
+// MARK: -
+// MARK: Features
+  .target(
+    name: "Auth",
+    dependencies: [
+      "Core",
+      .product(name: "ComposableArchitecture", package: "swift-composable-architecture")
+    ],
+    path: "Sources/Features/Auth",
+    resources: [.process("Resources")]
+  ),
+  .testTarget(
+    name: "AuthTests",
+    // …
+  )
+])
+
+
+
+
+ +
+
+

Features

+

Built for apps with hundreds of modules.

+
+

Imports become dependencies

Local targets become "Name"; products from your root dependencies become .product(name:package:) with the URL-derived package identity SwiftPM expects.

+

Apple SDKs ignored, safely

A built-in list of about 270 Apple frameworks is skipped, but only after external products are checked, so a package product named Charts is never lost.

+

Your parameters, verbatim

parameters and additionalDependencies go into the manifest as written, for resources, Swift settings, macros and plugins that no import reveals.

+

Products your way

Set libraryType to dynamic or static globally or per target, and rename a product with productName when Xcode needs the two to differ.

+

Readable output

Sorted products and targets, optional // MARK: groups per folder, a custom header file, and your indentation.

+

Architecture insight

leafInfo annotates each target with its dependency counts and flags the heaviest; unusedThreshold warns about modules nobody imports.

+

Tests paired automatically

FeatureTests is linked to Feature by name, with regularTargetName for the exceptions.

+

Old configs keep working

The legacy targetsParameters map and boolean verbose are migrated in memory. See the migration guide.

+

Fast on big graphs

Rendering a 1,000-target manifest takes under 10 ms, measured with package-benchmark. See performance.

+
+
+
+ +
+
+

Install

+

Add the plugin, write the config, run it.

+
+
+

1. Add the dependency

+

In the Package.swift you want generated. Requires Swift 6.2 (Xcode 26) on an Apple silicon Mac.

+
Package.swift
+
dependencies: [
+  .package(url: "https://github.com/mackoj/PackageGeneratorPlugin.git", from: "1.0.5"),
+]
+
+
+

2. Describe your targets

+

Create packageGenerator.yaml next to it, like the one at the top of this page. If none exists, the first run writes a packageGenerator.json template.

+
+
+

3. Generate

+

In Xcode, right-click the package and choose Package Generator. From a terminal or CI:

+
zsh
+
swift package plugin --allow-writing-to-package-directory package-generator
+# or with an explicit config
+swift package plugin --allow-writing-to-package-directory package-generator --confFile myconfig.yaml
+
+
+ +
+
+ + + + + From 8667c99e68ecc25bb69d38173551574c9c2b5878 Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 03:09:09 +0100 Subject: [PATCH 6/8] Refresh the README Add badges and links to the website, the CLI, performance and architecture rules docs; state the requirements; install from 1.0.5; fix the leaf info, pragma mark and unresolved-import examples to match the real output; replace the stale Yams troubleshooting tip; add a Development section. --- README.md | 54 +++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 41 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 5e94a59..b9fd14b 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,33 @@ -# PackageGenerator +# Package Generator -Auto-generate complex multi-target SPM `Package.swift`. Read source imports, resolve dependencies, build targets. Works with heavily modularized projects + TCA. +[![CI](https://github.com/mackoj/PackageGeneratorPlugin/actions/workflows/ci.yml/badge.svg)](https://github.com/mackoj/PackageGeneratorPlugin/actions/workflows/ci.yml) +[![Release](https://img.shields.io/github/v/release/mackoj/PackageGeneratorPlugin)](https://github.com/mackoj/PackageGeneratorPlugin/releases) +[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) -- **Backward compatible**: old config format still works -- **Zero-exclusion filtering**: only links known targets + products (Apple SDKs auto-ignored) -- **Advanced analysis**: unused target detection, dependency weight, exported files -- **CLI-free config**: auto-finds `packageGenerator.yaml/yml/json` -- **Full V2 architecture**: 7 epics from design, strict schema +**[Website](https://mackoj.github.io/PackageGeneratorPlugin/)** · +**[Package Generator CLI](https://github.com/mackoj/PackageGeneratorCLI)** · +**[Migration guide](MIGRATION.md)** · +**[Performance](docs/performance.md)** · +**[Architecture rules](docs/architecture-rules.md)** + +A SwiftPM command plugin that generates `Package.swift` for heavily modularized projects. It reads the imports of every target, resolves each one to a local target, an external product or an Apple SDK, and writes the products and targets for you. Works well with hundreds of targets and with TCA-style feature modules. + +The plugin runs [Package Generator CLI](https://github.com/mackoj/PackageGeneratorCLI), which parses your sources with swift-syntax. SwiftPM downloads the CLI as a binary target, so you never install it yourself. + +- **Imports become dependencies**: local targets become `"Name"`, products of your root dependencies become `.product(name:package:)` with the URL-derived package identity +- **Apple SDKs ignored safely**: a built-in list is skipped only after external products are checked, so a product named like an SDK (`Charts`) is kept +- **Verbatim parameters**: `parameters` and `additionalDependencies` go into the manifest as written +- **Analysis**: unused target detection, dependency weight, exported files +- **Backward compatible**: the old `targetsParameters` config format still works +- **Config auto-discovery**: finds `packageGenerator.yaml`, `.yml` or `.json` + +**Requirements**: Swift 6.2 (Xcode 26) on an Apple silicon Mac; `package-generator-cli` ships as an arm64 macOS binary. ## Quick Start 1. **Install** (add to dependencies in your root Package.swift): ```swift - .package(url: "https://github.com/mackoj/PackageGeneratorPlugin.git", from: "1.0.0") + .package(url: "https://github.com/mackoj/PackageGeneratorPlugin.git", from: "1.0.5") ``` 2. **Create** config at project root. Choose YAML or JSON: @@ -223,7 +238,7 @@ Output: // MARK: - // MARK: Features -.target(name: Auth", ...), +.target(name: "Auth", ...), .testTarget(name: "AuthTests", ...), ``` @@ -237,8 +252,11 @@ leafInfo: true Output: ```swift -.target(name: "Core", dependencies: [...]), // 3|2 -.target(name: "Auth", dependencies: [...]), // 5|3 🚛 + .target( + name: "Core",// [3|2] + ... + .target( + name: "Auth",// [5|3|🚛] ``` First number = total deps, second = local deps. 🚛 = highest local count. @@ -322,7 +340,7 @@ Errors appear in Xcode Report Navigator: - `❌ Error: Config file not found` — no `packageGenerator.{yaml,yml,json}` at root - `❌ Error: YAML decode failed` — invalid YAML syntax -- `ℹ️ Dropped unresolved import 'SomeLib'` — import not in local targets or auto-discovered/mapped products; add a `mappers.imports` entry if it's a real dependency +- `⚠️ Dropped unresolved import 'SomeLib'. If it's a system framework, ignore this.` — import not in local targets or auto-discovered/mapped products; add a `mappers.imports` entry if it's a real dependency - `📦 UnusedModule is used 0 times` — target never imported by others Use `verbose: "all"` for full diagnostics, `verbose: "cli"` or `verbose: "plugin"` for targeted output. @@ -359,9 +377,19 @@ Fails if Package.swift has errors or config invalid. ## Troubleshooting - **Plugin not visible in Xcode?** Run "Resolve Packages" in Package.swift. -- **YAML not working?** Ensure `Yams` dependency in plugin Package.swift. +- **YAML not working?** The plugin converts YAML with its bundled `yaml-converter` tool; check the YAML syntax, or try the same config as `packageGenerator.json`. - **dry-run keeps running?** Check `dryRun: false` in config + check error logs. +## Development + +```bash +swift build --build-tests && swift test # plugin, yaml-converter and unit tests +swift test --package-path Architecture # architecture rules (swift-llm-check) +swift package --package-path Benchmarks benchmark # benchmarks (package-benchmark, needs jemalloc) +``` + +A command plugin cannot be imported, so the tests and benchmarks compile the plugin's `PackagePlugin`-free files through symbolic links. Read [CODING_STANDARDS.md](CODING_STANDARDS.md) before changing code; [docs/architecture-rules.md](docs/architecture-rules.md) lists the rules CI enforces and [docs/performance.md](docs/performance.md) how to measure and profile. + ## License MIT From 250f94d297551f57fe13a86985d974ed5d4b77a1 Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 09:03:04 +0100 Subject: [PATCH 7/8] Point install snippets at 1.0.6 --- README.md | 2 +- site/index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b9fd14b..b6619bb 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ The plugin runs [Package Generator CLI](https://github.com/mackoj/PackageGenerat 1. **Install** (add to dependencies in your root Package.swift): ```swift - .package(url: "https://github.com/mackoj/PackageGeneratorPlugin.git", from: "1.0.5") + .package(url: "https://github.com/mackoj/PackageGeneratorPlugin.git", from: "1.0.6") ``` 2. **Create** config at project root. Choose YAML or JSON: diff --git a/site/index.html b/site/index.html index 04fbf06..a1490c9 100644 --- a/site/index.html +++ b/site/index.html @@ -321,7 +321,7 @@

1. Add the dependency

In the Package.swift you want generated. Requires Swift 6.2 (Xcode 26) on an Apple silicon Mac.

Package.swift
dependencies: [
-  .package(url: "https://github.com/mackoj/PackageGeneratorPlugin.git", from: "1.0.5"),
+  .package(url: "https://github.com/mackoj/PackageGeneratorPlugin.git", from: "1.0.6"),
 ]
From a8dcc215d93b34e47f5ecebc7d94c73ab42f87da Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 09:04:54 +0100 Subject: [PATCH 8/8] Adopt swift-llm-check 0.5.0's built-in detectors - `xcTestImports` and `disabledTests` come from the library; the local copies and their detector tests are gone. - `.llm-check.yaml` no longer excludes the `Shared` folders: with `symbolicLinks: follow` the codebase reads the links and `SourceFile.symbolicLinkDestination` says where each points, which replaces `SharedSource` and `Detect.unlinkedTestSources`. The benchmarks' own code stays excluded. - `SourceFile` is not a `Finding`, so the link rule maps each offending file to a `Violation` instead of calling `expectAll` on the files. Rule ids, titles and rationales are unchanged, so docs/architecture-rules.md is too. --- .llm-check.yaml | 10 ++++-- Architecture/Package.swift | 2 +- .../ArchitectureTests/ArchitectureRules.swift | 22 ++++++++++--- .../Tests/ArchitectureTests/Detect.swift | 27 ---------------- .../ArchitectureTests/DetectorTests.swift | 25 --------------- .../Tests/ArchitectureTests/Support.swift | 31 ------------------- 6 files changed, 25 insertions(+), 92 deletions(-) diff --git a/.llm-check.yaml b/.llm-check.yaml index c61195c..ecc8f1d 100644 --- a/.llm-check.yaml +++ b/.llm-check.yaml @@ -2,11 +2,15 @@ # A name matches any folder or file; a path with a slash matches from the root. excludes: - Architecture - - Benchmarks + # The benchmarks' own code; their `Shared` folder stays, for `test-sources-link-the-plugin-files`. + - Benchmarks/Package.swift + - Benchmarks/Tools + - Benchmarks/Benchmarks/GeneratorBenchmarks/GeneratorBenchmarks.swift - docs - Examples - site - # Symbolic links to files in Plugins/PackageGenerator; the rules read the originals. - - Tests/PackageGeneratorTests/Shared # Folders ending in Tests hold test code. testSuffixes: [Tests] +# Read the `Shared` links into Plugins/PackageGenerator, so a rule can require links and not copies. The plugin files +# are then also read under the link paths, which only the test rules see; neither finds anything in plugin code. +symbolicLinks: follow diff --git a/Architecture/Package.swift b/Architecture/Package.swift index 656e631..293d896 100644 --- a/Architecture/Package.swift +++ b/Architecture/Package.swift @@ -8,7 +8,7 @@ let package = Package( name: "Architecture", platforms: [.macOS(.v14)], dependencies: [ - .package(url: "https://github.com/mackoj/swift-llm-check.git", from: "0.4.1"), + .package(url: "https://github.com/mackoj/swift-llm-check.git", from: "0.5.0"), .package(url: "https://github.com/swiftlang/swift-syntax.git", "601.0.0"..<"700.0.0"), ], targets: [ diff --git a/Architecture/Tests/ArchitectureTests/ArchitectureRules.swift b/Architecture/Tests/ArchitectureTests/ArchitectureRules.swift index c077363..4418dfe 100644 --- a/Architecture/Tests/ArchitectureTests/ArchitectureRules.swift +++ b/Architecture/Tests/ArchitectureTests/ArchitectureRules.swift @@ -7,14 +7,26 @@ struct ArchitectureRules { static func plugin() throws -> Scope { try repository().productionCode.in("Plugins/PackageGenerator") } static func tests() throws -> Scope { try repository().testCode.in("Tests") } + /// The Swift files in `sharedSourceFolders`, links included (`symbolicLinks: follow`). + static func shared() throws -> [SourceFile] { try repository().allCode.in(sharedSourceFolders).files } + @Test func testSourcesLinkThePluginFiles() throws { - let sources = try SharedSource.all(in: repository()) + let sources = try Self.shared() #expect(sources.count >= 10) - expectNone(Detect.unlinkedTestSources(sources), rule: .testSourcesLinkThePluginFiles) + // `SourceFile` is not a `Finding` in swift-llm-check 0.5.0, so each offending file becomes a `Violation`. + let unlinked = sources.filter { $0.symbolicLinkDestination?.hasPrefix("Plugins/PackageGenerator/") != true } + expectNone( + unlinked.map { file in + Violation( + location: Location(filePath: file.path, relativePath: file.relativePath, line: 1, column: 1), + snippet: file.symbolicLinkDestination.map { "\(file.relativePath) -> \($0)" } + ?? "\(file.relativePath) is a regular file") + }, + rule: .testSourcesLinkThePluginFiles) } @Test func coreFilesImportOnlyFoundation() throws { - let linked = try SharedSource.all(in: repository()).compactMap(\.destination) + let linked = Array(Set(try Self.shared().compactMap(\.symbolicLinkDestination))).sorted() #expect(linked.count >= 3) expectNone(Detect.coreImports(in: try Self.plugin(), files: linked), rule: .coreFilesImportOnlyFoundation) } @@ -44,11 +56,11 @@ struct ArchitectureRules { @Test func testsUseSwiftTesting() throws { let tests = try Self.tests() #expect(tests.containing("import Testing").relativePaths.count >= 1) - expectNone(Detect.xcTestImports(in: tests), rule: .testsUseSwiftTesting) + expectNone(tests.xcTestImports, rule: .testsUseSwiftTesting) } @Test func testsAreNotDisabled() throws { - expectNone(Detect.disabledTests(in: try Self.tests()), rule: .testsAreNotDisabled) + expectNone(try Self.tests().disabledTests, rule: .testsAreNotDisabled) } } diff --git a/Architecture/Tests/ArchitectureTests/Detect.swift b/Architecture/Tests/ArchitectureTests/Detect.swift index 9933169..174ee0c 100644 --- a/Architecture/Tests/ArchitectureTests/Detect.swift +++ b/Architecture/Tests/ArchitectureTests/Detect.swift @@ -3,21 +3,6 @@ import SwiftSyntax /// The detectors, separate from the codebase so `DetectorTests` can run them on snippets. enum Detect { - /// Shared test sources that are regular files, or links that do not point into `Plugins/PackageGenerator`. - static func unlinkedTestSources(_ sources: [SharedSource]) -> [Violation] { - sources.filter { source in - guard let destination = source.destination else { return true } - return !destination.hasPrefix("Plugins/PackageGenerator/") - } - .map { source in - Violation( - location: Location( - filePath: source.relativePath, relativePath: source.relativePath, line: 1, column: 1), - snippet: source.destination.map { "\(source.relativePath) -> \($0)" } - ?? "\(source.relativePath) is a regular file") - } - } - /// Imports other than Foundation in `files`, the plugin files that the tests link. static func coreImports(in plugin: Scope, files: [String]) -> [Match] { guard !files.isEmpty else { return [] } @@ -53,18 +38,6 @@ enum Detect { } } - /// `import XCTest`. - static func xcTestImports(in scope: Scope) -> [Match] { - scope.imports(of: "XCTest") - } - - /// The `.disabled(…)` trait, wherever a test or suite takes it. - static func disabledTests(in scope: Scope) -> [Match] { - scope.calls(named: "disabled").filter { call in - call.node.receiver == nil && call.node.calledExpression.is(MemberAccessExprSyntax.self) - } - } - private static func memberAccesses(named names: Set, in scope: Scope) -> [Match] { scope.containing(Array(names)).nodes(of: MemberAccessExprSyntax.self) { $0.node.base != nil && names.contains($0.node.declName.baseName.text) diff --git a/Architecture/Tests/ArchitectureTests/DetectorTests.swift b/Architecture/Tests/ArchitectureTests/DetectorTests.swift index 179771e..08375eb 100644 --- a/Architecture/Tests/ArchitectureTests/DetectorTests.swift +++ b/Architecture/Tests/ArchitectureTests/DetectorTests.swift @@ -7,15 +7,6 @@ import Testing Scope(files: [SourceFile(path: path, source: source)]) } - @Test func unlinkedTestSourcesAreFound() { - let found = Detect.unlinkedTestSources([ - SharedSource(relativePath: "Tests/T/Shared/A.swift", destination: "Plugins/PackageGenerator/A.swift"), - SharedSource(relativePath: "Tests/T/Shared/B.swift", destination: nil), - SharedSource(relativePath: "Tests/T/Shared/C.swift", destination: "Sources/Other/C.swift"), - ]) - #expect(found.map(\.location.relativePath) == ["Tests/T/Shared/B.swift", "Tests/T/Shared/C.swift"]) - } - @Test func coreImportsAreFound() { let plugin = Scope(files: [ SourceFile(path: "Plugins/PackageGenerator/Core.swift", source: "import Foundation\nimport PackagePlugin"), @@ -80,20 +71,4 @@ import Testing """)) #expect(found.map(\.location.line) == [2, 2]) } - - @Test func xcTestImportsAreFound() { - let found = Detect.xcTestImports(in: scope("import XCTest\nimport Testing", at: "Tests/T/A.swift")) - #expect(found.map(\.location.line) == [1]) - } - - @Test func disabledTestsAreFound() { - let found = Detect.disabledTests( - in: scope( - """ - @Test(.disabled("flaky")) func a() {} - @Suite(.disabled()) struct B {} - @Test func c() { rule.disabled() } - """, at: "Tests/T/A.swift")) - #expect(found.map(\.location.line) == [1, 2]) - } } diff --git a/Architecture/Tests/ArchitectureTests/Support.swift b/Architecture/Tests/ArchitectureTests/Support.swift index 13ada31..7a3fcb6 100644 --- a/Architecture/Tests/ArchitectureTests/Support.swift +++ b/Architecture/Tests/ArchitectureTests/Support.swift @@ -1,4 +1,3 @@ -import Foundation import LLMCheck /// The PackageGeneratorPlugin repository, rooted where `.llm-check.yaml` is. Its file list and every parsed file are @@ -9,36 +8,6 @@ func repository() throws -> Codebase { try Codebase() } /// imported. let sharedSourceFolders = ["Tests/PackageGeneratorTests/Shared", "Benchmarks/Benchmarks/GeneratorBenchmarks/Shared"] -/// A Swift file in one of `sharedSourceFolders`, and where it points when it is a symbolic link. -struct SharedSource: Sendable { - /// From the repository root, like `Tests/PackageGeneratorTests/Shared/ParsedPackage.swift`. - let relativePath: String - /// The link's destination from the repository root, like `Plugins/PackageGenerator/ParsedPackage.swift`, or `nil` - /// when the file is a regular file. - let destination: String? - - /// The Swift files in `sharedSourceFolders` of `codebase`, read from the file system: `Codebase` excludes the - /// folders so that the rules read each file once, under its real path. - static func all(in codebase: Codebase) throws -> [SharedSource] { - let fileManager = FileManager.default - let root = codebase.root.standardizedFileURL.path + "/" - return try sharedSourceFolders.flatMap { relativeFolder in - let folder = codebase.root.appendingPathComponent(relativeFolder) - return try fileManager.contentsOfDirectory(atPath: folder.path).sorted() - .filter { $0.hasSuffix(".swift") } - .map { name in - let link = folder.appendingPathComponent(name) - let target = try? fileManager.destinationOfSymbolicLink(atPath: link.path) - let destination = target.map { - URL(fileURLWithPath: $0, relativeTo: folder).standardizedFileURL.path - .replacingOccurrences(of: root, with: "") - } - return SharedSource(relativePath: "\(relativeFolder)/\(name)", destination: destination) - } - } - } -} - extension RuleCategory { static let structure = RuleCategory( "structure",