diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 195d66a..2dcca15 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,6 +29,10 @@ jobs: run: scripts/smoke-test.sh - name: Architecture rules run: swift test --package-path Architecture + - name: Build benchmarks + env: + BENCHMARK_DISABLE_JEMALLOC: "true" + run: swift build --package-path Benchmarks actionlint: name: Workflow lint diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml new file mode 100644 index 0000000..96b1f62 --- /dev/null +++ b/.github/workflows/pages.yml @@ -0,0 +1,41 @@ +name: Pages + +# Publishes site/, the plugin'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/.llm-check.yaml b/.llm-check.yaml index c8d3586..82e58a9 100644 --- a/.llm-check.yaml +++ b/.llm-check.yaml @@ -5,7 +5,5 @@ excludes: - Benchmarks - docs - site - # Symlink to Plugins/SchemeGeneratorPlugin/Core, read once at its real path. - - Tests/SchemeGeneratorTests/Core # Folders ending in Tests hold test code. testSuffixes: [Tests] diff --git a/Architecture/Package.swift b/Architecture/Package.swift index 3ea86ed..94d5515 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 13bc1d5..9cadeea 100644 --- a/Architecture/Tests/ArchitectureTests/ArchitectureRules.swift +++ b/Architecture/Tests/ArchitectureTests/ArchitectureRules.swift @@ -27,11 +27,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 14c8756..38d8605 100644 --- a/Architecture/Tests/ArchitectureTests/Detect.swift +++ b/Architecture/Tests/ArchitectureTests/Detect.swift @@ -1,7 +1,7 @@ import LLMCheck import SwiftSyntax -/// The detectors, separate from the codebase so `DetectorTests` can run them on snippets. +/// The repository-specific detectors (the shared ones are swift-llm-check built-ins), separate from the codebase so `DetectorTests` can run them on snippets. enum Detect { /// Types whose every use is I/O, process state or plugin output. static let impureTypes: Set = [ @@ -41,16 +41,4 @@ enum Detect { return function?.name.text != "fatalError" } } - - /// `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) - } - } } diff --git a/Architecture/Tests/ArchitectureTests/DetectorTests.swift b/Architecture/Tests/ArchitectureTests/DetectorTests.swift index 4beb641..7c36901 100644 --- a/Architecture/Tests/ArchitectureTests/DetectorTests.swift +++ b/Architecture/Tests/ArchitectureTests/DetectorTests.swift @@ -55,20 +55,4 @@ import Testing """, at: "Plugins/SchemeGeneratorPlugin/SchemeGenerator.swift")) #expect(found.map(\.location.line) == [1, 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/Benchmarks/Benchmarks/SchemeGeneratorBenchmarks/Core b/Benchmarks/Benchmarks/SchemeGeneratorBenchmarks/Core new file mode 120000 index 0000000..8dc4222 --- /dev/null +++ b/Benchmarks/Benchmarks/SchemeGeneratorBenchmarks/Core @@ -0,0 +1 @@ +../../../Plugins/SchemeGeneratorPlugin/Core \ No newline at end of file diff --git a/Benchmarks/Benchmarks/SchemeGeneratorBenchmarks/SchemeGeneratorBenchmarks.swift b/Benchmarks/Benchmarks/SchemeGeneratorBenchmarks/SchemeGeneratorBenchmarks.swift new file mode 100644 index 0000000..ed8c326 --- /dev/null +++ b/Benchmarks/Benchmarks/SchemeGeneratorBenchmarks/SchemeGeneratorBenchmarks.swift @@ -0,0 +1,60 @@ +import Benchmark +import Foundation + +// The plugin's work per run, minus the disk: hash the product list, plan which schemes to write, render each one. +// A modular app has tens to hundreds of products; 1,000 shows how the cost grows. + +func products(_ count: Int) -> [String] { (0.. 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 hundred = products(100) + let thousand = products(1_000) + + Benchmark("Render scheme, one product", configuration: .init(scalingFactor: .kilo)) { benchmark in + for _ in benchmark.scaledIterations { blackHole(XcschemeTemplate.render(productName: "FeatureModule")) } + } + + Benchmark("Render schemes, 1000 products") { benchmark in + for name in thousand { blackHole(XcschemeTemplate.render(productName: name)) } + } + + Benchmark("Render and encode schemes, 1000 products") { benchmark in + for name in thousand { blackHole(XcschemeTemplate.renderData(productName: name)) } + } + + Benchmark("Hash product names, 100 products", configuration: .init(scalingFactor: .kilo)) { benchmark in + for _ in benchmark.scaledIterations { blackHole(ProductNamesHash.hash(hundred)) } + } + + Benchmark("Plan schemes, 1000 products") { benchmark in + // A third exist already, a few are obsolete, overwrite and removal on: every branch of the plan. + let existing = Array(thousand.prefix(333)) + (0..<20).map { "Obsolete\($0)" } + blackHole( + SchemePlan( + productNames: thousand, existingSchemes: existing, excludedSchemes: ["Obsolete0"], + overwriteAlreadyGeneratedSchemes: true, removeNotGeneratedSchemes: true)) + } + + Benchmark("Read scheme names, 1000 files") { benchmark in + let files = thousand.map { SchemeNaming.fileName(scheme: $0) } + ["README.md", ".DS_Store"] + blackHole(files.compactMap(SchemeNaming.schemeName(fileName:))) + } + + Benchmark("Full run without disk, 1000 products") { benchmark in + let existing = Array(thousand.prefix(500)) + blackHole(ProductNamesHash.hash(thousand)) + let plan = SchemePlan( + productNames: thousand, existingSchemes: existing, excludedSchemes: [], + overwriteAlreadyGeneratedSchemes: true, removeNotGeneratedSchemes: true) + for name in plan.toWrite { blackHole(XcschemeTemplate.renderData(productName: name)) } + } +} diff --git a/Benchmarks/Package.swift b/Benchmarks/Package.swift new file mode 100644 index 0000000..74bb0be --- /dev/null +++ b/Benchmarks/Package.swift @@ -0,0 +1,31 @@ +// swift-tools-version: 6.1 +import PackageDescription + +// SchemeGeneratorPlugin's benchmarks, on ordo-one/package-benchmark (https://www.swift.org/blog/benchmarks/). A +// separate package so the plugin never depends on it. A plugin target cannot be imported, so the benchmark target +// compiles the plugin's pure core itself: Benchmarks/SchemeGeneratorBenchmarks/Core is a symlink to +// Plugins/SchemeGeneratorPlugin/Core. 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: "SchemeGeneratorBenchmarks", + dependencies: [ + .product(name: "Benchmark", package: "package-benchmark") + ], + path: "Benchmarks/SchemeGeneratorBenchmarks", + swiftSettings: [.swiftLanguageMode(.v5)], + 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..02def47 --- /dev/null +++ b/Benchmarks/Tools/Hotspots/main.swift @@ -0,0 +1,86 @@ +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 library 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) +} + +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(/SchemeGenerator|SchemePlan|XcschemeTemplate|ProductNamesHash|SchemeNaming/) { + 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 (SchemeGeneratorPlugin core)", 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..8389722 --- /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 schemes, 1000 products' [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 SchemeGeneratorBenchmarks +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/SchemeGeneratorBenchmarks" --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 defa07e..a98e4a4 100644 --- a/CODING_STANDARDS.md +++ b/CODING_STANDARDS.md @@ -10,7 +10,7 @@ Read during review. The mechanical part is enforced by `swift test --package-pat the configuration types. It imports only Foundation and CryptoKit and performs no I/O. `SchemeGenerator.swift` reads the configuration and the schemes directory, calls the core, then writes and deletes files. - **One copy of the core.** A plugin target cannot be imported, so `Tests/SchemeGeneratorTests/Core` and - `Benchmarks/Sources/SchemeGeneratorCore/Core` are symlinks to `Plugins/SchemeGeneratorPlugin/Core`. Never copy a file + `Benchmarks/Benchmarks/SchemeGeneratorBenchmarks/Core` are symlinks to `Plugins/SchemeGeneratorPlugin/Core`. Never copy a file instead of linking it; a new core file is picked up by both automatically. - **Report through Diagnostics.** Messages users must see go through `Diagnostics.emit`, which Xcode shows in the Report navigator. The plugin stops with the module's `fatalError(.error, "…")`, which emits first; a bare diff --git a/Plugins/SchemeGeneratorPlugin/Core/SchemePlanning.swift b/Plugins/SchemeGeneratorPlugin/Core/SchemePlanning.swift index 6cd1ae4..2c26638 100644 --- a/Plugins/SchemeGeneratorPlugin/Core/SchemePlanning.swift +++ b/Plugins/SchemeGeneratorPlugin/Core/SchemePlanning.swift @@ -2,8 +2,8 @@ import CryptoKit import Foundation // The plugin's decisions, kept free of I/O and of PackagePlugin so the test target and the benchmarks can compile -// this folder as it is (Tests/SchemeGeneratorTests/Core and Benchmarks/Sources/SchemeGeneratorCore are symlinks to -// it). SchemeGenerator.swift reads the disk, calls these functions and writes the result. +// this folder as it is: Tests/SchemeGeneratorTests/Core and Benchmarks/Benchmarks/SchemeGeneratorBenchmarks/Core are +// symlinks to it. SchemeGenerator.swift reads the disk, calls these functions and writes the result. /// Which scheme files to write and which to delete. struct SchemePlan: Equatable { @@ -40,11 +40,13 @@ struct SchemePlan: Equatable { } enum SchemeNaming { + private static let schemeSuffix = ".\(xcschemeExtension)" + /// The scheme name of a file in `schemesDirectory`, or nil when it is not an `.xcscheme` file. static func schemeName(fileName: String) -> String? { - let suffix = ".\(xcschemeExtension)" - guard fileName.hasSuffix(suffix), fileName.count > suffix.count else { return nil } - return String(fileName.dropLast(suffix.count)) + // UTF-8 counts are O(1); `count` walks every Character. The suffix is ASCII, so both counts agree for it. + guard fileName.utf8.count > schemeSuffix.utf8.count, fileName.hasSuffix(schemeSuffix) else { return nil } + return String(fileName.dropLast(schemeSuffix.utf8.count)) } /// The file name of the scheme for `productName`. @@ -68,9 +70,15 @@ enum ProductNamesHash { /// The lowercase hex SHA-256 of the product names joined by newlines. Stored in the tool configuration to skip a /// run when the product list has not changed. static func hash(_ productNames: [String]) -> String { - let data = Data(productNames.joined(separator: "\n").utf8) - return SHA256.hash(data: data) - .compactMap { String(format: "%02x", $0) } - .joined() + let digest = SHA256.hash(data: Data(productNames.joined(separator: "\n").utf8)) + var hex = [UInt8]() + hex.reserveCapacity(SHA256.byteCount * 2) + for byte in digest { + hex.append(hexDigits[Int(byte >> 4)]) + hex.append(hexDigits[Int(byte & 0x0F)]) + } + return String(decoding: hex, as: UTF8.self) } + + private static let hexDigits = Array("0123456789abcdef".utf8) } diff --git a/Plugins/SchemeGeneratorPlugin/Core/XcschemeTemplate.swift b/Plugins/SchemeGeneratorPlugin/Core/XcschemeTemplate.swift index 9e2f21f..2266752 100644 --- a/Plugins/SchemeGeneratorPlugin/Core/XcschemeTemplate.swift +++ b/Plugins/SchemeGeneratorPlugin/Core/XcschemeTemplate.swift @@ -72,8 +72,36 @@ let xcscheme = """ """ enum XcschemeTemplate { + static let placeholder = "__LIBRARY__" + + /// The template cut at each placeholder, once: rendering appends these around the product name rather than + /// searching the template again for every product. + static let pieces: [Substring] = { + var pieces: [Substring] = [] + var rest = xcscheme[...] + while let range = rest.range(of: placeholder) { + pieces.append(rest[.. String { - xcscheme.replacingOccurrences(of: "__LIBRARY__", with: productName) + var scheme = "" + scheme.reserveCapacity(piecesUTF8Count + (pieces.count - 1) * productName.utf8.count) + for (index, piece) in pieces.enumerated() { + if index > 0 { scheme += productName } + scheme += piece + } + return scheme + } + + /// `render(productName:)` as UTF-8, ready to write. + static func renderData(productName: String) -> Data { + Data(render(productName: productName).utf8) } } diff --git a/Plugins/SchemeGeneratorPlugin/SchemeGenerator.swift b/Plugins/SchemeGeneratorPlugin/SchemeGenerator.swift index b694aa7..212cbb2 100644 --- a/Plugins/SchemeGeneratorPlugin/SchemeGenerator.swift +++ b/Plugins/SchemeGeneratorPlugin/SchemeGenerator.swift @@ -192,13 +192,12 @@ public struct SchemeGenerator { fatalError(.error, "Failed to create fileHandle for \(libraryName) at \(librarySchemeURL.path)") } - if let outputData = XcschemeTemplate.render(productName: libraryName).data(using: .utf8) { - do { - try libraryScemeFileHandle.write(contentsOf: outputData) - } catch { - let bf = ByteCountFormatter() - fatalError(.error, "Failed to write \(bf.string(fromByteCount: Int64(outputData.count))) in fileHandle for \(libraryName) at \(librarySchemeURL.path)") - } + let outputData = XcschemeTemplate.renderData(productName: libraryName) + do { + try libraryScemeFileHandle.write(contentsOf: outputData) + } catch { + let bf = ByteCountFormatter() + fatalError(.error, "Failed to write \(bf.string(fromByteCount: Int64(outputData.count))) in fileHandle for \(libraryName) at \(librarySchemeURL.path)") } do { try libraryScemeFileHandle.close() diff --git a/README.md b/README.md index 08972d0..096dcff 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,33 @@ # Scheme Generator +[![CI](https://github.com/mackoj/SchemeGeneratorPlugin/actions/workflows/ci.yml/badge.svg)](https://github.com/mackoj/SchemeGeneratorPlugin/actions/workflows/ci.yml) [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fmackoj%2FSchemeGeneratorPlugin%2Fbadge%3Ftype%3Dswift-versions)](https://swiftpackageindex.com/mackoj/SchemeGeneratorPlugin) [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fmackoj%2FSchemeGeneratorPlugin%2Fbadge%3Ftype%3Dplatforms)](https://swiftpackageindex.com/mackoj/SchemeGeneratorPlugin) -Scheme Generator is a Swift Package Manager Plugin for quickly updating your Schemes files. It is a great tool for a project that is modularized or that uses TCA. +**[Website](https://mackoj.github.io/SchemeGeneratorPlugin/)** · +**[Performance](docs/performance.md)** · +**[Architecture rules](docs/architecture-rules.md)** -⚠️ This is in beta +Scheme Generator is a Swift Package Manager command plugin that writes a shared Xcode scheme (`.xcscheme`) for every +product in your `Package.swift`, and removes the schemes of products that are gone. It is a great tool for a project +that is modularized or that uses TCA. * [Installation](#installation) * [Basic usage](#basic-usage) * [Configuration](#configuration) * [CI](#ci) * [How does it work?](#how-does-it-work) +* [Contributing](#contributing) ## Installation -Add to your dependencies `.package(url: "https://github.com/mackoj/SchemeGeneratorPlugin.git", from: "0.5.5"),`. +Add it to the dependencies of the package whose products need schemes: -_This plugin works with Xcode 14.1 / 14.0._ +```swift +.package(url: "https://github.com/mackoj/SchemeGeneratorPlugin.git", from: "0.5.8"), +``` + +_Requires Xcode 14 or later (swift-tools-version 5.7) on macOS 12 or later._ ## Basic usage @@ -35,11 +45,11 @@ _If the `schemesDirectory` point to inside a workspace `project.xcworkspace/xcsh You can then invoke the plugin from the root of your repository like so: -`swift package plugin scheme-generator` +`swift package --allow-writing-to-package-directory scheme-generator` This will generate schemes for all compatible targets defined in your package and write them in `schemesDirectory`. -Notice that you must also passed `--allow-writing-to-directory` option to SwiftPM. Otherwise SwiftPM will throw an error as it's a sandbox violation for a plugin to write to a package directory without explicit permission. +The `--allow-writing-to-package-directory` option is required: without it SwiftPM stops the plugin, since writing to the package directory without explicit permission is a sandbox violation. You can pass `--confFile newName.json` to `scheme-generator` in order to change the default path for the configuration. It will be saved so that you will not be required to input the configuration fileName at each launch. @@ -50,7 +60,7 @@ This file contains these keys: - `schemesDirectory`: A string that represents where the schemes will be saved(if you use TCA you can put it in workspace) - `removeNotGeneratedSchemes`: A bool that represents if it should remove schemes that are no longer in Package.swift - `overwriteAlreadyGeneratedSchemes`: A bool that represents if it should force the overwrite of schemes already present scheme -- `excludedSchemes`: An array of String that represents the **name** of the schemes files that already exist and should not be processed +- `excludedSchemes`: An array of String that represents the **name** of the schemes files that already exist and should never be removed - `verbose`: A bool that represents if it should print more information in the console ```json @@ -69,10 +79,16 @@ If a new configuration filename is used as explained in #basic-usage step 1. It You can use it in CI to automatically generate your schemes. -`swift package plugin --allow-writing-to-package-directory scheme-generator` +`swift package --allow-writing-to-package-directory scheme-generator` ## How Does it Work? It loads its configuration to figure out `what` it can do and `where` to apply it. Then it loads all the products from the `Package.swift`. Apply a filter to do just what is required then wrote the files in the `schemesDirectory`. -The scheme is based on a template. +The scheme is based on a template. A run with an unchanged product list stops early (set `overwriteAlreadyGeneratedSchemes` to force it). + +## Contributing + +- `swift build --build-tests && swift test` tests the plugin's pure core (`Plugins/SchemeGeneratorPlugin/Core`, shared with the test target through a symlink); `scripts/smoke-test.sh` runs the plugin on a sample package. +- `swift test --package-path Architecture` checks the [architecture rules](docs/architecture-rules.md) written with [swift-llm-check](https://github.com/mackoj/swift-llm-check); see `CODING_STANDARDS.md`. +- `swift package --package-path Benchmarks benchmark` runs the benchmarks; see [docs/performance.md](docs/performance.md). diff --git a/Tests/SchemeGeneratorTests/SchemePlanTests.swift b/Tests/SchemeGeneratorTests/SchemePlanTests.swift index 9ec593d..a641fbb 100644 --- a/Tests/SchemeGeneratorTests/SchemePlanTests.swift +++ b/Tests/SchemeGeneratorTests/SchemePlanTests.swift @@ -1,4 +1,5 @@ import Testing +import CryptoKit import Foundation @Suite struct SchemePlanTests { @@ -54,6 +55,8 @@ import Foundation #expect(SchemeNaming.schemeName(fileName: "My.Feature.xcscheme") == "My.Feature") #expect(SchemeNaming.schemeName(fileName: "README.md") == nil) #expect(SchemeNaming.schemeName(fileName: ".xcscheme") == nil) + #expect(SchemeNaming.schemeName(fileName: "Café.xcscheme") == "Café") + #expect(SchemeNaming.schemeName(fileName: "App.xcscheme.bak") == nil) } @Test func fileNameRoundTrips() { @@ -82,6 +85,13 @@ import Foundation ProductNamesHash.hash(["A", "B"]) == "23519a43c66b4c342f25b32e09797ec5f3fc0be388cd8243fb3449afbdce4013") #expect(ProductNamesHash.hash(["A", "B"]) != ProductNamesHash.hash(["B", "A"])) } + + @Test(arguments: [[], ["App"], ["Feature", "Café", "日本"], (0..<300).map { "Module\($0)" }]) + func matchesTheFormatBasedEncoding(names: [String]) { + let reference = SHA256.hash(data: Data(names.joined(separator: "\n").utf8)) + .map { String(format: "%02x", $0) }.joined() + #expect(ProductNamesHash.hash(names) == reference) + } } @Suite struct XcschemeTemplateTests { @@ -92,6 +102,13 @@ import Foundation #expect(scheme == xcscheme.replacingOccurrences(of: "__LIBRARY__", with: "Feature")) #expect(scheme.hasPrefix("")) } + + @Test(arguments: ["", "A", "Café", "日本Module", "Has__LIBRARY__Inside"]) + func matchesStringReplacement(productName: String) { + let reference = xcscheme.replacingOccurrences(of: "__LIBRARY__", with: productName) + #expect(XcschemeTemplate.render(productName: productName) == reference) + #expect(XcschemeTemplate.renderData(productName: productName) == reference.data(using: .utf8)) + } } @Suite struct ConfigurationCodingTests { diff --git a/docs/performance.md b/docs/performance.md new file mode 100644 index 0000000..6265229 --- /dev/null +++ b/docs/performance.md @@ -0,0 +1,62 @@ +# 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. A plugin target +cannot be imported, so the benchmark target compiles the plugin's pure core itself: +`Benchmarks/Benchmarks/SchemeGeneratorBenchmarks/Core` is a symlink to `Plugins/SchemeGeneratorPlugin/Core`. What is +measured is everything the plugin does per run except touching the disk: hash the product list, plan which schemes to +create, overwrite and remove, render each `.xcscheme`. Reading the configuration and writing files stay in +`SchemeGenerator.swift` and are not benchmarked. + +Run everything from the repository root. package-benchmark uses jemalloc for malloc counts (`brew install jemalloc`); +`BENCHMARK_DISABLE_JEMALLOC=true` builds without it, as CI does. + +## 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 a few percent between runs. + +- `--filter` takes one regular expression per flag; repeat the flag rather than writing `A|B`. +- The per-operation benchmarks (`scalingFactor: .kilo`) are marked `*` in package-benchmark's tables. + +## Profile a benchmark + +```sh +Benchmarks/scripts/profile.sh 'Full run without disk, 1000 products' 20 +``` + +It runs that one benchmark under Instruments' Time Profiler and prints the functions the samples were in (**Self**) and +the core functions with the most samples under them (**Inclusive**). The trace stays in `Benchmarks/.build/profiles/`. + +## What has paid off + +Measured on an M-series Mac, Swift 6.4, release build (0.5.9): + +| Benchmark | Wall clock p50 (µs) | Mallocs p50 | +|---|---|---| +| Full run without disk, 1000 products | 15368 → 1731 (0.11x) | 6388 → 3026 (0.47x) | +| Render schemes, 1000 products | 13369 → 519 (0.04x) | 4100 → 1000 (0.24x) | +| Render and encode schemes, 1000 products | 14066 → 729 (0.05x) | 6100 → 3000 (0.49x) | +| Hash product names, 100 products | 48 → 7 (0.15x) | 273 → 11 (0.04x) | +| Read scheme names, 1000 files | 371 → 267 (0.72x) | 1912 → 1912 | +| Plan schemes, 1000 products | 803 → 782 | 19 → 19 | + +- **Cut the template once, append per product.** `replacingOccurrences(of:with:)` bridged to `NSString` and searched + the 2.4 KB template again for every product. The template is now split at `__LIBRARY__` once (`XcschemeTemplate.pieces`) + and each scheme is appended into a string reserved at its final size. `renderData` encodes with `Data(string.utf8)` + instead of `data(using:)`. +- **Hex without `String(format:)`.** The product-list hash formatted each of its 32 bytes with `String(format: "%02x")`, + one Foundation formatter call and allocation per byte; a lookup table into a reserved byte buffer is one allocation. +- **Count UTF-8, not Characters.** `String.count` walks grapheme clusters; the scheme-file suffix is ASCII, so + `utf8.count` is the same number in O(1). +- **Not worth it here:** the plan is now dominated by sorting (the order schemes are written and listed in), under a + millisecond for 1,000 products; writing the files dominates a real run. diff --git a/site/index.html b/site/index.html new file mode 100644 index 0000000..3613a37 --- /dev/null +++ b/site/index.html @@ -0,0 +1,374 @@ + + + + + +Scheme Generator · Xcode schemes for every SwiftPM product + + + + + + + + + + +
+
+
+
+
    +
  • SwiftPM command plugin
  • +
  • Xcode 14+
  • +
  • No dependencies
  • +
  • MIT
  • +
