SPB Git

Repository Public MIT

Fixture.swift 7.7 KB 152 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Tests/GlassCLICoreTests/Fixture.swift8// Module           : Tests9// 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 Foundation42import SPGlassRegistry43import SPGlassThemes44@testable import GlassCLICore4546/// A throwaway project directory and a throwaway registry built with the real builder.47struct Fixture {48    let root: URL49    let project: URL50    let registry: URL5152    init() throws {53        root = FileManager.default.temporaryDirectory.appendingPathComponent("spglass-cli-\(UUID().uuidString)").resolvingSymlinksInPath()54        project = root.appendingPathComponent("project")55        registry = root.appendingPathComponent("registry")56        try FileManager.default.createDirectory(at: project.appendingPathComponent("Sources/App"), withIntermediateDirectories: true)57        try "// swift-tools-version: 6.2\n".write(to: project.appendingPathComponent("Package.swift"), atomically: true, encoding: .utf8)58        try publish(version: "1.0.0")59    }6061    func cleanUp() { try? FileManager.default.removeItem(at: root) }6263    static func item(_ id: String, dependencies: [String] = [], files: [String: String]) -> RegistryItemSource {64        RegistryItemSource(id: id, name: id.split(separator: "-").map { $0.capitalized }.joined(), kind: id == "glass-foundation" ? "primitive" : "native-wrapper", category: id == "glass-foundation" ? nil : "buttons", description: "Item \(id).", dependencies: dependencies, frameworks: [], files: files.sorted { $0.key < $1.key }.map { ($0.key, Data($0.value.utf8)) }, symbols: [], examples: [ManifestExample(title: "Usage", code: "\(id)()")], accessibility: ["Has a label."], changes: ["Release."])65    }6667    /// Publishes a version. 1.1.0 changes the button, drops one of its files and adds another.68    func publish(version: String, signingKey: String? = nil, extra: [RegistryItemSource] = []) throws {69        let isNew = version != "1.0.0"70        let buttonFiles: [String: String] = isNew71            ? ["Buttons/Button.swift": "struct Button {\n    var title = \"\"\n    var isLoading = false\n}\n", "Buttons/Button+Loading.swift": "extension Button {}\n"]72            : ["Buttons/Button.swift": "struct Button {\n    var title = \"\"\n}\n", "Buttons/Button+Style.swift": "enum ButtonStyle { case regular }\n"]73        let items = [74            Self.item("glass-foundation", files: ["Core/Base.swift": "struct Base {}\n", "Resources/en.lproj/GlassKit.strings": "\"a\" = \"b\";\n"]),75            Self.item("glass-button", dependencies: ["glass-foundation"], files: buttonFiles),76            Self.item("glass-card", dependencies: ["glass-button"], files: ["Containers/Card.swift": "struct Card { var button = Button() }\n"]),77        ] + extra78        let themes = try [GlassTheme.aurora, .crystal].map { RegistryThemeSource(id: $0.id.rawValue, name: $0.name, summary: $0.summary, data: try GlassThemeCodec.encode($0)) }79        _ = try RegistryBuilder(root: registry, name: "Fixture", homepage: "https://example.invalid", license: "MIT", version: version, date: "2026-12-02", platforms: ["macOS"], minimumOS: ["macOS": "26.0"]).build(items: items, themes: themes, signingKey: signingKey)80    }8182    @discardableResult83    func run(_ arguments: String..., source: (any RegistrySource)? = nil, failAfterChanges: Int? = nil, environment: [String: String] = [:]) async -> CLIOutcome {84        await CLI.run(arguments: arguments, currentDirectory: project, environment: environment, sourceOverride: source, failAfterChanges: failAfterChanges)85    }8687    /// `spglass init` pointing at the fixture registry.88    func initialize() async {89        let outcome = await run("init", "--registry", registry.path)90        precondition(outcome.exitCode == 0, outcome.standardError)91    }9293    func read(_ path: String) -> String? {94        try? String(contentsOf: project.appendingPathComponent(path), encoding: .utf8)95    }9697    func write(_ path: String, _ text: String) throws {98        let url = project.appendingPathComponent(path)99        try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)100        try text.write(to: url, atomically: true, encoding: .utf8)101    }102103    func exists(_ path: String) -> Bool {104        FileManager.default.fileExists(atPath: project.appendingPathComponent(path).path)105    }106107    func lock() throws -> ProjectLock {108        try JSONDecoder().decode(ProjectLock.self, from: Data(contentsOf: project.appendingPathComponent("spglass.lock.json")))109    }110111    /// Every regular file below the project, with its content: used to prove that nothing changed.112    func snapshot() -> [String: Data] {113        var result: [String: Data] = [:]114        let enumerator = FileManager.default.enumerator(at: project, includingPropertiesForKeys: [.isRegularFileKey])115        while let url = enumerator?.nextObject() as? URL {116            if (try? url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true {117                result[String(url.path.dropFirst(project.path.count + 1))] = try? Data(contentsOf: url)118            }119        }120        return result121    }122123    func json(_ outcome: CLIOutcome) throws -> [String: Any] {124        try parseJSON(outcome.standardOutput)125    }126}127128func parseJSON(_ text: String) throws -> [String: Any] {129    guard let object = try JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any] else {130        throw CLIError(code: "test", message: "not a JSON object")131    }132    return object133}134135/// A registry that is unreachable, or that serves altered bytes for chosen paths.136struct StubSource: RegistrySource {137    var base: (any RegistrySource)?138    var replacements: [String: Data] = [:]139    var unreachable = false140    let identity = "stub://registry"141142    func fetch(_ relativePath: String, limit: Int) async throws -> Data {143        if unreachable { throw CLIError(code: "network", message: "Network error: the registry is unreachable.", exitCode: .network) }144        if let data = replacements[relativePath] {145            guard data.count <= limit else { throw CLIError(RegistryError.tooLarge(what: relativePath, bytes: data.count, limit: limit)) }146            return data147        }148        guard let base else { throw CLIError(code: "not_found", message: "missing", exitCode: .notFound) }149        return try await base.fetch(relativePath, limit: limit)150    }151}152
Files main
Menu

Theme