Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
32 changes: 32 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
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.
# Package.swift needs tools 6.2 (Xcode 26), the default on macos-26.
runs-on: macos-26
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
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
12 changes: 12 additions & 0 deletions .llm-check.yaml
Original file line number Diff line number Diff line change
@@ -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]
23 changes: 23 additions & 0 deletions Architecture/Package.swift
Original file line number Diff line number Diff line change
@@ -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"),
]
)
]
)
69 changes: 69 additions & 0 deletions Architecture/Tests/ArchitectureTests/ArchitectureRules.swift
Original file line number Diff line number Diff line change
@@ -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.
"""))
}
73 changes: 73 additions & 0 deletions Architecture/Tests/ArchitectureTests/Detect.swift
Original file line number Diff line number Diff line change
@@ -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<ImportDeclSyntax>] {
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<FunctionCallExprSyntax>] {
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<MemberAccessExprSyntax>] {
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<MemberAccessExprSyntax>] {
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<Syntax>] {
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<ImportDeclSyntax>] {
scope.imports(of: "XCTest")
}

/// The `.disabled(…)` trait, wherever a test or suite takes it.
static func disabledTests(in scope: Scope) -> [Match<FunctionCallExprSyntax>] {
scope.calls(named: "disabled").filter { call in
call.node.receiver == nil && call.node.calledExpression.is(MemberAccessExprSyntax.self)
}
}

private static func memberAccesses(named names: Set<String>, in scope: Scope) -> [Match<MemberAccessExprSyntax>] {
scope.containing(Array(names)).nodes(of: MemberAccessExprSyntax.self) {
$0.node.base != nil && names.contains($0.node.declName.baseName.text)
}
}
}
99 changes: 99 additions & 0 deletions Architecture/Tests/ArchitectureTests/DetectorTests.swift
Original file line number Diff line number Diff line change
@@ -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])
}
}
Loading
Loading