+

A scheme for every product,
in one command.

+

Scheme Generator reads the products of your Package.swift and writes a shared Xcode .xcscheme for each one, right where your workspace looks for them. Add a module, run the plugin, and its scheme is there. Remove one, and its scheme goes away.

+ +
+
+
+
Terminal
+
$ swift package --allow-writing-to-package-directory \
+    scheme-generator
+Found 42 products.
+Schemes that will be removed:
+LegacyNetworking
+Schemes that will be created:
+OnboardingFeature
+SettingsFeature
+Finished
+
+
+
+
+ +
+
+

Why

+

Modular apps have many products.
Xcode only shows the schemes you made.

+

Split an app into a package of feature modules, as with The Composable Architecture, and each module deserves its own scheme: build it alone, run its tests, preview it fast. Xcode's autocreated schemes are per user and get out of step; shared schemes written by hand drift the moment someone adds or renames a product. Scheme Generator makes the schemes a function of Package.swift.

+
+
+

Read

+

It loads schemeGenerator.json and the list of products SwiftPM reports for your package.

+
+
+

Plan

+

It compares them with the .xcscheme files already in schemesDirectory: new products get a scheme, obsolete schemes are removed, excluded ones are left alone.

+
+
+

Write

+

It writes each scheme from a template that builds, tests, profiles and archives that product, and remembers the product list so an unchanged package is a no-op.

