Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Sources/GlassCLICore/ProjectFiles.swift8// Module : Glass CLICore9// 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 SPGlassRegistry4344/// `spglass.json`: where the project gets GlassKit sources from and where it puts them.45public struct ProjectConfig: Codable, Equatable, Sendable {46 public var schemaVersion: Int47 public var registry: String48 /// Directory, relative to the project root, that receives component sources.49 public var sourcesPath: String50 /// Directory, relative to the project root, that receives theme files.51 public var themesPath: String52 /// Base64 Ed25519 public key. When set, the registry index must carry a valid signature.53 public var publicKey: String?5455 public static let fileName = "spglass.json"56 public static let defaultRegistry = "https://glass.spboucher.ai/registry"5758 public init(registry: String = ProjectConfig.defaultRegistry, sourcesPath: String, themesPath: String, publicKey: String? = nil) {59 self.schemaVersion = RegistrySchema.version60 self.registry = registry; self.sourcesPath = sourcesPath; self.themesPath = themesPath; self.publicKey = publicKey61 }6263 public func validate() throws {64 guard schemaVersion == RegistrySchema.version else { throw CLIError(RegistryError.unsupportedSchema(what: ProjectConfig.fileName, version: schemaVersion)) }65 try RegistryPath.validate(sourcesPath)66 try RegistryPath.validate(themesPath)67 guard !registry.isEmpty, registry.utf8.count <= 2048 else {68 throw CLIError(code: "invalid_config", message: "The registry address in \(ProjectConfig.fileName) is empty or too long.", exitCode: .invalidData)69 }70 }71}7273/// `spglass.lock.json`: what is installed, at which version, and the checksum each file had when it was written.74public struct ProjectLock: Codable, Equatable, Sendable {75 public var schemaVersion: Int76 public var registry: String77 public var items: [LockedItem]78 public var themes: [LockedTheme]7980 public static let fileName = "spglass.lock.json"8182 public init(registry: String, items: [LockedItem] = [], themes: [LockedTheme] = []) {83 self.schemaVersion = RegistrySchema.version84 self.registry = registry; self.items = items; self.themes = themes85 }8687 public func item(_ id: String) -> LockedItem? { items.first { $0.id == id } }88 public func theme(_ id: String) -> LockedTheme? { themes.first { $0.id == id } }8990 public mutating func set(_ item: LockedItem) {91 items.removeAll { $0.id == item.id }92 items.append(item)93 items.sort { $0.id < $1.id }94 }9596 public mutating func set(_ theme: LockedTheme) {97 themes.removeAll { $0.id == theme.id }98 themes.append(theme)99 themes.sort { $0.id < $1.id }100 }101102 /// The item that owns a project-relative path, if any.103 public func owner(of path: String) -> LockedItem? {104 let key = RegistryPath.collisionKey(path)105 return items.first { $0.files.contains { RegistryPath.collisionKey($0.path) == key } }106 }107108 public func validate() throws {109 guard schemaVersion == RegistrySchema.version else { throw CLIError(RegistryError.unsupportedSchema(what: ProjectLock.fileName, version: schemaVersion)) }110 for item in items {111 try RegistryPath.validateIdentifier(item.id)112 _ = try SemanticVersion(item.version)113 for file in item.files {114 try RegistryPath.validate(file.path)115 guard RegistryHash.isSHA256(file.sha256) else {116 throw CLIError(code: "invalid_lock", message: "\(ProjectLock.fileName) holds an invalid checksum for \(item.id).", exitCode: .invalidData)117 }118 }119 }120 for theme in themes {121 try RegistryPath.validateIdentifier(theme.id)122 try RegistryPath.validate(theme.path)123 }124 }125}126127public struct LockedItem: Codable, Equatable, Sendable {128 public var id: String129 public var version: String130 public var kind: String131 /// True when the user asked for this item; false when it came as a dependency.132 public var requested: Bool133 public var dependencies: [String]134 public var digest: String135 /// Paths are relative to the project root; checksums are those of the registry files.136 public var files: [ManifestFile]137}138139public struct LockedTheme: Codable, Equatable, Sendable {140 public var id: String141 public var version: String142 public var path: String143 public var sha256: String144}145146/// A project directory: its configuration, its lock file and safe access to the files below it.147public struct Project: Sendable {148 public let root: URL149150 public init(root: URL) {151 self.root = root.standardizedFileURL152 }153154 public var configURL: URL { root.appendingPathComponent(ProjectConfig.fileName) }155 public var lockURL: URL { root.appendingPathComponent(ProjectLock.fileName) }156157 public func loadConfig() throws -> ProjectConfig {158 guard let data = try? Data(contentsOf: configURL) else {159 throw CLIError(code: "not_initialized", message: "No \(ProjectConfig.fileName) in \(root.path).", hint: "Run `spglass init` in the project directory.", exitCode: .notFound)160 }161 let config = try RegistryJSON.decode(ProjectConfig.self, from: data, what: ProjectConfig.fileName, limit: 64 * 1024)162 try config.validate()163 return config164 }165166 public func loadLock(registry: String) throws -> ProjectLock {167 guard let data = try? Data(contentsOf: lockURL) else { return ProjectLock(registry: registry) }168 let lock = try RegistryJSON.decode(ProjectLock.self, from: data, what: ProjectLock.fileName)169 try lock.validate()170 return lock171 }172173 public func save<T: Encodable>(_ value: T, to url: URL) throws {174 try RegistryJSON.encode(value).write(to: url, options: .atomic)175 }176177 /// The absolute URL of a project-relative path, after checking that the path is safe and that no existing178 /// component below the root is a symbolic link (a link could lead outside the project).179 public func url(for relativePath: String) throws -> URL {180 try RegistryPath.validate(relativePath)181 var current = root182 for component in relativePath.split(separator: "/") {183 current = current.appendingPathComponent(String(component))184 if let type = try? FileManager.default.attributesOfItem(atPath: current.path)[.type] as? FileAttributeType, type == .typeSymbolicLink {185 throw CLIError(RegistryError.unsafePath(relativePath, reason: "\"\(component)\" is a symbolic link"))186 }187 }188 return current189 }190191 public func read(_ relativePath: String) throws -> Data? {192 let url = try url(for: relativePath)193 var isDirectory: ObjCBool = false194 guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory) else { return nil }195 if isDirectory.boolValue {196 throw CLIError(RegistryError.unsafePath(relativePath, reason: "a directory is in the way"))197 }198 return try Data(contentsOf: url)199 }200}201202/// What kind of project a directory holds, and where sources would naturally go.203public struct ProjectDetection: Equatable, Sendable, Encodable {204 public enum Kind: String, Sendable, Encodable { case swiftPackage, xcodeProject, unknown }205 public var kind: Kind206 public var suggestedSourcesPath: String?207 public var notes: [String]208209 public static func detect(in root: URL) -> ProjectDetection {210 let fileManager = FileManager.default211 let entries = ((try? fileManager.contentsOfDirectory(atPath: root.path)) ?? []).sorted()212 func isDirectory(_ path: String) -> Bool {213 var flag: ObjCBool = false214 return fileManager.fileExists(atPath: root.appendingPathComponent(path).path, isDirectory: &flag) && flag.boolValue215 }216 if entries.contains("Package.swift") {217 let targets = ((try? fileManager.contentsOfDirectory(atPath: root.appendingPathComponent("Sources").path)) ?? [])218 .filter { !$0.hasPrefix(".") && isDirectory("Sources/\($0)") && (try? RegistryPath.validate($0)) != nil }.sorted()219 if targets.count == 1 {220 return ProjectDetection(kind: .swiftPackage, suggestedSourcesPath: "Sources/\(targets[0])/GlassKit", notes: [221 "Swift package with one target: sources go inside it and are compiled with it.",222 "Declare `resources: [.process(\"GlassKit/Core/Resources\")]` on the target so that GlassKit's strings are bundled.",223 ])224 }225 return ProjectDetection(kind: .swiftPackage, suggestedSourcesPath: nil, notes: [226 targets.isEmpty ? "No target directory was found under Sources/." : "Several targets were found: \(targets.joined(separator: ", ")).",227 "Choose the target with `spglass init --path Sources/<Target>/GlassKit`.",228 ])229 }230 let projects = entries.filter { $0.hasSuffix(".xcodeproj") }231 if !projects.isEmpty {232 let name = String(projects[0].dropLast(".xcodeproj".count))233 if projects.count == 1, isDirectory(name), (try? RegistryPath.validate(name)) != nil {234 return ProjectDetection(kind: .xcodeProject, suggestedSourcesPath: "\(name)/GlassKit", notes: [235 "Xcode project \"\(projects[0])\" with a source folder \"\(name)\".",236 "spglass never edits the project file. If \"\(name)\" is a synchronized folder (Xcode 16 and later), the new files are picked up automatically; otherwise drag the GlassKit folder into the project navigator and add it to the app target.",237 ])238 }239 return ProjectDetection(kind: .xcodeProject, suggestedSourcesPath: nil, notes: [240 "The layout of the Xcode project is ambiguous (\(projects.count) project file(s), no source folder named after the project).",241 "Choose the folder with `spglass init --path <AppFolder>/GlassKit`, then add that folder to the app target in Xcode.",242 ])243 }244 return ProjectDetection(kind: .unknown, suggestedSourcesPath: nil, notes: [245 "No Package.swift or .xcodeproj here.",246 "Choose the folder with `spglass init --path <dir>`.",247 ])248 }249}250