diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml new file mode 100644 index 0000000..a253ebe --- /dev/null +++ b/.github/actionlint.yaml @@ -0,0 +1,5 @@ +# Every job runs on GitHub-hosted runners. +self-hosted-runner: + labels: [] +# The repository defines no configuration variables, so any `vars.*` reference is a typo. +config-variables: [] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..80d9a68 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,52 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + host: + name: macOS host + runs-on: macos-15 + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + # Everything is simulator-only, so this builds an empty module: it checks the package and its guards. + - name: Build + run: swift build --build-tests + - name: Test + run: swift test + - name: Architecture rules + run: swift test --package-path Architecture + + simulators: + name: Simulators + runs-on: macos-15 + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Test on an iOS simulator + run: | + udid=$(xcrun simctl list devices available --json \ + | jq -r '[.devices | to_entries[] | select(.key | contains("iOS")) | .value[] | select(.name | startswith("iPhone"))][0].udid') + echo "Testing on $udid" + xcodebuild test -scheme EnvironmentVariationPreview -destination "id=$udid" -quiet + - name: Build for tvOS, watchOS and visionOS simulators + run: | + for platform in "tvOS Simulator" "watchOS Simulator" "visionOS Simulator"; do + echo "::group::$platform" + xcodebuild build -scheme EnvironmentVariationPreview -destination "generic/platform=$platform" -quiet + echo "::endgroup::" + done 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/.github/workflows/soundness.yml b/.github/workflows/soundness.yml new file mode 100644 index 0000000..b3410ac --- /dev/null +++ b/.github/workflows/soundness.yml @@ -0,0 +1,43 @@ +name: Soundness + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + actionlint: + name: Workflow lint + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Run actionlint + run: pipx run --spec actionlint-py==1.7.12.25 actionlint + + zizmor: + name: Workflow security audit + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Run zizmor + env: + # Online audits (impostor commits, known-vulnerable actions) read public repositories. + GH_TOKEN: ${{ github.token }} + run: pipx run --spec zizmor==1.30.1 zizmor --format github .github/workflows diff --git a/.github/zizmor.yml b/.github/zizmor.yml new file mode 100644 index 0000000..85df1f9 --- /dev/null +++ b/.github/zizmor.yml @@ -0,0 +1,6 @@ +rules: + unpinned-uses: + config: + policies: + # Setting policies replaces zizmor's defaults, so keep the default for GitHub's own actions. + "actions/*": ref-pin diff --git a/.gitignore b/.gitignore index 3b29812..62c7a46 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ .DS_Store -/.build +.build/ /Packages /*.xcodeproj xcuserdata/ @@ -7,3 +7,5 @@ DerivedData/ .swiftpm/config/registries.json .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata .netrc +/Architecture/Package.resolved +/Benchmarks/Package.resolved diff --git a/.llm-check.yaml b/.llm-check.yaml new file mode 100644 index 0000000..82e58a9 --- /dev/null +++ b/.llm-check.yaml @@ -0,0 +1,9 @@ +# 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 + - site +# Folders ending in Tests hold test code. +testSuffixes: [Tests] diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..b69cbb1 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,30 @@ +# Agent notes + +`EnvironmentVariationPreview` is a SwiftUI library, not an app: one view modifier, `.environmentVariations([...])`, +that renders a view once per environment value (color scheme, dynamic type, layout direction, locale…) with a caption. +It compiles only for the simulator. Usage is in `README.md`. + +Read `CODING_STANDARDS.md` before writing code. + +## How to work +- **Smallest diff.** Every changed line traces to the request. Match the surrounding file's idioms (two-space indent, + DocC comments on public API). +- **Test first.** A bug gets a failing test; a new environment value gets a description test. +- A new environment value is a new `EnvironmentValueItem` case plus its branch in `apply(to:)` and in `description`. + +## Docs travel with code +- `README.md` is the user documentation; DocC comments are the API reference (Swift Package Index, see `.spi.yml`). +- `site/index.html` is the landing page (GitHub Pages, `.github/workflows/pages.yml`). Its code samples and install + snippet repeat the README: update them in the same change. + +## Build and test +- Host: `swift build --build-tests && swift test` builds an empty module (everything is simulator-only), which checks + the package resolves and the guards are intact. +- Simulator: `xcodebuild test -scheme EnvironmentVariationPreview -destination 'platform=iOS Simulator,name='` + runs the real tests. CI also builds for tvOS, watchOS and visionOS simulators. +- Architecture rules: `swift test --package-path Architecture` (macOS only) runs the mechanical part of + `CODING_STANDARDS.md` as [swift-llm-check](https://github.com/mackoj/swift-llm-check) rules, listed in + `docs/architecture-rules.md`. A failure prints the rule, why it exists and how to fix it: fix the code, never add a + baseline. A new or changed rule needs a `DetectorTests` case and + `LLM_CHECK_RECORD=1 swift test --package-path Architecture` to regenerate the document. +- Releases: tags are bare semver (`1.1.4`, no `v`), created with `gh release create`. diff --git a/Architecture/Package.swift b/Architecture/Package.swift new file mode 100644 index 0000000..c986db9 --- /dev/null +++ b/Architecture/Package.swift @@ -0,0 +1,23 @@ +// swift-tools-version: 6.0 +import PackageDescription + +// EnvironmentVariationPreview's mechanical rules (CODING_STANDARDS.md) as tests, written with swift-llm-check. +// Test-only and macOS-only, so the library never builds it and its swift-tools-version 5.7.1 floor is unaffected. +// 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.5.0"), + .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..8ce8e54 --- /dev/null +++ b/Architecture/Tests/ArchitectureTests/ArchitectureRules.swift @@ -0,0 +1,61 @@ +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 sources() throws -> Scope { try repository().productionCode.in("/Sources") } + + @Test func sourcesAreSimulatorOnly() throws { + let sources = try Self.sources() + #expect(sources.relativePaths.count > 5) + expectNone(sources.topLevelStatements(notUnder: "targetEnvironment(simulator)"), rule: .sourcesAreSimulatorOnly) + } + + @Test func importsStayWithinBudget() throws { + expectNone(Detect.importsOverBudget(in: try Self.sources()), rule: .importsStayWithinBudget) + } + + @Test func availabilityNamesThePackageFloor() throws { + let found = Detect.availabilityOffTheFloor(in: try Self.sources(), floor: packageFloor) + expectNone(found, rule: .availabilityNamesThePackageFloor) + } + + @Test func publicTypesDeclareAvailability() throws { + let sources = try Self.sources() + #expect(sources.declarations.withModifier("public").count > 10) + expectNone(Detect.publicDeclarationsWithoutAvailability(in: sources), rule: .publicTypesDeclareAvailability) + } + + @Test func anyViewStaysInApply() throws { + let sources = try Self.sources() + #expect(sources.references(to: "AnyView").count > 40) + expectNone(Detect.anyViewOutsideApply(in: sources), rule: .anyViewStaysInApply) + } + + @Test func erasedPayloadsNameTheirType() throws { + expectNone(Detect.erasedPayloadsWithoutTypeComment(in: try Self.sources()), rule: .erasedPayloadsNameTheirType) + } + + @Test func descriptionsNameTheirCase() throws { + let sources = try Self.sources() + #expect(sources.containing("var description").relativePaths.count >= 2) + expectNone(Detect.descriptionsNamingAnotherCase(in: sources), rule: .descriptionsNameTheirCase) + } +} + +/// 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..ab2c98b --- /dev/null +++ b/Architecture/Tests/ArchitectureTests/Detect.swift @@ -0,0 +1,99 @@ +import Foundation +import LLMCheck +import SwiftSyntax + +/// The detectors, separate from the codebase so `DetectorTests` can run them on snippets. +enum Detect { + /// What the library may import. + static let allowedModules: Set = ["Foundation", "SwiftUI", "CoreData"] + + /// Imports of any other module. + static func importsOverBudget(in scope: Scope) -> [Match] { + scope.imports.filter { !allowedModules.contains($0.node.moduleName) } + } + + /// Platform names that make an `@available` a statement about the floor. + static let platformNames = ["iOS", "macOS", "tvOS", "watchOS", "visionOS", "macCatalyst"] + + /// `@available(…)` attributes that name a platform but not exactly the package floor. + static func availabilityOffTheFloor(in scope: Scope, floor: String) -> [Match] { + scope.containing("@available").nodes(of: AttributeSyntax.self) { match in + guard match.node.attributeName.trimmedDescription == "available", + let arguments = match.node.arguments?.trimmedDescription + else { return false } + let namesPlatform = arguments.split(whereSeparator: { !$0.isLetter }).contains { + platformNames.contains(String($0)) + } + return namesPlatform && arguments != floor + } + } + + /// Public types without `@available`, and public members of extensions when neither has it. + static func publicDeclarationsWithoutAvailability(in scope: Scope) -> [Declaration] { + scope.declarations.filter { declaration in + guard declaration.isPublic, !declaration.hasAttribute("available") else { return false } + switch declaration.kind { + case .struct, .class, .enum, .actor, .protocol: + return true + case .function, .initializer, .variable: + guard let parent = declaration.parent, parent.kind == .extension else { return false } + return !parent.hasAttribute("available") + default: + return false + } + } + } + + /// `AnyView` anywhere but inside `EnvironmentValueItem.apply`. + static func anyViewOutsideApply(in scope: Scope) -> [Match] { + scope.references(to: "AnyView").filter { !$0.declarationNames.contains("EnvironmentValueItem.apply") } + } + + /// Enum cases with an `Any` or `Any?` parameter and no `// TypeName` comment after them on the same line. A type + /// name is UpperCamelCase, so `// TODO` is not one. + static func erasedPayloadsWithoutTypeComment(in scope: Scope) -> [Match] { + scope.containing("case").nodes(of: EnumCaseDeclSyntax.self) { match in + let erased = match.node.elements.contains { element in + element.parameterClause?.parameters.contains { + ["Any", "Any?"].contains($0.type.trimmedDescription) + } ?? false + } + guard erased else { return false } + let trailing = match.node.lastToken(viewMode: .sourceAccurate)?.trailingTrivia ?? [] + return !trailing.contains { piece in + guard case .lineComment(let text) = piece else { return false } + let name = text.dropFirst(2).trimmingCharacters(in: .whitespaces) + return name.first?.isUppercase == true && name.contains(where: \.isLowercase) + && name.allSatisfy { $0.isLetter || $0.isNumber || $0 == "." } + } + } + } + + /// In the `switch` of a `description` property, `case .name(…)` whose first string literal does not start with + /// `"name: "`. Cases without a payload (`case .regular:`) are not checked. + static func descriptionsNamingAnotherCase(in scope: Scope) -> [Match] { + scope.containing("description").nodes(of: SwitchCaseSyntax.self) { match in + guard isInDescription(match.node), let name = payloadCaseName(match.node) else { return false } + guard let literal = match.node.statements.firstDescendant(of: StringLiteralExprSyntax.self), + let first = literal.segments.first?.as(StringSegmentSyntax.self) + else { return true } + return !first.content.text.hasPrefix("\(name): ") + } + } + + private static func isInDescription(_ node: some SyntaxProtocol) -> Bool { + sequence(first: Syntax(node), next: \.parent).contains { + $0.as(PatternBindingSyntax.self)?.pattern.trimmedDescription == "description" + } + } + + /// `name` for `case .name(let value):`; nil for anything else. + private static func payloadCaseName(_ node: SwitchCaseSyntax) -> String? { + guard let item = node.label.as(SwitchCaseLabelSyntax.self)?.caseItems.first, + let pattern = item.pattern.as(ExpressionPatternSyntax.self), + let call = pattern.expression.as(FunctionCallExprSyntax.self), + let member = call.calledExpression.as(MemberAccessExprSyntax.self), member.base == nil + else { return nil } + return member.declName.baseName.text + } +} diff --git a/Architecture/Tests/ArchitectureTests/DetectorTests.swift b/Architecture/Tests/ArchitectureTests/DetectorTests.swift new file mode 100644 index 0000000..23752da --- /dev/null +++ b/Architecture/Tests/ArchitectureTests/DetectorTests.swift @@ -0,0 +1,123 @@ +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 = "Sources/EnvironmentVariationPreview/File.swift") -> Scope { + Scope(files: [SourceFile(path: path, source: source)]) + } + + @Test func importsOverBudgetAreFound() { + let found = Detect.importsOverBudget( + in: scope( + """ + import Foundation + import SwiftUI + import CoreData + import UIKit + @testable import Combine + """)) + #expect(found.map(\.location.line) == [4, 5]) + } + + @Test func availabilityOffTheFloorIsFound() { + let found = Detect.availabilityOffTheFloor( + in: scope( + """ + @available(iOS 13.0, *) + extension A {} + @available(iOS 14.0, macOS 11.0, *) + struct B {} + @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) + struct C {} + @available(*, deprecated, renamed: "d") + func e() {} + """), + floor: "iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *") + #expect(found.map(\.location.line) == [1, 3]) + } + + @Test func publicDeclarationsWithoutAvailabilityAreFound() { + let found = Detect.publicDeclarationsWithoutAvailability( + in: scope( + """ + public struct A { + public init() {} + } + @available(iOS 14.0, *) + public enum B {} + extension View { + public func c() {} + @available(iOS 14.0, *) + public func d() {} + func e() {} + } + @available(iOS 14.0, *) + extension B { + public var f: Int { 0 } + } + struct G {} + """)) + #expect(found.map(\.name) == ["A", "c"]) + } + + @Test func anyViewOutsideApplyIsFound() { + let found = Detect.anyViewOutsideApply( + in: scope( + """ + enum EnvironmentValueItem { + func apply(to content: V) -> some View { AnyView(content) } + } + struct Modifier: ViewModifier { + func body(content: Content) -> some View { AnyView(content) } + } + """)) + #expect(found.map(\.location.line) == [5]) + } + + @Test func erasedPayloadsWithoutCommentAreFound() { + let found = Detect.erasedPayloadsWithoutTypeComment( + in: scope( + """ + enum EnvironmentValueItem { + case dynamicTypeSize(Any) // DynamicTypeSize + case symbolRenderingMode(Any?) // SymbolRenderingMode + case controlSize(Any) + case menuOrder(Any) // TODO + case editMode(Binding?) + case colorScheme(ColorScheme) + } + """)) + #expect(found.map(\.location.line) == [4, 5]) + } + + @Test func descriptionsNamingAnotherCaseAreFound() { + let found = Detect.descriptionsNamingAnotherCase( + in: scope( + """ + enum EnvironmentValueItem { + var description: String { + switch self { + case .colorScheme(let value): return "colorScheme: \\(value)" + case .verticalSizeClass(let value): return "horizontalSizeClass: \\(value)" + case .font(let value): return "font \\(value)" + case .locale(let value): return String(describing: value) + } + } + var title: String { + switch self { + case .colorScheme(let value): return "anything" + } + } + } + extension LegibilityWeight { + public var description: String { + switch self { + case .regular: return "regular" + } + } + } + """)) + #expect(found.map(\.location.line) == [5, 6, 7]) + } +} diff --git a/Architecture/Tests/ArchitectureTests/Rules.swift b/Architecture/Tests/ArchitectureTests/Rules.swift new file mode 100644 index 0000000..a869394 --- /dev/null +++ b/Architecture/Tests/ArchitectureTests/Rules.swift @@ -0,0 +1,138 @@ +import LLMCheck + +extension Rule { + static let sourcesAreSimulatorOnly = Rule( + id: "sources-are-simulator-only", + title: "Every file in `Sources` is wrapped, whole, in `#if targetEnvironment(simulator)`.", + category: .platforms, + rationale: """ + EnvironmentVariationPreview is a preview tool (CODING_STANDARDS.md, "Simulator only"): apps link it \ + from their UI modules, so whatever it compiles on a device ships in the App Store binary. Wrapping every \ + file keeps device and Mac builds empty, so the library costs nothing outside the simulator and the \ + canvas. A declaration outside the guard is compiled, and shipped, everywhere. + """, + howToFix: """ + Put the whole file, imports included, between `#if targetEnvironment(simulator)` on the first line and \ + `#endif` on the last, with no `#else`, like `Sources/EnvironmentVariationPreview/EnvironmentVariations.swift`. + """, + badExample: """ + import Foundation + + extension Locale { … } + """, + goodExample: """ + #if targetEnvironment(simulator) + import Foundation + + extension Locale { … } + #endif + """ + ) + + static let importsStayWithinBudget = Rule( + id: "imports-stay-within-budget", + title: "The library imports only Foundation, SwiftUI and CoreData.", + category: .platforms, + rationale: """ + The package has no dependencies and must build on every platform it lists (CODING_STANDARDS.md, \ + "No dependencies"). CoreData is there for the `managedObjectContext` environment value; UIKit or AppKit \ + would tie a file to one platform, and any other module is a new dependency for every client. + """, + howToFix: """ + Use SwiftUI or Foundation API. If an environment value needs a platform framework, wrap the case and its \ + import in `#if canImport(…)` and add the module to this rule's budget in the same pull request. + """, + badExample: "import UIKit", + goodExample: "import SwiftUI" + ) + + static let availabilityNamesThePackageFloor = Rule( + id: "availability-names-the-package-floor", + title: "Every `@available` that names platforms names the package floor: iOS 14, macOS 11, tvOS 14, watchOS 7.", + category: .platforms, + rationale: """ + The `platforms` in `Package.swift` are the floor, and the `@available` attributes repeat it so the DocC \ + pages and Xcode's quick help say where each API works. One attribute with another floor, such as \ + `@available(iOS 13.0, *)`, documents a version the package cannot be used on and forgets the other \ + platforms. Newer APIs are reached with `if #available` inside `EnvironmentValueItem.apply`, not with a \ + higher `@available` (CODING_STANDARDS.md, "One availability floor"). + """, + howToFix: "Write `@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)` exactly.", + badExample: "@available(iOS 13.0, *)\nextension LegibilityWeight: CustomStringConvertible {", + goodExample: """ + @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) + extension LegibilityWeight: CustomStringConvertible { + """ + ) + + static let publicTypesDeclareAvailability = Rule( + id: "public-types-declare-availability", + title: "A public type, or a public member of an extension, carries `@available` itself or through its extension.", + category: .platforms, + rationale: """ + Without the attribute, DocC and quick help show the declaration as available everywhere, and the floor \ + in the generated documentation drifts from `Package.swift` (CODING_STANDARDS.md, "One availability \ + floor"). Members of a type that has the attribute inherit it. + """, + howToFix: "Add `@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)` to the type, extension or member.", + badExample: """ + extension View { + public func environmentVariations(_ variarions: EnvironmentValueItemList) -> some View { + """, + goodExample: """ + extension View { + @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) + public func environmentVariations(_ variarions: EnvironmentValueItemList) -> some View { + """ + ) + + static let anyViewStaysInApply = Rule( + id: "any-view-stays-in-apply", + title: "`AnyView` appears only in `EnvironmentValueItem.apply(to:)`.", + category: .environmentValues, + rationale: """ + `apply(to:)` returns a different `.environment` type per case, and Swift's result builders cannot \ + return them from one `switch` without erasing, so that one function erases (CODING_STANDARDS.md, \ + "Type erasure in one place"). Anywhere else `AnyView` hides the view's identity from SwiftUI's diffing \ + and is avoidable with `some View` or `@ViewBuilder`. + """, + howToFix: "Return `some View`, or mark the function `@ViewBuilder` and let it build a `_ConditionalContent`.", + badExample: "func body(content: Content) -> some View { AnyView(content.padding()) }", + goodExample: "func body(content: Content) -> some View { content.padding() }" + ) + + static let erasedPayloadsNameTheirType = Rule( + id: "erased-payloads-name-their-type", + title: "An `EnvironmentValueItem` case whose payload is `Any` or `Any?` names the real type in a trailing comment.", + category: .environmentValues, + rationale: """ + Types newer than the floor, such as `DynamicTypeSize` (iOS 15), cannot appear in a case of an enum \ + available on iOS 14, so their payload is `Any` and `apply(to:)` casts it back under `if #available` \ + (CODING_STANDARDS.md, "Newer types as Any"). The comment is the only place that says what the cast \ + expects; a caller who passes anything else gets the content back unchanged, silently. + """, + howToFix: "End the case with `// TypeName`, the SwiftUI type that `apply(to:)` casts the payload to.", + badExample: "case dynamicTypeSize(Any)", + goodExample: "case dynamicTypeSize(Any) // DynamicTypeSize" + ) + + static let descriptionsNameTheirCase = Rule( + id: "descriptions-name-their-case", + title: "In a `description` switch, the string for `.name(let value)` starts with `\"name: \"`.", + category: .environmentValues, + rationale: """ + The description is the caption under each variation in the preview canvas, and the only thing that \ + tells two otherwise identical renders apart. A caption that names another case, such as one copied \ + from the line above, labels the screenshot wrong (CODING_STANDARDS.md, "Captions name the case"). + """, + howToFix: "Start the string with the case's name, a colon and a space, then interpolate the payload.", + badExample: "case .verticalSizeClass(let value): return \"horizontalSizeClass: \\(value.debugDescription)\"", + goodExample: "case .verticalSizeClass(let value): return \"verticalSizeClass: \\(value.debugDescription)\"" + ) +} + +/// Every rule, in the order `docs/architecture-rules.md` lists them. +let allRules: [Rule] = [ + .sourcesAreSimulatorOnly, .importsStayWithinBudget, .availabilityNamesThePackageFloor, + .publicTypesDeclareAvailability, .anyViewStaysInApply, .erasedPayloadsNameTheirType, .descriptionsNameTheirCase, +] diff --git a/Architecture/Tests/ArchitectureTests/Support.swift b/Architecture/Tests/ArchitectureTests/Support.swift new file mode 100644 index 0000000..f2027b9 --- /dev/null +++ b/Architecture/Tests/ArchitectureTests/Support.swift @@ -0,0 +1,22 @@ +import LLMCheck + +/// The EnvironmentVariationPreview 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() } + +/// The availability every public declaration names: the `platforms` floor in `Package.swift`. +let packageFloor = "iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *" + +extension RuleCategory { + static let platforms = RuleCategory( + "platforms", + description: """ + Simulator-only code, imports and availability. Read before you add a file, an `import` or an \ + `@available` to `Sources`. + """ + ) + static let environmentValues = RuleCategory( + "environment-values", + description: "`EnvironmentValueItem` and how it is applied. Read before you add or change an environment value." + ) +} diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/CODING_STANDARDS.md b/CODING_STANDARDS.md new file mode 100644 index 0000000..66d6cc3 --- /dev/null +++ b/CODING_STANDARDS.md @@ -0,0 +1,44 @@ +# Coding standards + +The conventions this library already follows, written down so a change keeps them. The mechanical ones are enforced +by the `Architecture/` package (`swift test --package-path Architecture`); see `docs/architecture-rules.md`. + +## Simulator only + +EnvironmentVariationPreview exists for SwiftUI previews and snapshot tests. Every file in `Sources` is wrapped, whole, +in `#if targetEnvironment(simulator)` … `#endif`, so device and Mac builds compile an empty module and an app that links +the library ships none of it. Tests are wrapped the same way and run on an iOS simulator. + +## No dependencies + +The package depends on nothing. The library imports Foundation, SwiftUI and CoreData (for `managedObjectContext`) +only. A platform framework (UIKit, AppKit) would tie a file to one platform. + +## One availability floor + +`Package.swift` sets the floor: iOS 14, macOS 11, tvOS 14, watchOS 7. Every public type, and every public member of +an extension, carries `@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)`, exactly. An API newer than the +floor is reached with `if #available` inside `EnvironmentValueItem.apply(to:)`, which falls back to the unchanged +content. + +## Newer types as `Any` + +An environment value whose type is newer than the floor (`DynamicTypeSize`, `Material`, `MenuOrder`…) cannot appear in +a case of an enum available on iOS 14. Its case takes `Any` (or `Any?`) and names the real type in a trailing comment: +`case dynamicTypeSize(Any) // DynamicTypeSize`. `apply(to:)` casts it back under `if #available`. + +## Type erasure in one place + +`EnvironmentValueItem.apply(to:)` returns a different `.environment` type per case, so it erases with `AnyView`. That +is the only `AnyView` in the library; everything else returns `some View`. + +## Captions name the case + +`EnvironmentValueItem.description` is the caption under each variation. The string for `.name(let value)` starts with +`"name: "`, followed by the value. + +## Style + +Two-space indentation, as in the existing files. Public API has a DocC comment (Swift Package Index builds the +documentation, see `.spi.yml`). The package keeps `swift-tools-version: 5.7.1`: `Architecture/` and `Benchmarks/` are +separate packages so they can use newer tools without raising it. Tests use XCTest, which every supported toolchain has. diff --git a/README.md b/README.md index 20a9835..9e2bb14 100644 --- a/README.md +++ b/README.md @@ -1,83 +1,115 @@ +[![CI](https://github.com/mackoj/EnvironmentVariationPreview/actions/workflows/ci.yml/badge.svg)](https://github.com/mackoj/EnvironmentVariationPreview/actions/workflows/ci.yml) [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fmackoj%2FEnvironmentVariationPreview%2Fbadge%3Ftype%3Dswift-versions)](https://swiftpackageindex.com/mackoj/EnvironmentVariationPreview) [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fmackoj%2FEnvironmentVariationPreview%2Fbadge%3Ftype%3Dplatforms)](https://swiftpackageindex.com/mackoj/EnvironmentVariationPreview) # EnvironmentVariationPreview -EnvironmentVariationPreview is a SwiftUI library designed to simplify the process of previewing your SwiftUI views in a variety of environments. The code of this library work exclusively with the simulator. +**[Website](https://mackoj.github.io/EnvironmentVariationPreview/)** · +**[Architecture rules](docs/architecture-rules.md)** · +**[Performance](docs/performance.md)** + +One SwiftUI view modifier, `.environmentVariations([...])`, that renders a view once per environment value, side by +side and captioned: light and dark, right-to-left, the smallest and largest dynamic type, any locale, and 30 more +environment values. It compiles only for the simulator, so it ships nothing in your app. | video | image | | --- | --- | -|