+
+
+
+
+ +
+
+

Features

+

Small, predictable, out of your way.

+
+
+
+

Every product, one scheme each

+

Libraries and executables alike get a shared scheme with build, test, launch, profile, analyze and archive actions, named after the product.

+
+
+
+

Cleans up after itself

+

With removeNotGeneratedSchemes, a scheme whose product left Package.swift is deleted. excludedSchemes protects the hand-made ones.

+
+
+
+

A no-op when nothing changed

+

It keeps a hash of the product list and stops early when it is unchanged, so it is cheap to run on every build or on CI. overwriteAlreadyGeneratedSchemes forces a refresh.

+
+
+
+

Xcode or terminal

+

Right-click your package in Xcode's navigator, or run swift package scheme-generator from a script or a CI job. Messages appear in Xcode's Report navigator.

+
+
+
+

Sandboxed and dependency-free

+

A plain SwiftPM command plugin with no package dependencies. It asks for permission before writing, and writes only to the folder you configure.

+
+
+
+

Fast for large packages

+

Planning and rendering 1,000 schemes takes under 2 ms; the disk is the only cost you will notice. Measured with package-benchmark.

+
+
+
+
+ +
+
+

Configuration

+

One JSON file at the root of your package.

+

Name it schemeGenerator.json, or pass --confFile other.json once: the plugin remembers the name. If it is missing, the plugin writes a default one for you to fill in.

