SPB Git

Repository Public MIT

SnippetCompiler.swift 6.3 KB 141 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Apps/GlassStudio/KitTests/SnippetCompiler.swift8// Module           : GlassStudio9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42@testable import GlassStudioKit4344/// Compiles generated snippets for real: each one becomes the body of a view in a throwaway SwiftPM package45/// that depends on this repository by path, and `swift build` decides.46///47/// The first build compiles SP GlassKit itself, so tests that use this are gated behind48/// `GLASS_SNIPPET_COMPILE=1` (see ``isEnabled``).49enum SnippetCompiler {50    struct Outcome {51        let status: Int3252        /// Compiler output, standard output and standard error together.53        let output: String54        let snippetCount: Int5556        var succeeded: Bool { status == 0 }57    }5859    enum Failure: Error {60        case cannotLaunch(String)61    }6263    /// True when the environment asks for the slow compilation tests.64    static var isEnabled: Bool { ProcessInfo.processInfo.environment["GLASS_SNIPPET_COMPILE"] == "1" }6566    /// The repository this test file belongs to (`Apps/GlassStudio/KitTests/SnippetCompiler.swift` → root).67    static let repositoryRoot = URL(fileURLWithPath: #filePath)68        .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()6970    /// A Swift file with one view per snippet: `struct Snippet_<index>_<k>: View { var body: some View { … } }`.71    static func source(index: Int, comment: String, snippets: [String]) -> String {72        var lines = ["// \(comment.replacingOccurrences(of: "\n", with: " "))", "import SwiftUI", "import SPGlassKit", ""]73        for (k, snippet) in snippets.enumerated() {74            lines.append("struct Snippet_\(index)_\(k): View {")75            lines.append("    var body: some View {")76            lines.append(SwiftLiteral.indent(snippet, levels: 2))77            lines.append("    }")78            lines.append("}")79            lines.append("")80        }81        return lines.joined(separator: "\n")82    }8384    /// The snippets of a descriptor for its default values, each variant and any extra value sets.85    @MainActor86    static func snippets(of descriptor: ComponentDescriptor, extra: [InspectorValues] = []) -> [String] {87        ([descriptor.defaultValues] + descriptor.variants.map(descriptor.values(for:)) + extra).map(descriptor.snippet)88    }8990    /// Writes `snippets` (one file per entry) into a temporary package and builds it.91    /// - Parameter snippets: for each file, a comment naming its origin and the snippets it holds.92    static func compile(_ snippets: [(comment: String, snippets: [String])]) throws -> Outcome {93        let manager = FileManager.default94        let directory = manager.temporaryDirectory.appendingPathComponent("glass-snippets-\(UUID().uuidString)", isDirectory: true)95        let sources = directory.appendingPathComponent("Sources/Snippets", isDirectory: true)96        try manager.createDirectory(at: sources, withIntermediateDirectories: true)97        defer { try? manager.removeItem(at: directory) }9899        let manifest = """100        // swift-tools-version: 6.2101        import PackageDescription102103        let package = Package(104            name: "Snippets",105            platforms: [.macOS(.v26)],106            dependencies: [.package(name: "sp-glasskit", path: \(SwiftLiteral.string(repositoryRoot.path)))],107            targets: [108                .target(name: "Snippets", dependencies: [.product(name: "SPGlassKit", package: "sp-glasskit")], swiftSettings: [.swiftLanguageMode(.v6)]),109            ]110        )111112        """113        try manifest.write(to: directory.appendingPathComponent("Package.swift"), atomically: true, encoding: .utf8)114        for (index, file) in snippets.enumerated() {115            let text = source(index: index, comment: file.comment, snippets: file.snippets)116            try text.write(to: sources.appendingPathComponent("Snippets\(index).swift"), atomically: true, encoding: .utf8)117        }118119        let process = Process()120        process.executableURL = URL(fileURLWithPath: "/usr/bin/env")121        process.arguments = ["swift", "build", "--package-path", directory.path, "--scratch-path", directory.appendingPathComponent(".build").path]122        process.currentDirectoryURL = directory123        let pipe = Pipe()124        process.standardOutput = pipe125        process.standardError = pipe126        do {127            try process.run()128        } catch {129            throw Failure.cannotLaunch(String(describing: error))130        }131        // Read before waiting: a full pipe would block the compiler.132        let data = pipe.fileHandleForReading.readDataToEndOfFile()133        process.waitUntilExit()134        return Outcome(135            status: process.terminationStatus,136            output: String(decoding: data, as: UTF8.self),137            snippetCount: snippets.reduce(0) { $0 + $1.snippets.count }138        )139    }140}141
Files main
Menu

Theme