Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Apps/GlassStudio/KitTests/SnippetCompilerC.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 Foundation4243/// Compiles generated snippets for real: writes them into a temporary SwiftPM package that depends on this44/// repository by path, then runs `swift build` on it.45///46/// Each snippet becomes the body of a view in a file importing SwiftUI and SPGlassKit, which is exactly where47/// the Studio tells the user to paste it. A snippet may ask for one more module with a leading48/// `// Requires: import <Module>` line.49struct SnippetCompilerC {50 /// The snippets of one descriptor (defaults, variants, …).51 struct Unit {52 let descriptorID: String53 let snippets: [String]54 }5556 struct Outcome {57 let status: Int3258 /// Standard output and standard error of `swift build`.59 let output: String60 let fileCount: Int61 let snippetCount: Int6263 var succeeded: Bool { status == 0 }64 }6566 enum Failure: Error {67 case cannotLaunch(String)68 }6970 /// `Apps/GlassStudio/KitTests/SnippetCompilerC.swift` → the repository root, four levels up.71 static var repositoryRoot: URL {72 var url = URL(fileURLWithPath: #filePath)73 for _ in 0..<4 { url.deleteLastPathComponent() }74 return url.standardizedFileURL75 }7677 static let targetName = "SnippetCheckC"7879 /// Modules a snippet asks for with `// Requires: import <Module>` lines.80 static func requiredImports(in snippet: String) -> [String] {81 let prefix = "// Requires: import "82 return snippet.components(separatedBy: "\n").compactMap { line in83 let trimmed = line.trimmingCharacters(in: .whitespaces)84 guard trimmed.hasPrefix(prefix) else { return nil }85 let module = String(trimmed.dropFirst(prefix.count)).trimmingCharacters(in: .whitespaces)86 let allowed = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "_"))87 return !module.isEmpty && module.unicodeScalars.allSatisfy(allowed.contains) ? module : nil88 }89 }9091 /// The Swift file for one descriptor: one view per snippet.92 static func source(for unit: Unit, index: Int) -> String {93 var imports = ["SwiftUI", "SPGlassKit"]94 for module in unit.snippets.flatMap(requiredImports(in:)) where !imports.contains(module) {95 imports.append(module)96 }97 var text = "// \(unit.descriptorID)\n" + imports.map { "import \($0)\n" }.joined() + "\n"98 for (position, snippet) in unit.snippets.enumerated() {99 let body = snippet.components(separatedBy: "\n").map { $0.isEmpty ? $0 : " " + $0 }.joined(separator: "\n")100 text += "struct Snippet_\(index)_\(position): View {\n var body: some View {\n\(body)\n }\n}\n\n"101 }102 return text103 }104105 static func manifest(repositoryRoot: URL) -> String {106 let path = repositoryRoot.path.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"")107 let identity = repositoryRoot.lastPathComponent.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"")108 return """109 // swift-tools-version: 6.2110 import PackageDescription111112 let package = Package(113 name: "\(targetName)",114 platforms: [.macOS(.v26)],115 dependencies: [.package(path: "\(path)")],116 targets: [117 .target(118 name: "\(targetName)",119 dependencies: [.product(name: "SPGlassKit", package: "\(identity)")],120 swiftSettings: [.swiftLanguageMode(.v6)]121 ),122 ]123 )124125 """126 }127128 /// Writes the package, builds it and removes it. The compiler output is returned whatever the result.129 static func compile(_ units: [Unit]) throws -> Outcome {130 let fileManager = FileManager.default131 let directory = fileManager.temporaryDirectory.appendingPathComponent("glass-snippets-c-\(UUID().uuidString)", isDirectory: true)132 let sources = directory.appendingPathComponent("Sources/\(targetName)", isDirectory: true)133 try fileManager.createDirectory(at: sources, withIntermediateDirectories: true)134 defer { try? fileManager.removeItem(at: directory) }135136 try manifest(repositoryRoot: repositoryRoot).write(to: directory.appendingPathComponent("Package.swift"), atomically: true, encoding: .utf8)137 for (index, unit) in units.enumerated() {138 try source(for: unit, index: index).write(to: sources.appendingPathComponent("Snippets_\(index).swift"), atomically: true, encoding: .utf8)139 }140141 let process = Process()142 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")143 process.arguments = [144 "swift", "build",145 "--package-path", directory.path,146 "--scratch-path", directory.appendingPathComponent(".build", isDirectory: true).path,147 ]148 process.currentDirectoryURL = directory149 let pipe = Pipe()150 process.standardOutput = pipe151 process.standardError = pipe152 do {153 try process.run()154 } catch {155 throw Failure.cannotLaunch(String(describing: error))156 }157 // Read until the build closes the pipe, then collect the status: reading first avoids a full pipe.158 let data = pipe.fileHandleForReading.readDataToEndOfFile()159 process.waitUntilExit()160 return Outcome(161 status: process.terminationStatus,162 output: String(decoding: data, as: UTF8.self),163 fileCount: units.count,164 snippetCount: units.reduce(0) { $0 + $1.snippets.count }165 )166 }167}168