+
+
+
schemeGenerator.json
+
{
+  "schemesDirectory": "Project/project.xcworkspace/xcshareddata/xcschemes",
+  "excludedSchemes": ["Target1Tests", "Target2Tests"],
+  "removeNotGeneratedSchemes": true,
+  "overwriteAlreadyGeneratedSchemes": false,
+  "verbose": true
+}
+
+
+ + + + + + + + + +
KeyMeaning
schemesDirectoryWhere schemes are written. Required. Point it into a workspace's xcshareddata/xcschemes to share them.
removeNotGeneratedSchemesDelete schemes whose product is no longer in Package.swift.
overwriteAlreadyGeneratedSchemesRewrite schemes that already exist.
excludedSchemesNames of existing scheme files the plugin must never remove.
verbosePrint the configuration and every scheme it creates or removes.
+
+
+
+
+ +
+
+

Install

+

Add the package, run the command.

+
+
+
+
Package.swift
+
dependencies: [
+  .package(url: "https://github.com/mackoj/SchemeGeneratorPlugin.git", from: "0.5.8"),
+]
+
+
+
Terminal
+
swift package --allow-writing-to-package-directory scheme-generator
+
+
+
+
    +
  1. Add the dependency to the package whose products need schemes. No target needs to use it.
  2. +
  3. Create schemeGenerator.json next to Package.swift.
  4. +
  5. In Xcode, right-click the package and choose Scheme Generator, then Allow Command to Change Files. In a terminal or on CI, pass --allow-writing-to-package-directory.
  6. +
  7. If the schemes go into a workspace, restart Xcode to see them all.
  8. +
+

Requires Xcode 14 or later (swift-tools-version 5.7) on macOS 12 or later.

+ +
+
+
+
+
+ + + +