Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Sources/GlassRegistryBuilder/main.swift8// Module : GlassRegistryBuilder9// 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 SPGlassCore43import SPGlassRegistry44import SPGlassThemes4546// Builds the published registry (`Registry/`) from the package sources.47//48// swift run GlassRegistryBuilder [--root <repo>] [--output <dir>] [--version <x.y.z>] [--date <yyyy-mm-dd>]49// [--allow-overwrite] [--signing-key-file <path>]50// swift run GlassRegistryBuilder keygen <private-key-file>51//52// Every Swift file is prepared for source mode (imports of GlassKit modules removed) and assigned to exactly53// one item; dependencies between items are inferred from the symbols each file uses.5455struct BuilderFailure: Error, CustomStringConvertible { let description: String }5657let foundationModules = ["SPGlassCore", "SPGlassTokens", "SPGlassThemes", "SPGlassEffects"]58let componentModules = ["SPGlassComponents", "SPGlassNavigation", "SPGlassForms", "SPGlassData", "SPGlassMedia", "SPGlassMaps", "SPGlassAI"]59let allModules = Set(foundationModules + componentModules + ["SPGlassKit"])6061func shortName(_ module: String) -> String { String(module.dropFirst("SPGlass".count)) }6263func files(under directory: URL) -> [URL] {64 var result: [URL] = []65 let enumerator = FileManager.default.enumerator(at: directory, includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles])66 while let url = enumerator?.nextObject() as? URL {67 if (try? url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true { result.append(url) }68 }69 return result.sorted { $0.path < $1.path }70}7172func prepared(_ url: URL) throws -> Data {73 let data = try Data(contentsOf: url)74 guard url.pathExtension == "swift" else { return data }75 return Data(SourceTransform.forSourceMode(String(decoding: data, as: UTF8.self), moduleNames: allModules).utf8)76}7778/// The example source without its file header: from the first import onwards.79func exampleCode(_ url: URL) -> String? {80 guard let text = try? String(contentsOf: url, encoding: .utf8) else { return nil }81 let lines = text.components(separatedBy: "\n")82 guard let start = lines.firstIndex(where: { $0.hasPrefix("import ") }) else { return nil }83 return lines[start...].joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines) + "\n"84}8586/// Bullet points of the "Accessibility" section of a component page.87func accessibilityNotes(_ url: URL) -> [String] {88 guard let text = try? String(contentsOf: url, encoding: .utf8) else { return [] }89 var notes: [String] = []90 var inside = false91 for line in text.components(separatedBy: "\n") {92 if line.hasPrefix("## ") { inside = line.lowercased().hasPrefix("## accessibility"); continue }93 if inside, line.hasPrefix("- ") { notes.append(String(line.dropFirst(2)).trimmingCharacters(in: .whitespaces)) }94 }95 return Array(notes.prefix(32))96}9798func run() throws {99 var arguments = Array(CommandLine.arguments.dropFirst())100 if arguments.first == "keygen" {101 guard arguments.count == 2 else { throw BuilderFailure(description: "usage: GlassRegistryBuilder keygen <private-key-file>") }102 let url = URL(fileURLWithPath: arguments[1])103 guard !FileManager.default.fileExists(atPath: url.path) else { throw BuilderFailure(description: "\(url.path) already exists; a signing key is never overwritten.") }104 let key = RegistrySignature.generatePrivateKey()105 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)106 guard FileManager.default.createFile(atPath: url.path, contents: Data((key + "\n").utf8), attributes: [.posixPermissions: 0o600]) else {107 throw BuilderFailure(description: "could not write \(url.path)")108 }109 print("private key written to \(url.path) (keep it out of any repository)")110 print("public key: \(try RegistrySignature.publicKey(forPrivateKey: key))")111 return112 }113114 var options: [String: String] = [:]115 var flags: Set<String> = []116 while !arguments.isEmpty {117 let argument = arguments.removeFirst()118 switch argument {119 case "--allow-overwrite": flags.insert(argument)120 case "--root", "--output", "--version", "--date", "--signing-key-file":121 guard !arguments.isEmpty else { throw BuilderFailure(description: "\(argument) needs a value") }122 options[argument] = arguments.removeFirst()123 default: throw BuilderFailure(description: "unknown argument \(argument)")124 }125 }126 let root = URL(fileURLWithPath: options["--root"] ?? FileManager.default.currentDirectoryPath).standardizedFileURL127 let output = URL(fileURLWithPath: options["--output"] ?? "Registry", relativeTo: root).standardizedFileURL128 let version = options["--version"] ?? GlassKitInfo.version129 let formatter = DateFormatter()130 formatter.calendar = Calendar(identifier: .gregorian)131 formatter.locale = Locale(identifier: "en_US_POSIX")132 formatter.dateFormat = "yyyy-MM-dd"133 let date = options["--date"] ?? formatter.string(from: Date())134 let sources = root.appendingPathComponent("Sources")135136 struct Draft {137 var id: String, name: String, kind: String, category: String?, description: String138 var frameworks: [String] = []139 var files: [(path: String, url: URL)] = []140 var fixedDependencies: [String] = []141 }142 var drafts: [Draft] = []143144 // Foundation: every file of the four base modules, plus the licence.145 var foundation = Draft(id: "glass-foundation", name: "GlassKit Foundation", kind: GlassComponentKind.primitive.rawValue, category: nil,146 description: "Core types and localised strings, design tokens, the theme engine and the Liquid Glass surface modifiers every component builds on.")147 for module in foundationModules {148 let directory = sources.appendingPathComponent(module)149 for url in files(under: directory) {150 foundation.files.append(("\(shortName(module))/" + String(url.path.dropFirst(directory.path.count + 1)), url))151 }152 }153 foundation.files.append(("LICENSE-SPGlassKit.txt", root.appendingPathComponent("LICENSE")))154 drafts.append(foundation)155156 // Components: a file belongs to the component whose type name is the longest prefix of its base name.157 for module in componentModules {158 let directory = sources.appendingPathComponent(module)159 let components = GlassComponentCatalog.all.filter { $0.module == module }160 var owned: [String: Draft] = [:]161 for component in components {162 owned[component.name] = Draft(id: component.id, name: component.name, kind: component.kind.rawValue, category: component.category.rawValue, description: component.summary, frameworks: component.frameworks, fixedDependencies: ["glass-foundation"])163 }164 var support = Draft(id: "glass-\(shortName(module).lowercased())-support", name: "\(shortName(module)) support", kind: GlassComponentKind.primitive.rawValue, category: nil,165 description: "Helpers shared by the components of \(module).", fixedDependencies: ["glass-foundation"])166 for url in files(under: directory) {167 let relative = String(url.path.dropFirst(directory.path.count + 1))168 let path = "\(shortName(module))/\(relative)"169 let base = url.deletingPathExtension().lastPathComponent170 let isSupport = relative.hasPrefix("Support/")171 let owner = isSupport ? nil : components.map(\.name).filter { base == $0 || base.hasPrefix($0) }.max { $0.count < $1.count }172 if let owner { owned[owner]?.files.append((path, url)) } else { support.files.append((path, url)) }173 }174 for component in components {175 guard let draft = owned[component.name], !draft.files.isEmpty else {176 throw BuilderFailure(description: "component \(component.name) has no source file in Sources/\(module)")177 }178 drafts.append(draft)179 }180 if !support.files.isEmpty { drafts.append(support) }181 }182183 // Read and prepare the files, then infer dependencies from symbol usage.184 var contents: [String: [(path: String, data: Data)]] = [:]185 var declared: [String: Set<String>] = [:]186 var referenced: [String: Set<String>] = [:]187 var publicTypes: [String: [String]] = [:]188 for draft in drafts {189 var prepared_: [(String, Data)] = []190 for file in draft.files {191 let data = try prepared(file.url)192 prepared_.append((file.path, data))193 guard file.url.pathExtension == "swift" else { continue }194 let text = String(decoding: data, as: UTF8.self)195 declared[draft.id, default: []].formUnion(SwiftSourceScanner.declaredSymbols(in: text))196 referenced[draft.id, default: []].formUnion(SwiftSourceScanner.referencedIdentifiers(in: text))197 publicTypes[draft.id, default: []].append(contentsOf: SwiftSourceScanner.publicTypes(in: text))198 let foreign = SwiftSourceScanner.imports(in: text).filter { allModules.contains($0) }199 guard foreign.isEmpty else { throw BuilderFailure(description: "\(file.path) still imports \(foreign)") }200 }201 contents[draft.id] = prepared_202 }203 var owners: [String: String] = [:]204 for draft in drafts {205 for symbol in declared[draft.id] ?? [] {206 if let other = owners[symbol], other != draft.id {207 // Extensions may redeclare a name in two items; keep the first owner, which is deterministic.208 continue209 }210 owners[symbol] = draft.id211 }212 }213214 var items: [RegistryItemSource] = []215 for draft in drafts {216 var dependencies = Set(draft.fixedDependencies)217 for symbol in referenced[draft.id] ?? [] {218 if let owner = owners[symbol], owner != draft.id, !(declared[draft.id] ?? []).contains(symbol) { dependencies.insert(owner) }219 }220 if draft.id == "glass-foundation", !dependencies.isEmpty {221 throw BuilderFailure(description: "the foundation must not depend on components: \(dependencies.sorted())")222 }223 var examples: [ManifestExample] = []224 let exampleFile = files(under: root.appendingPathComponent("Examples/Gallery")).first { $0.lastPathComponent == "\(draft.name)Example.swift" }225 if let exampleFile, let code = exampleCode(exampleFile) {226 examples.append(ManifestExample(title: "\(draft.name) example", code: code))227 }228 items.append(RegistryItemSource(229 id: draft.id, name: draft.name, kind: draft.kind, category: draft.category, description: draft.description,230 dependencies: dependencies.sorted(), frameworks: draft.frameworks, files: contents[draft.id] ?? [],231 symbols: Array((publicTypes[draft.id] ?? []).prefix(200)), examples: examples,232 accessibility: accessibilityNotes(root.appendingPathComponent("docs/components/\(draft.id).md")),233 changes: ["Initial release."]234 ))235 }236237 let themes = try (GlassTheme.builtIn + GlassTheme.examples).map { theme in238 RegistryThemeSource(id: theme.id.rawValue, name: theme.name, summary: theme.summary, data: try GlassThemeCodec.encode(theme))239 }240241 var signingKey: String?242 if let keyFile = options["--signing-key-file"] {243 signingKey = try String(contentsOf: URL(fileURLWithPath: keyFile), encoding: .utf8)244 }245 let builder = RegistryBuilder(246 root: output, name: "SP Glass Registry", homepage: GlassKitInfo.websiteURL, license: GlassKitInfo.license,247 version: version, date: date, platforms: GlassPlatform.allCases.map(\.rawValue),248 minimumOS: ["iOS": "26.0", "iPadOS": "26.0", "macOS": "26.0"], allowOverwrite: flags.contains("--allow-overwrite")249 )250 let report = try builder.build(items: items, themes: themes, signingKey: signingKey)251 print("registry \(version) at \(output.path)")252 print(" items: \(items.count) (\(report.written.count) written, \(report.unchanged.count) unchanged), themes: \(themes.count), signed: \(signingKey != nil)")253 for item in items where item.kind == "primitive" {254 print(" \(item.id): \(item.files.count) files")255 }256}257258do {259 try run()260} catch {261 FileHandle.standardError.write(Data("error: \(error)\n".utf8))262 exit(1)263}264