Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Apps/GlassStudio/KitTests/SnippetCompilerB.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 snippet becomes the body of a SwiftUI view in a temporary45/// SwiftPM package that depends on this repository by path, and `swift build` must succeed.46struct SnippetCompilerB {47 struct Outcome {48 let status: Int3249 let output: String50 let snippetCount: Int51 }5253 enum Failure: Error {54 case launch(String)55 }5657 /// Root of this repository: this file is `Apps/GlassStudio/KitTests/SnippetCompilerB.swift`.58 let repositoryRoot: URL5960 init(filePath: String = #filePath) {61 var url = URL(fileURLWithPath: filePath)62 for _ in 0..<4 { url.deleteLastPathComponent() }63 repositoryRoot = url64 }6566 /// One Swift source per descriptor: a view per value set, whose body is the snippet.67 @MainActor68 static func source(for descriptor: ComponentDescriptor, index: Int, valueSets: [InspectorValues]) -> String {69 var source = "import SwiftUI\nimport SPGlassKit\n"70 for (setIndex, values) in valueSets.enumerated() {71 source += "\n// \(descriptor.id), value set \(setIndex)\n"72 source += "struct Snippet_\(index)_\(setIndex): View {\n var body: some View {\n"73 source += SwiftLiteral.indent(descriptor.snippet(values), levels: 2)74 source += "\n }\n}\n"75 }76 return source77 }7879 /// Writes `sources` (file name → content) into a temporary package and builds it.80 func compile(_ sources: [String: String], snippetCount: Int) throws -> Outcome {81 let fileManager = FileManager.default82 let directory = fileManager.temporaryDirectory.appendingPathComponent("glass-snippets-b-\(UUID().uuidString)", isDirectory: true)83 let sourceDirectory = directory.appendingPathComponent("Sources/Snippets", isDirectory: true)84 try fileManager.createDirectory(at: sourceDirectory, withIntermediateDirectories: true)85 defer { try? fileManager.removeItem(at: directory) }8687 // A path dependency is identified by the last component of its path.88 let manifest = """89 // swift-tools-version: 6.290 import PackageDescription9192 let package = Package(93 name: "GlassSnippetsB",94 platforms: [.macOS(.v26)],95 dependencies: [.package(path: \(SwiftLiteral.string(repositoryRoot.path)))],96 targets: [97 .target(98 name: "Snippets",99 dependencies: [.product(name: "SPGlassKit", package: \(SwiftLiteral.string(repositoryRoot.lastPathComponent)))],100 swiftSettings: [.swiftLanguageMode(.v6)]101 ),102 ]103 )104105 """106 try manifest.write(to: directory.appendingPathComponent("Package.swift"), atomically: true, encoding: .utf8)107 for (name, source) in sources {108 try source.write(to: sourceDirectory.appendingPathComponent(name), atomically: true, encoding: .utf8)109 }110111 let logURL = directory.appendingPathComponent("build.log")112 guard fileManager.createFile(atPath: logURL.path, contents: nil), let log = FileHandle(forWritingAtPath: logURL.path) else {113 throw Failure.launch("cannot create \(logURL.path)")114 }115 let process = Process()116 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")117 process.arguments = ["swift", "build", "--scratch-path", directory.appendingPathComponent(".build").path]118 process.currentDirectoryURL = directory119 process.standardOutput = log120 process.standardError = log121 process.standardInput = FileHandle.nullDevice122 do {123 try process.run()124 } catch {125 throw Failure.launch(String(describing: error))126 }127 process.waitUntilExit()128 try? log.close()129130 let output = (try? String(contentsOf: logURL, encoding: .utf8)) ?? ""131 return Outcome(status: process.terminationStatus, output: Self.digest(output), snippetCount: snippetCount)132 }133134 /// The diagnostics of a build log, then its end, bounded so that a failure message stays readable.135 static func digest(_ output: String) -> String {136 let lines = output.components(separatedBy: "\n")137 let errors = lines.filter { $0.contains("error:") }.prefix(40)138 return (errors + ["…"] + lines.suffix(25)).joined(separator: "\n")139 }140}141