From 3e23344899102a133f57ed42fcdbb677c4e277ce Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 02:38:21 +0100 Subject: [PATCH 1/2] Add architecture rules with swift-llm-check Encode the plugin's conventions (pure core linked into the tests, Diagnostics over print, package identity over displayName, deferred Apple SDK filtering, URL-based PackagePlugin APIs, Swift Testing) as an Architecture/ test package, document them in CODING_STANDARDS.md and docs/architecture-rules.md, and add a macOS CI workflow that builds, tests and runs the rules. --- .github/copilot-instructions.md | 11 +- .github/workflows/ci.yml | 31 ++++ .gitignore | 6 + .llm-check.yaml | 12 ++ Architecture/Package.swift | 23 +++ .../ArchitectureTests/ArchitectureRules.swift | 69 +++++++ .../Tests/ArchitectureTests/Detect.swift | 73 ++++++++ .../ArchitectureTests/DetectorTests.swift | 99 ++++++++++ .../Tests/ArchitectureTests/Rules.swift | 152 ++++++++++++++++ .../Tests/ArchitectureTests/Support.swift | 55 ++++++ CODING_STANDARDS.md | 46 +++++ docs/architecture-rules.md | 171 ++++++++++++++++++ 12 files changed, 745 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 .llm-check.yaml create mode 100644 Architecture/Package.swift create mode 100644 Architecture/Tests/ArchitectureTests/ArchitectureRules.swift create mode 100644 Architecture/Tests/ArchitectureTests/Detect.swift create mode 100644 Architecture/Tests/ArchitectureTests/DetectorTests.swift create mode 100644 Architecture/Tests/ArchitectureTests/Rules.swift create mode 100644 Architecture/Tests/ArchitectureTests/Support.swift create mode 100644 CODING_STANDARDS.md create mode 100644 docs/architecture-rules.md diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 66b1de1..84c6baa 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -4,13 +4,18 @@ A Swift Package Manager **Command Plugin** that auto-generates `Package.swift` for heavily modularized SPM projects. It reads source files, extracts imports via a companion binary (`package-generator-cli`), resolves dependencies, and writes the output. -It is **not a library**. There is no test target. Testing is done via dry-run in consumer projects. +It is **not a library**. The pure generator files (no `PackagePlugin` import) are unit tested through symbolic links in `Tests/PackageGeneratorTests/Shared`; the rest is tested via dry-run in consumer projects. + +Read `CODING_STANDARDS.md` before changing code. Its mechanical rules are enforced by the `Architecture/` package (swift-llm-check) and listed in `docs/architecture-rules.md`. ## Build & Run ```bash -# Build the package (plugin + yaml-converter tool) -swift build +# Build the package (plugin + yaml-converter tool) and run the unit tests +swift build --build-tests && swift test + +# Architecture rules (regenerate docs/architecture-rules.md with LLM_CHECK_RECORD=1) +swift test --package-path Architecture # Run the plugin in a consumer project swift package plugin --allow-writing-to-package-directory package-generator diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..985e5d0 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,31 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + macos: + name: macOS + # package-generator-cli ships as an arm64 macOS binary, so the plugin builds on Apple silicon only. + runs-on: macos-15 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Swift version + run: swift --version + - name: Build + run: swift build --build-tests + - name: Test + run: swift test + - name: Architecture rules + run: swift test --package-path Architecture diff --git a/.gitignore b/.gitignore index bdf05aa..151d7ed 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,9 @@ packageGenerator.json packageGenerator.yaml packageGenerator.yml Package_generated.swift +/Architecture/.build +/Architecture/.swiftpm +/Architecture/Package.resolved +/Benchmarks/.build +/Benchmarks/.swiftpm +/Benchmarks/.benchmarkBaselines diff --git a/.llm-check.yaml b/.llm-check.yaml new file mode 100644 index 0000000..c61195c --- /dev/null +++ b/.llm-check.yaml @@ -0,0 +1,12 @@ +# swift-llm-check: what the rules in Architecture/ read. `Codebase()` finds the repository root here. +# A name matches any folder or file; a path with a slash matches from the root. +excludes: + - Architecture + - Benchmarks + - 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] diff --git a/Architecture/Package.swift b/Architecture/Package.swift new file mode 100644 index 0000000..656e631 --- /dev/null +++ b/Architecture/Package.swift @@ -0,0 +1,23 @@ +// swift-tools-version: 6.0 +import PackageDescription + +// PackageGeneratorPlugin's mechanical rules (CODING_STANDARDS.md) as tests, written with swift-llm-check. +// A separate, test-only package, so the plugin never builds it and its dependencies stay Yams alone. +// Run from the repository root: `swift test --package-path Architecture`. +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/swiftlang/swift-syntax.git", "601.0.0"..<"700.0.0"), + ], + targets: [ + .testTarget( + name: "ArchitectureTests", + dependencies: [ + .product(name: "LLMCheck", package: "swift-llm-check"), + .product(name: "SwiftSyntax", package: "swift-syntax"), + ] + ) + ] +) diff --git a/Architecture/Tests/ArchitectureTests/ArchitectureRules.swift b/Architecture/Tests/ArchitectureTests/ArchitectureRules.swift new file mode 100644 index 0000000..db99704 --- /dev/null +++ b/Architecture/Tests/ArchitectureTests/ArchitectureRules.swift @@ -0,0 +1,69 @@ +import LLMCheck +import Testing + +/// The rules, run on the repository. A failure prints the rule, why it exists and how to fix it. +@Suite("Architecture rules") +struct ArchitectureRules { + static func plugin() throws -> Scope { try repository().productionCode.in("Plugins/PackageGenerator") } + static func tests() throws -> Scope { try repository().testCode.in("Tests") } + + @Test func testSourcesLinkThePluginFiles() throws { + let sources = try SharedSource.all(in: repository()) + #expect(sources.count >= 3) + expectNone(Detect.unlinkedTestSources(sources), rule: .testSourcesLinkThePluginFiles) + } + + @Test func coreFilesImportOnlyFoundation() throws { + let linked = try SharedSource.all(in: repository()).compactMap(\.destination) + #expect(linked.count >= 3) + expectNone(Detect.coreImports(in: try Self.plugin(), files: linked), rule: .coreFilesImportOnlyFoundation) + } + + @Test func pluginReportsThroughDiagnostics() throws { + let plugin = try Self.plugin() + #expect(plugin.containing("Diagnostics.emit").relativePaths.count > 3) + expectNone(Detect.printCalls(in: plugin), rule: .pluginReportsThroughDiagnostics) + } + + @Test func externalProductsUsePackageIdentity() throws { + expectNone(Detect.displayNameReads(in: try Self.plugin()), rule: .externalProductsUsePackageIdentity) + } + + @Test func appleSDKFilteringIsDeferred() throws { + let plugin = try Self.plugin() + #expect(plugin.containing("func filterImports").relativePaths.count == 1) + expectNone(Detect.earlySDKFiltering(in: plugin), rule: .appleSDKFilteringIsDeferred) + } + + @Test func pluginUsesURLAPIs() throws { + let plugin = try Self.plugin() + #expect(plugin.containing("directoryURL").relativePaths.count > 3) + expectNone(Detect.deprecatedPathAPIs(in: plugin), rule: .pluginUsesURLAPIs) + } + + @Test func testsUseSwiftTesting() throws { + let tests = try Self.tests() + #expect(tests.containing("import Testing").relativePaths.count >= 1) + expectNone(Detect.xcTestImports(in: tests), rule: .testsUseSwiftTesting) + } + + @Test func testsAreNotDisabled() throws { + expectNone(Detect.disabledTests(in: try Self.tests()), rule: .testsAreNotDisabled) + } +} + +/// Keeps `docs/architecture-rules.md` in step with the rules. Regenerate with +/// `LLM_CHECK_RECORD=1 swift test --package-path Architecture`. +@Test func rulesDocumentIsUpToDate() throws { + let catalog = RuleCatalog(allRules) + #expect(catalog.duplicateIDs.isEmpty) + try expectFile( + "docs/architecture-rules.md", in: repository(), + matches: catalog.markdown( + title: "Architecture rules", + introduction: """ + The mechanical part of `CODING_STANDARDS.md`, enforced by the `Architecture/` package with \ + [swift-llm-check](https://github.com/mackoj/swift-llm-check): \ + `swift test --package-path Architecture` (macOS). Generated from its rules; do not edit by hand. + """)) +} diff --git a/Architecture/Tests/ArchitectureTests/Detect.swift b/Architecture/Tests/ArchitectureTests/Detect.swift new file mode 100644 index 0000000..008b3e3 --- /dev/null +++ b/Architecture/Tests/ArchitectureTests/Detect.swift @@ -0,0 +1,73 @@ +import LLMCheck +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 [] } + return plugin.in(files).imports.filter { $0.node.moduleName != "Foundation" } + } + + /// Calls to the global `print`. + static func printCalls(in scope: Scope) -> [Match] { + scope.calls(named: "print").filter { $0.node.calledExpression.is(DeclReferenceExprSyntax.self) } + } + + /// `x.displayName` in code. Comments that explain why it is avoided pass. + static func displayNameReads(in scope: Scope) -> [Match] { + memberAccesses(named: ["displayName"], in: scope) + } + + /// The deprecated `Path` accessors: `.directory`, `.pluginWorkDirectory`, and `.path` on a `tool(named:)` result. + static func deprecatedPathAPIs(in scope: Scope) -> [Match] { + let directories = memberAccesses(named: ["directory", "pluginWorkDirectory"], in: scope) + let toolPaths = memberAccesses(named: ["path"], in: scope.containing("tool(named:")).filter { match in + guard let base = match.node.base else { return false } + return base.trimmedDescription.contains("tool(named:") + } + return directories + toolPaths + } + + /// `appleDefaultSDKs` referenced inside a function named `filterImports`. + static func earlySDKFiltering(in scope: Scope) -> [Match] { + scope.references(to: "appleDefaultSDKs").filter { match in + sequence(first: match.node, next: \.parent).contains { + $0.as(FunctionDeclSyntax.self)?.name.text == "filterImports" + } + } + } + + /// `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 new file mode 100644 index 0000000..655c556 --- /dev/null +++ b/Architecture/Tests/ArchitectureTests/DetectorTests.swift @@ -0,0 +1,99 @@ +import LLMCheck +import Testing + +/// Each detector on snippets: it finds what its rule forbids and nothing its rule allows. +@Suite struct DetectorTests { + func scope(_ source: String, at path: String = "Plugins/PackageGenerator/File.swift") -> Scope { + 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"), + SourceFile(path: "Plugins/PackageGenerator/Shell.swift", source: "import PackagePlugin"), + ]) + let found = Detect.coreImports(in: plugin, files: ["Plugins/PackageGenerator/Core.swift"]) + #expect(found.map(\.location.relativePath) == ["Plugins/PackageGenerator/Core.swift"]) + #expect(found.map(\.node.moduleName) == ["PackagePlugin"]) + } + + @Test func coreImportsWithNoLinkedFilesPass() { + #expect(Detect.coreImports(in: scope("import PackagePlugin"), files: []).isEmpty) + } + + @Test func printCallsAreFound() { + let found = Detect.printCalls( + in: scope( + """ + print("Resolved") + Diagnostics.emit(.remark, "print(\\"fine in a string\\")") + logger.print("not the global print") + """)) + #expect(found.map(\.location.line) == [1]) + } + + @Test func displayNameReadsAreFound() { + let found = Detect.displayNameReads( + in: scope( + """ + // `displayName` is the package's self-declared name. + let identity = dependency.package.id + let name = dependency.package.displayName + """)) + #expect(found.map(\.location.line) == [3]) + } + + @Test func deprecatedPathAPIsAreFound() { + let found = Detect.deprecatedPathAPIs( + in: scope( + """ + let a = context.package.directory + let b = context.pluginWorkDirectory + let c = try context.tool(named: "cli").path + let d = context.package.directoryURL + let e = context.pluginWorkDirectoryURL + let f = outputURL.path + let g = try context.tool(named: "cli").url + """)) + #expect(found.map(\.location.line).sorted() == [1, 2, 3]) + } + + @Test func earlySDKFilteringIsFound() { + let found = Detect.earlySDKFiltering( + in: scope( + """ + func filterImports(rawImports: [String]) -> [String] { + rawImports.filter { !appleDefaultSDKs.contains($0) } + } + func renderSingleTarget() { + let appleExclusions = Set(appleDefaultSDKs) + } + """)) + #expect(found.map(\.location.line) == [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/Rules.swift b/Architecture/Tests/ArchitectureTests/Rules.swift new file mode 100644 index 0000000..59e25ef --- /dev/null +++ b/Architecture/Tests/ArchitectureTests/Rules.swift @@ -0,0 +1,152 @@ +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`.", + 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. + """, + howToFix: """ + Replace the file with a relative link: \ + `ln -s ../../../Plugins/PackageGenerator/Name.swift Tests/PackageGeneratorTests/Shared/Name.swift`. + """, + badExample: "cp Plugins/PackageGenerator/ParsedPackage.swift Tests/PackageGeneratorTests/Shared/", + goodExample: "Shared/ParsedPackage.swift -> ../../../Plugins/PackageGenerator/ParsedPackage.swift" + ) + + static let coreFilesImportOnlyFoundation = Rule( + id: "core-files-import-only-foundation", + 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 \ + `yaml-converter`, not the plugin. + """, + howToFix: """ + 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`). + """, + badExample: """ + // Plugins/PackageGenerator/ProductGeneration.swift + import PackagePlugin + Diagnostics.emit(.warning, "Dropped unresolved import '\\(dep)'") + """, + goodExample: """ + // Plugins/PackageGenerator/ProductGeneration.swift + import Foundation + func render(_ target: ParsedPackage, warn: (String) -> Void) -> String + """ + ) + + static let pluginReportsThroughDiagnostics = Rule( + id: "plugin-reports-through-diagnostics", + title: "The plugin reports through `Diagnostics.emit`, never `print`.", + category: .structure, + rationale: """ + A command plugin's standard output is not shown in Xcode's issue navigator, and in a terminal it mixes \ + with SwiftPM's own output. `Diagnostics` gives every message a severity users can filter \ + (CODING_STANDARDS.md, "Diagnostics, not print"). + """, + howToFix: "Call `Diagnostics.emit(.remark, …)`, guarded by `config.verbosePlugin` when it is verbose-only.", + badExample: "print(\"Resolved \\(resolvedPaths.count) targets\")", + goodExample: """ + if config.verbosePlugin { Diagnostics.emit(.remark, "Resolved \\(resolvedPaths.count) targets") } + """ + ) + + static let externalProductsUsePackageIdentity = Rule( + id: "external-products-use-package-identity", + title: "The plugin never reads a package's `displayName`.", + category: .output, + rationale: """ + `.product(name:package:)` needs the package identity SwiftPM derives from the URL, \ + `dependency.package.id`. `displayName` is the name a package declares for itself and can differ \ + (`VitaminPlay` for `vitamin-play-apple-releases`), which produces a `Package.swift` that does not resolve \ + (CODING_STANDARDS.md, "External products use the package identity"). + """, + howToFix: "Use `dependency.package.id`.", + badExample: "let packageIdentity = dependency.package.displayName", + goodExample: "let packageIdentity = dependency.package.id" + ) + + static let appleSDKFilteringIsDeferred = Rule( + id: "apple-sdk-filtering-is-deferred", + title: "`filterImports` does not consult `appleDefaultSDKs`.", + category: .output, + rationale: """ + 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"). + """, + howToFix: """ + Leave the import in `filterImports`' result. `renderSingleTarget` skips it once it has found no external \ + product and no local target of that name. + """, + badExample: """ + func filterImports(rawImports: [String], …) -> [String] { + rawImports.filter { !appleDefaultSDKs.contains($0) } + """, + goodExample: """ + } else if appleSDKs.contains(dep) { + // Known Apple SDK: skip silently, after externalDeps and local targets were checked. + """ + ) + + static let pluginUsesURLAPIs = Rule( + id: "plugin-uses-url-apis", + title: "The plugin uses the URL-based `PackagePlugin` APIs, not the deprecated `Path` ones.", + category: .pluginAPI, + rationale: """ + `context.package.directory`, `context.pluginWorkDirectory` and `tool.path` return the deprecated \ + `PackagePlugin.Path` and warn on every build; the `URL` variants work with Foundation directly \ + (CODING_STANDARDS.md, "URL-based PackagePlugin APIs"). + """, + howToFix: "Use `directoryURL`, `pluginWorkDirectoryURL` and `url`, then `appendingPathComponent`.", + badExample: "let packageDir = context.package.directory", + goodExample: "let packageDir = context.package.directoryURL" + ) + + static let testsUseSwiftTesting = Rule( + id: "tests-use-swift-testing", + title: "Tests use Swift Testing, never XCTest.", + category: .testing, + rationale: """ + The suite is Swift Testing only (CODING_STANDARDS.md, "Swift Testing only"): `@Test`, `#expect` and \ + `#require` give one failure message style, parameterised tests and parallel, randomly ordered runs. + """, + howToFix: "Write an `@Suite` of `@Test` functions with `#expect` and `#require`, and `import Testing`.", + badExample: """ + import XCTest + final class ProductTests: XCTestCase { func testName() { XCTAssertEqual(…) } } + """, + goodExample: """ + import Testing + @Suite struct ProductTests { @Test func name() { #expect(…) } } + """ + ) + + static let testsAreNotDisabled = Rule( + id: "tests-are-not-disabled", + title: "No test or suite is `.disabled`.", + category: .testing, + rationale: """ + A disabled test still reads as coverage while checking nothing. A failing behaviour is either fixed, or \ + asserted as a known issue that says why. + """, + howToFix: "Fix the code or the test. If the bug must wait, wrap the failing part in `withKnownIssue(\"…\")`.", + badExample: "@Test(.disabled(\"flaky\")) func rendersProducts() {", + goodExample: "@Test func rendersProducts() {" + ) +} + +/// Every rule, in the order `docs/architecture-rules.md` lists them. +let allRules: [Rule] = [ + .testSourcesLinkThePluginFiles, .coreFilesImportOnlyFoundation, .pluginReportsThroughDiagnostics, + .externalProductsUsePackageIdentity, .appleSDKFilteringIsDeferred, .pluginUsesURLAPIs, + .testsUseSwiftTesting, .testsAreNotDisabled, +] diff --git a/Architecture/Tests/ArchitectureTests/Support.swift b/Architecture/Tests/ArchitectureTests/Support.swift new file mode 100644 index 0000000..dc8240e --- /dev/null +++ b/Architecture/Tests/ArchitectureTests/Support.swift @@ -0,0 +1,55 @@ +import Foundation +import LLMCheck + +/// The PackageGeneratorPlugin repository, rooted where `.llm-check.yaml` is. Its file list and every parsed file are +/// 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" + +/// A Swift file in `sharedTestSourcesFolder`, 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 `sharedTestSourcesFolder` of `codebase`, read from the file system: `Codebase` excludes the + /// folder 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: "") + } + return SharedSource(relativePath: "\(sharedTestSourcesFolder)/\(name)", destination: destination) + } + } +} + +extension RuleCategory { + static let structure = RuleCategory( + "structure", + description: "The pure core and the plugin shell. Read before you add an `import` or a file to `Plugins`." + ) + static let output = RuleCategory( + "output", + description: "What ends up in the generated `Package.swift`. Read before you change dependency resolution." + ) + static let pluginAPI = RuleCategory( + "plugin-api", + description: "How the plugin talks to SwiftPM. Read before you use a `PackagePlugin` API." + ) + static let testing = RuleCategory( + "testing", + description: "Swift Testing, and no silenced tests. Read before you add or skip a test." + ) +} diff --git a/CODING_STANDARDS.md b/CODING_STANDARDS.md new file mode 100644 index 0000000..120ccb2 --- /dev/null +++ b/CODING_STANDARDS.md @@ -0,0 +1,46 @@ +# Coding standards + +Read during review. The mechanical part is enforced by the `Architecture/` package (see +[docs/architecture-rules.md](docs/architecture-rules.md)); the rest is judgement. + +## Shape of the plugin + +- **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. +- **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 + 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. +- **Swift 6 language mode.** All code compiles under strict concurrency (`swiftLanguageModes: [.v6]`). + +## Behaviour that users rely on + +- **Output is deterministic.** The same config and imports give byte-for-byte the same `Package.swift`: products and + targets are sorted, dependencies are sorted before `additionalDependencies` are appended. +- **Config strings are verbatim.** `parameters` and `additionalDependencies` are written into `Package.swift` as + given, trimmed but never parsed or rewritten. +- **Apple SDK filtering happens at render time.** `filterImports` drops only self-imports and explicit exclusions. + `renderSingleTarget` looks an import up in the external products first, then the local targets, and only then in + `appleDefaultSDKs`, so a package product named like an SDK (`Charts`) is never dropped. +- **External products use the package identity.** `.product(name:package:)` takes `dependency.package.id`, the + URL-derived identity SwiftPM resolves, never `displayName`. +- **URL-based PackagePlugin APIs.** `context.package.directoryURL`, `context.pluginWorkDirectoryURL`, `tool.url`; + never the deprecated `Path` APIs. +- **Old configs keep working.** A new config key is optional with a default that reproduces today's output; legacy + keys (`targetsParameters`, boolean `verbose`) are migrated in memory, never on disk. Document new keys in + `README.md` and, when they replace an old one, in `MIGRATION.md`. + +## Reporting + +- **Diagnostics, not print.** The plugin reports through `Diagnostics.emit`; `print` output is lost in Xcode. + Verbose-only messages check `config.verbosePlugin`. + +## Tests + +- **Swift Testing only.** `@Suite`, `@Test`, `#expect`, `#require`; no XCTest, no disabled tests. +- **Test the rendered text.** Assert on the generated `Package.swift` lines, which is what users see. diff --git a/docs/architecture-rules.md b/docs/architecture-rules.md new file mode 100644 index 0000000..7d425c6 --- /dev/null +++ b/docs/architecture-rules.md @@ -0,0 +1,171 @@ +# Architecture rules + +The mechanical part of `CODING_STANDARDS.md`, enforced by the `Architecture/` package with [swift-llm-check](https://github.com/mackoj/swift-llm-check): `swift test --package-path Architecture` (macOS). Generated from its rules; do not edit by hand. + +## structure + +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`. + +`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. + +**How to fix:** Replace the file with a relative link: `ln -s ../../../Plugins/PackageGenerator/Name.swift Tests/PackageGeneratorTests/Shared/Name.swift`. + +Bad: + +```swift +cp Plugins/PackageGenerator/ParsedPackage.swift Tests/PackageGeneratorTests/Shared/ +``` + +Good: + +```swift +Shared/ParsedPackage.swift -> ../../../Plugins/PackageGenerator/ParsedPackage.swift +``` + +### 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. + +**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`). + +Bad: + +```swift +// Plugins/PackageGenerator/ProductGeneration.swift +import PackagePlugin +Diagnostics.emit(.warning, "Dropped unresolved import '\(dep)'") +``` + +Good: + +```swift +// Plugins/PackageGenerator/ProductGeneration.swift +import Foundation +func render(_ target: ParsedPackage, warn: (String) -> Void) -> String +``` + +### The plugin reports through `Diagnostics.emit`, never `print`. + +`plugin-reports-through-diagnostics`: A command plugin's standard output is not shown in Xcode's issue navigator, and in a terminal it mixes with SwiftPM's own output. `Diagnostics` gives every message a severity users can filter (CODING_STANDARDS.md, "Diagnostics, not print"). + +**How to fix:** Call `Diagnostics.emit(.remark, …)`, guarded by `config.verbosePlugin` when it is verbose-only. + +Bad: + +```swift +print("Resolved \(resolvedPaths.count) targets") +``` + +Good: + +```swift +if config.verbosePlugin { Diagnostics.emit(.remark, "Resolved \(resolvedPaths.count) targets") } +``` + +## output + +What ends up in the generated `Package.swift`. Read before you change dependency resolution. + +### The plugin never reads a package's `displayName`. + +`external-products-use-package-identity`: `.product(name:package:)` needs the package identity SwiftPM derives from the URL, `dependency.package.id`. `displayName` is the name a package declares for itself and can differ (`VitaminPlay` for `vitamin-play-apple-releases`), which produces a `Package.swift` that does not resolve (CODING_STANDARDS.md, "External products use the package identity"). + +**How to fix:** Use `dependency.package.id`. + +Bad: + +```swift +let packageIdentity = dependency.package.displayName +``` + +Good: + +```swift +let packageIdentity = dependency.package.id +``` + +### `filterImports` does not consult `appleDefaultSDKs`. + +`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"). + +**How to fix:** Leave the import in `filterImports`' result. `renderSingleTarget` skips it once it has found no external product and no local target of that name. + +Bad: + +```swift +func filterImports(rawImports: [String], …) -> [String] { + rawImports.filter { !appleDefaultSDKs.contains($0) } +``` + +Good: + +```swift +} else if appleSDKs.contains(dep) { + // Known Apple SDK: skip silently, after externalDeps and local targets were checked. +``` + +## plugin-api + +How the plugin talks to SwiftPM. Read before you use a `PackagePlugin` API. + +### The plugin uses the URL-based `PackagePlugin` APIs, not the deprecated `Path` ones. + +`plugin-uses-url-apis`: `context.package.directory`, `context.pluginWorkDirectory` and `tool.path` return the deprecated `PackagePlugin.Path` and warn on every build; the `URL` variants work with Foundation directly (CODING_STANDARDS.md, "URL-based PackagePlugin APIs"). + +**How to fix:** Use `directoryURL`, `pluginWorkDirectoryURL` and `url`, then `appendingPathComponent`. + +Bad: + +```swift +let packageDir = context.package.directory +``` + +Good: + +```swift +let packageDir = context.package.directoryURL +``` + +## testing + +Swift Testing, and no silenced tests. Read before you add or skip a test. + +### Tests use Swift Testing, never XCTest. + +`tests-use-swift-testing`: The suite is Swift Testing only (CODING_STANDARDS.md, "Swift Testing only"): `@Test`, `#expect` and `#require` give one failure message style, parameterised tests and parallel, randomly ordered runs. + +**How to fix:** Write an `@Suite` of `@Test` functions with `#expect` and `#require`, and `import Testing`. + +Bad: + +```swift +import XCTest +final class ProductTests: XCTestCase { func testName() { XCTAssertEqual(…) } } +``` + +Good: + +```swift +import Testing +@Suite struct ProductTests { @Test func name() { #expect(…) } } +``` + +### No test or suite is `.disabled`. + +`tests-are-not-disabled`: A disabled test still reads as coverage while checking nothing. A failing behaviour is either fixed, or asserted as a known issue that says why. + +**How to fix:** Fix the code or the test. If the bug must wait, wrap the failing part in `withKnownIssue("…")`. + +Bad: + +```swift +@Test(.disabled("flaky")) func rendersProducts() { +``` + +Good: + +```swift +@Test func rendersProducts() { +``` From ffaf8212b2d54063a144e8406e2d5d493db115d7 Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 02:39:28 +0100 Subject: [PATCH 2/2] Run CI on macos-26 for Swift 6.2 tools --- .github/workflows/ci.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 985e5d0..c81956b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,7 +16,8 @@ jobs: macos: name: macOS # package-generator-cli ships as an arm64 macOS binary, so the plugin builds on Apple silicon only. - runs-on: macos-15 + # Package.swift needs tools 6.2 (Xcode 26), the default on macos-26. + runs-on: macos-26 steps: - uses: actions/checkout@v4 with: