Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Sources/GlassCLICore/Commands.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 SPGlassCore43import SPGlassRegistry44import SPGlassThemes4546/// Everything a command needs: the project, how to reach the registry, and the parsed arguments.47public struct CommandContext: Sendable {48 public var arguments: ParsedArguments49 public var project: Project50 public var environment: [String: String]51 /// Replaces the configured registry, for tests.52 public var sourceOverride: (any RegistrySource)?53 /// Test hook passed to the file transaction.54 public var failAfterChanges: Int?5556 public init(arguments: ParsedArguments, project: Project, environment: [String: String], sourceOverride: (any RegistrySource)? = nil, failAfterChanges: Int? = nil) {57 self.arguments = arguments; self.project = project; self.environment = environment58 self.sourceOverride = sourceOverride; self.failAfterChanges = failAfterChanges59 }6061 var offline: Bool { arguments.flag("offline") }6263 func timeout() throws -> TimeInterval {64 guard let text = arguments.option("timeout") else { return 20 }65 guard let seconds = Int(text), (1...300).contains(seconds) else { throw CLIError.usage("--timeout takes a number of seconds between 1 and 300.") }66 return TimeInterval(seconds)67 }6869 /// The registry client for an address: a local directory or an HTTPS URL, behind the cache.70 func client(registry: String, publicKey: String?) throws -> RegistryClient {71 let key = arguments.option("public-key") ?? publicKey72 if let sourceOverride { return RegistryClient(source: sourceOverride, publicKey: key) }73 let address = arguments.option("registry") ?? registry74 let source: any RegistrySource75 if address.lowercased().hasPrefix("https://") || address.lowercased().hasPrefix("http://") {76 guard let url = URL(string: address) else { throw CLIError.usage("\"\(RegistryText.clip(address))\" is not a valid URL.") }77 source = CachingRegistrySource(upstream: try HTTPRegistrySource(baseURL: url, timeout: try timeout()), cacheRoot: CachingRegistrySource.defaultCacheRoot(environment: environment), offline: offline)78 } else {79 let url = URL(fileURLWithPath: address, relativeTo: project.root).standardizedFileURL80 var isDirectory: ObjCBool = false81 guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory), isDirectory.boolValue else {82 throw CLIError(code: "registry_not_found", message: "The registry directory \"\(RegistryText.clip(address))\" does not exist.", exitCode: .notFound)83 }84 source = LocalDirectorySource(root: url)85 }86 return RegistryClient(source: source, publicKey: key)87 }8889 func transaction() -> FileTransaction {90 var transaction = FileTransaction(project: project)91 transaction.failAfterChanges = failAfterChanges92 return transaction93 }94}9596enum Commands {97 // MARK: init9899 static func initialize(_ context: CommandContext) throws -> CommandOutput {100 let project = context.project101 if FileManager.default.fileExists(atPath: project.configURL.path), !context.arguments.flag("force") {102 throw CLIError(code: "already_initialized", message: "\(ProjectConfig.fileName) already exists.", hint: "Use --force to replace it.", exitCode: .conflict)103 }104 let detection = ProjectDetection.detect(in: project.root)105 guard let sourcesPath = context.arguments.option("path") ?? detection.suggestedSourcesPath else {106 throw CLIError(code: "ambiguous_project", message: "The place for GlassKit sources cannot be chosen automatically.", hint: detection.notes.joined(separator: " "), exitCode: .usage)107 }108 // Not "Themes": that is the directory of the foundation's own theme sources.109 let themesPath = context.arguments.option("themes-path") ?? sourcesPath + "/CustomThemes"110 let registry = context.arguments.option("registry") ?? ProjectConfig.defaultRegistry111 let config = ProjectConfig(registry: registry, sourcesPath: sourcesPath, themesPath: themesPath, publicKey: context.arguments.option("public-key"))112 try config.validate()113 _ = try project.url(for: sourcesPath)114 _ = try project.url(for: themesPath)115 if !(registry.lowercased().hasPrefix("https://")) {116 // A local registry must exist; an http:// one is refused by the client.117 _ = try context.client(registry: registry, publicKey: nil)118 }119 try project.save(config, to: project.configURL)120121 var text = "Wrote \(ProjectConfig.fileName)\n project: \(detection.kind.rawValue)\n sources: \(sourcesPath)\n themes: \(themesPath)\n registry: \(registry)\n"122 if !detection.notes.isEmpty { text += "\nIntegration:\n" + detection.notes.map { " - \($0)\n" }.joined() }123 text += "\nNext: spglass add glass-button\n"124 return CommandOutput(text: text, json: [125 "config": .from(config), "project": .from(detection),126 ])127 }128129 // MARK: list / info130131 static func list(_ context: CommandContext, themesOnly: Bool = false) async throws -> CommandOutput {132 let config = try? context.project.loadConfig()133 let client = try context.client(registry: config?.registry ?? ProjectConfig.defaultRegistry, publicKey: config?.publicKey)134 let index = try await client.index()135 let lock = try? context.project.loadLock(registry: client.identity)136137 if themesOnly || context.arguments.flag("themes") {138 var text = ""139 var rows: [JSONValue] = []140 for theme in index.themes {141 let installed = lock?.theme(theme.id) != nil142 text += "\(installed ? "✓" : " ") \(theme.id.padding(toLength: 22, withPad: " ", startingAt: 0)) \(theme.latest.padding(toLength: 8, withPad: " ", startingAt: 0)) \(RegistryText.clip(theme.summary, limit: 90))\n"143 rows.append(["id": .string(theme.id), "name": .string(theme.name), "latest": .string(theme.latest), "installed": .bool(installed), "summary": .string(theme.summary)])144 }145 return CommandOutput(text: text.isEmpty ? "No theme in the registry.\n" : text, json: ["themes": .array(rows)])146 }147148 let category = context.arguments.option("category")149 let kind = context.arguments.option("kind")150 if let kind, !RegistryValidator.knownKinds.contains(kind) {151 throw CLIError.usage("Unknown kind \"\(RegistryText.clip(kind))\". Kinds: " + RegistryValidator.knownKinds.sorted().joined(separator: ", ") + ".")152 }153 let categories = Set(index.items.compactMap(\.category))154 if let category, !categories.contains(category) {155 throw CLIError.usage("Unknown category \"\(RegistryText.clip(category))\". Categories: " + categories.sorted().joined(separator: ", ") + ".")156 }157 var text = ""158 var rows: [JSONValue] = []159 for item in index.items {160 if let category, item.category != category { continue }161 if let kind, item.kind != kind { continue }162 let installed = lock?.item(item.id)163 if context.arguments.flag("installed"), installed == nil { continue }164 text += "\(installed == nil ? " " : "✓") \(item.id.padding(toLength: 26, withPad: " ", startingAt: 0)) \(item.latest.padding(toLength: 8, withPad: " ", startingAt: 0)) \(item.kind.padding(toLength: 18, withPad: " ", startingAt: 0)) \(item.category ?? "-")\n"165 rows.append([166 "id": .string(item.id), "name": .string(item.name), "kind": .string(item.kind), "category": .optional(item.category),167 "latest": .string(item.latest), "installed": .optional(installed?.version), "summary": .string(item.summary),168 ])169 }170 return CommandOutput(text: text.isEmpty ? "No matching component.\n" : text, json: ["items": .array(rows)])171 }172173 static func info(_ context: CommandContext) async throws -> CommandOutput {174 let config = try? context.project.loadConfig()175 let client = try context.client(registry: config?.registry ?? ProjectConfig.defaultRegistry, publicKey: config?.publicKey)176 let index = try await client.index()177 let id = context.arguments.positionals[0]178 let manifest = try await client.manifest(id: id, version: context.arguments.option("version"), index: index)179 let versions = index.item(id)?.versions.map(\.version) ?? []180 var text = "\(manifest.name) (\(manifest.id)) \(manifest.version)\n\(manifest.description)\n\n"181 text += " kind: \(manifest.kind)\n category: \(manifest.category ?? "-")\n licence: \(manifest.license)\n"182 text += " platforms: " + manifest.platforms.map { "\($0) \(manifest.minimumOS[$0] ?? "")" }.joined(separator: ", ") + "\n"183 text += " versions: \(versions.joined(separator: ", "))\n"184 text += " depends on: \(manifest.dependencies.isEmpty ? "-" : manifest.dependencies.map { "\($0.id) \($0.version)" }.joined(separator: ", "))\n"185 if !manifest.frameworks.isEmpty { text += " frameworks: \(manifest.frameworks.joined(separator: ", "))\n" }186 text += " symbols: \(manifest.symbols.joined(separator: ", "))\n files:\n"187 for file in manifest.files { text += " \(file.path) (\(file.bytes) bytes)\n" }188 if !manifest.accessibility.isEmpty { text += " accessibility:\n" + manifest.accessibility.map { " - \($0)\n" }.joined() }189 if let example = manifest.examples.first { text += "\n\(example.title):\n\n\(example.code)\n" }190 return CommandOutput(text: text, json: ["manifest": .from(manifest), "versions": .strings(versions)])191 }192193 // MARK: add / update194195 static func add(_ context: CommandContext, update: Bool) async throws -> CommandOutput {196 let project = context.project197 let recovered = FileTransaction.recover(project: project)198 let config = try project.loadConfig()199 let client = try context.client(registry: config.registry, publicKey: config.publicKey)200 let lock = try project.loadLock(registry: client.identity)201202 var roots = context.arguments.positionals203 if update, roots.isEmpty { roots = lock.items.filter(\.requested).map(\.id) }204 if update {205 for root in roots where lock.item(root) == nil {206 throw CLIError(code: "not_installed", message: "\"\(RegistryText.clip(root))\" is not installed.", hint: "Use `spglass add \(RegistryText.clip(root))`.", exitCode: .notFound)207 }208 }209 if roots.isEmpty {210 return CommandOutput(text: "Nothing is installed.\n", json: ["items": [], "applied": false])211 }212 if context.arguments.option("version") != nil, roots.count != 1 {213 throw CLIError.usage("--version applies to exactly one component.")214 }215 if context.arguments.flag("overwrite"), context.arguments.flag("write-incoming") {216 throw CLIError.usage("--overwrite and --write-incoming are mutually exclusive.")217 }218219 let planner = InstallPlanner(project: project, config: config, client: client)220 let options = InstallOptions(overwrite: context.arguments.flag("overwrite"), writeIncoming: context.arguments.flag("write-incoming"), preferInstalledVersion: !update)221 let plan = try await planner.plan(roots: roots, version: context.arguments.option("version"), lock: lock, options: options)222223 let dryRun = context.arguments.flag("dry-run")224 var text = recovered > 0 ? "Recovered \(recovered) interrupted operation\(recovered == 1 ? "" : "s"): the project was restored to its previous state.\n" : ""225 text += describe(plan)226 if !client.isAuthenticated, !dryRun, !plan.isNoOp {227 text += "Note: files were checked against the registry's checksums. No public key is configured, so the registry index itself is not authenticated.\n"228 }229 var json: [String: JSONValue] = ["items": .from(plan.items), "dryRun": .bool(dryRun), "authenticated": .bool(client.isAuthenticated)]230231 if dryRun {232 json["applied"] = false233 json["conflicts"] = .strings(plan.conflicts.map(\.path))234 if plan.hasConflicts { text += "\nConflicts would stop this operation:\n" + plan.conflicts.map { " \($0.path)\n" }.joined() }235 return CommandOutput(text: text + "\nDry run: nothing was changed.\n", json: .object(json), exitCode: plan.hasConflicts ? .conflict : .success)236 }237 if plan.isNoOp, plan.lock == lock {238 json["applied"] = false239 return CommandOutput(text: text + "\nEverything is up to date.\n", json: .object(json))240 }241 try await planner.apply(plan, transaction: context.transaction())242 json["applied"] = true243 let incoming = plan.items.flatMap(\.files).filter { $0.action == .incoming }244 if !incoming.isEmpty {245 text += "\nKept your version of \(incoming.count) file\(incoming.count == 1 ? "" : "s"). Merge by hand, then delete the .incoming copies:\n" + incoming.map { " \($0.path).incoming\n" }.joined()246 }247 return CommandOutput(text: text + "\nDone. \(ProjectLock.fileName) updated.\n", json: .object(json))248 }249250 private static func describe(_ plan: InstallPlan) -> String {251 var text = ""252 for item in plan.items {253 let version = item.fromVersion.map { $0 == item.toVersion ? item.toVersion : "\($0) → \(item.toVersion)" } ?? item.toVersion254 text += "\(item.action.rawValue.padding(toLength: 10, withPad: " ", startingAt: 0)) \(item.id) \(version)\(item.requested ? "" : " (dependency)")\n"255 for file in item.files where file.action != .unchanged {256 text += " \(file.action.rawValue.padding(toLength: 14, withPad: " ", startingAt: 0)) \(file.path)\n"257 }258 }259 return text260 }261262 // MARK: remove263264 static func remove(_ context: CommandContext) async throws -> CommandOutput {265 let project = context.project266 FileTransaction.recover(project: project)267 let config = try project.loadConfig()268 var lock = try project.loadLock(registry: config.registry)269 let force = context.arguments.flag("force")270 var targets: [String] = []271 for id in context.arguments.positionals {272 try RegistryPath.validateIdentifier(id)273 guard lock.item(id) != nil else {274 throw CLIError(code: "not_installed", message: "\"\(id)\" is not installed.", exitCode: .notFound)275 }276 if !targets.contains(id) { targets.append(id) }277 }278 let graph = Dictionary(uniqueKeysWithValues: lock.items.map { ($0.id, $0.dependencies) })279 if !force {280 for id in targets {281 let dependents = DependencyGraph.dependents(of: id, in: graph).filter { !targets.contains($0) }282 if !dependents.isEmpty {283 throw CLIError(code: "has_dependents", message: "\"\(id)\" is needed by: \(dependents.joined(separator: ", ")). Nothing was changed.", hint: "Remove those first, or use --force.", exitCode: .conflict)284 }285 }286 }287 if context.arguments.flag("prune") {288 // Dependencies nobody asked for and nothing else needs go too.289 var changed = true290 while changed {291 changed = false292 for item in lock.items where !item.requested && !targets.contains(item.id) {293 let remaining = DependencyGraph.dependents(of: item.id, in: graph).filter { !targets.contains($0) }294 if remaining.isEmpty { targets.append(item.id); changed = true }295 }296 }297 }298299 var changes: [FileChange] = []300 var deleted: [String] = [], kept: [String] = [], missing: [String] = []301 for id in targets {302 for file in lock.item(id)?.files ?? [] {303 guard let local = try project.read(file.path) else { missing.append(file.path); continue }304 if RegistryHash.sha256(local) == file.sha256 || force {305 changes.append(.delete(file.path)); deleted.append(file.path)306 } else {307 kept.append(file.path)308 }309 }310 lock.items.removeAll { $0.id == id }311 }312 var text = targets.map { "remove \($0)\n" }.joined()313 text += deleted.map { " delete \($0)\n" }.joined()314 if !kept.isEmpty {315 text += "\nKept because you modified them (they are yours now and no longer tracked):\n" + kept.map { " \($0)\n" }.joined()316 }317 let json: JSONValue = ["removed": .strings(targets), "deleted": .strings(deleted), "kept": .strings(kept), "missing": .strings(missing), "dryRun": .bool(context.arguments.flag("dry-run"))]318 if context.arguments.flag("dry-run") {319 return CommandOutput(text: text + "\nDry run: nothing was changed.\n", json: json)320 }321 changes.append(.write(ProjectLock.fileName, try RegistryJSON.encode(lock)))322 try await context.transaction().apply(changes)323 return CommandOutput(text: text + "\nDone.\n", json: json)324 }325326 // MARK: diff / verify327328 static func diff(_ context: CommandContext) async throws -> CommandOutput {329 let project = context.project330 let config = try project.loadConfig()331 let client = try context.client(registry: config.registry, publicKey: config.publicKey)332 let lock = try project.loadLock(registry: client.identity)333 let ids = context.arguments.positionals.isEmpty ? lock.items.map(\.id) : context.arguments.positionals334 var index: RegistryIndex?335 var text = ""336 var rows: [JSONValue] = []337 for id in ids {338 guard let item = lock.item(id) else {339 throw CLIError(code: "not_installed", message: "\"\(RegistryText.clip(id))\" is not installed.", exitCode: .notFound)340 }341 var manifest: ComponentManifest?342 for file in item.files {343 let local = try project.read(file.path)344 if let local, RegistryHash.sha256(local) == file.sha256 { continue }345 guard let local else {346 text += "missing \(file.path)\n"347 rows.append(["id": .string(id), "path": .string(file.path), "state": "missing", "diff": ""])348 continue349 }350 // Fetch the installed version of the file to compare with.351 if index == nil { index = try await client.index() }352 if manifest == nil, let index { manifest = try await client.manifest(id: id, version: item.version, index: index) }353 let prefix = config.sourcesPath + "/"354 var patch = ""355 if let manifest, let original = manifest.files.first(where: { prefix + $0.path == file.path }) {356 let data = try await client.file(original, of: manifest)357 patch = LineDiff.unified(old: String(decoding: data, as: UTF8.self), new: String(decoding: local, as: UTF8.self), oldLabel: "registry/\(file.path) (\(item.version))", newLabel: "local/\(file.path)")358 }359 text += patch.isEmpty ? "modified \(file.path)\n" : patch360 rows.append(["id": .string(id), "path": .string(file.path), "state": "modified", "diff": .string(patch)])361 }362 }363 return CommandOutput(text: text.isEmpty ? "No local change.\n" : text, json: ["changes": .array(rows)])364 }365366 static func verify(_ context: CommandContext) throws -> CommandOutput {367 let project = context.project368 let config = try project.loadConfig()369 let lock = try project.loadLock(registry: config.registry)370 var ok = 0371 var modified: [String] = [], missing: [String] = []372 for item in lock.items {373 for file in item.files {374 guard let local = try project.read(file.path) else { missing.append(file.path); continue }375 if RegistryHash.sha256(local) == file.sha256 { ok += 1 } else { modified.append(file.path) }376 }377 }378 for theme in lock.themes {379 guard let local = try project.read(theme.path) else { missing.append(theme.path); continue }380 if RegistryHash.sha256(local) == theme.sha256 { ok += 1 } else { modified.append(theme.path) }381 }382 var text = "\(lock.items.count) component\(lock.items.count == 1 ? "" : "s"), \(lock.themes.count) theme\(lock.themes.count == 1 ? "" : "s"): \(ok) file\(ok == 1 ? "" : "s") identical to the registry version.\n"383 if !modified.isEmpty { text += "\nModified locally (expected when you customise a component):\n" + modified.map { " \($0)\n" }.joined() }384 if !missing.isEmpty { text += "\nMissing:\n" + missing.map { " \($0)\n" }.joined() + "Restore them with `spglass add <id>`.\n" }385 let failed = !missing.isEmpty || (context.arguments.flag("strict") && !modified.isEmpty)386 return CommandOutput(387 text: text,388 json: ["identical": .int(ok), "modified": .strings(modified), "missing": .strings(missing), "strict": .bool(context.arguments.flag("strict"))],389 exitCode: failed ? .integrity : .success390 )391 }392393 // MARK: themes394395 static func themeAdd(_ context: CommandContext) async throws -> CommandOutput {396 let project = context.project397 FileTransaction.recover(project: project)398 let config = try project.loadConfig()399 let client = try context.client(registry: config.registry, publicKey: config.publicKey)400 var lock = try project.loadLock(registry: client.identity)401 let index = try await client.index()402 if context.arguments.option("version") != nil, context.arguments.positionals.count != 1 {403 throw CLIError.usage("--version applies to exactly one theme.")404 }405 var changes: [FileChange] = []406 var rows: [JSONValue] = []407 var text = ""408 var conflicts: [(path: String, diff: String)] = []409 for id in context.arguments.positionals {410 let fetched = try await client.theme(id: id, version: context.arguments.option("version"), index: index)411 let path = config.themesPath + "/\(id).json"412 let local = try project.read(path)413 let action: FilePlan.Action414 if let local {415 let hash = RegistryHash.sha256(local)416 if hash == fetched.version.sha256 { action = .unchanged }417 else if lock.theme(id)?.sha256 == hash { action = .replace }418 else if context.arguments.flag("overwrite") { action = .overwrite }419 else { action = .conflict }420 } else {421 action = .create422 }423 switch action {424 case .create, .replace: changes.append(.write(path, fetched.data))425 case .overwrite:426 changes.append(.write(path + ".orig", local ?? Data()))427 changes.append(.write(path, fetched.data))428 case .conflict:429 conflicts.append((path, LineDiff.unified(old: String(decoding: local ?? Data(), as: UTF8.self), new: String(decoding: fetched.data, as: UTF8.self), oldLabel: "local/\(path)", newLabel: "registry/\(path) (\(fetched.version.version))")))430 default: break431 }432 lock.set(LockedTheme(id: id, version: fetched.version.version, path: path, sha256: fetched.version.sha256))433 text += "\(action.rawValue.padding(toLength: 10, withPad: " ", startingAt: 0)) \(path) (\(fetched.theme.name) \(fetched.version.version))\n"434 rows.append(["id": .string(id), "path": .string(path), "action": .string(action.rawValue), "version": .string(fetched.version.version)])435 }436 let dryRun = context.arguments.flag("dry-run")437 if !conflicts.isEmpty, !dryRun { throw InstallPlanner.conflictError(conflicts) }438 if dryRun {439 return CommandOutput(text: text + "\nDry run: nothing was changed.\n", json: ["themes": .array(rows), "applied": false], exitCode: conflicts.isEmpty ? .success : .conflict)440 }441 changes.append(.write(ProjectLock.fileName, try RegistryJSON.encode(lock)))442 try await context.transaction().apply(changes)443 return CommandOutput(text: text + "\nDone. Load a theme with GlassThemeCodec.decode(_:) or generate Swift with `spglass export --format swift`.\n", json: ["themes": .array(rows), "applied": true])444 }445446 static func export(_ context: CommandContext) async throws -> CommandOutput {447 let project = context.project448 let config = try project.loadConfig()449 let lock = try project.loadLock(registry: config.registry)450 guard let format = context.arguments.option("format"), ["swift", "json"].contains(format) else {451 throw CLIError.usage("--format must be swift or json.")452 }453 var themes = lock.themes454 if let only = context.arguments.option("theme") {455 themes = themes.filter { $0.id == only }456 guard !themes.isEmpty else { throw CLIError(code: "not_installed", message: "Theme \"\(RegistryText.clip(only))\" is not installed.", hint: "Use `spglass theme add \(RegistryText.clip(only))`.", exitCode: .notFound) }457 }458 guard !themes.isEmpty else {459 throw CLIError(code: "nothing_to_export", message: "No theme is installed.", hint: "Use `spglass theme add <id>` first.", exitCode: .notFound)460 }461 let output = context.arguments.option("output") ?? config.themesPath462 try RegistryPath.validate(output)463 // In source mode the generated file lives in the same module as the GlassKit sources: no import.464 let sourceMode = lock.item("glass-foundation") != nil465 var changes: [FileChange] = []466 var written: [String] = []467 for locked in themes {468 guard let data = try project.read(locked.path) else {469 throw CLIError(code: "missing_file", message: "\(locked.path) is missing.", hint: "Restore it with `spglass theme add \(locked.id)`.", exitCode: .integrity)470 }471 let theme: GlassTheme472 do { theme = try GlassThemeCodec.decode(data) } catch {473 throw CLIError(code: "invalid_theme", message: "\(locked.path): \(error.description)", exitCode: .invalidData)474 }475 let name = GlassThemeSwiftExporter.propertyName(for: theme.id).replacingOccurrences(of: "`", with: "")476 let path: String, content: Data477 if format == "swift" {478 path = "\(output)/GlassTheme+\(name.prefix(1).uppercased() + name.dropFirst()).swift"479 content = Data(GlassThemeSwiftExporter.source(for: theme, moduleImport: sourceMode ? nil : "SPGlassKit").utf8)480 } else {481 path = "\(output)/\(theme.id.rawValue).export.json"482 do { content = try GlassThemeCodec.encode(theme) } catch {483 throw CLIError(code: "invalid_theme", message: error.description, exitCode: .invalidData)484 }485 }486 if let existing = try project.read(path), existing != content, !context.arguments.flag("overwrite") {487 throw CLIError(code: "local_modifications", message: "\(path) already exists with different content. Nothing was changed.", hint: "Use --overwrite to replace it.", exitCode: .conflict)488 }489 changes.append(.write(path, content))490 written.append(path)491 }492 try await context.transaction().apply(changes)493 return CommandOutput(text: written.map { "wrote \($0)\n" }.joined(), json: ["written": .strings(written), "format": .string(format)])494 }495496 // MARK: doctor497498 static func doctor(_ context: CommandContext) async -> CommandOutput {499 struct Check { let name: String; let status: String; let detail: String }500 var checks: [Check] = []501 let project = context.project502 let detection = ProjectDetection.detect(in: project.root)503 checks.append(Check(name: "project", status: detection.kind == .unknown ? "warning" : "ok", detail: "\(detection.kind.rawValue) at \(project.root.path)"))504505 let leftovers = (try? FileManager.default.contentsOfDirectory(atPath: project.root.appendingPathComponent(FileTransaction.stagingDirectoryName).path))?.count ?? 0506 checks.append(Check(name: "interrupted operations", status: leftovers == 0 ? "ok" : "warning", detail: leftovers == 0 ? "none" : "\(leftovers) found; the next add, update or remove rolls them back"))507508 var config: ProjectConfig?509 do {510 config = try project.loadConfig()511 checks.append(Check(name: "configuration", status: "ok", detail: "\(ProjectConfig.fileName): sources in \(config?.sourcesPath ?? ""), themes in \(config?.themesPath ?? "")"))512 } catch {513 let wrapped = CLIError.wrap(error)514 checks.append(Check(name: "configuration", status: wrapped.code == "not_initialized" ? "warning" : "error", detail: wrapped.message))515 }516517 if let config {518 do {519 let lock = try project.loadLock(registry: config.registry)520 var missing = 0, modified = 0521 for file in lock.items.flatMap(\.files) {522 guard let data = try project.read(file.path) else { missing += 1; continue }523 if RegistryHash.sha256(data) != file.sha256 { modified += 1 }524 }525 checks.append(Check(name: "installed files", status: missing > 0 ? "error" : "ok", detail: "\(lock.items.count) components; \(modified) file(s) modified locally; \(missing) missing"))526 if detection.kind == .swiftPackage, lock.item("glass-foundation") != nil {527 let manifest = (try? String(contentsOf: project.root.appendingPathComponent("Package.swift"), encoding: .utf8)) ?? ""528 let declared = manifest.contains("Resources\")")529 checks.append(Check(name: "resources", status: declared ? "ok" : "warning", detail: declared ? "the target declares GlassKit's resources" : "Package.swift does not seem to declare `.process(\"GlassKit/Core/Resources\")`; GlassKit's localised strings would be missing"))530 }531 } catch {532 checks.append(Check(name: "lock file", status: "error", detail: CLIError.wrap(error).message))533 }534 do {535 let client = try context.client(registry: config.registry, publicKey: config.publicKey)536 let index = try await client.index()537 checks.append(Check(name: "registry", status: "ok", detail: "\(client.identity): \(index.items.count) items, \(index.themes.count) themes\(context.offline ? " (from cache)" : "")"))538 checks.append(Check(name: "authenticity", status: client.isAuthenticated ? "ok" : "warning", detail: client.isAuthenticated ? "the index signature matches the configured public key" : "no public key configured: files are checksummed, the index is not authenticated"))539 } catch {540 let wrapped = CLIError.wrap(error)541 checks.append(Check(name: "registry", status: wrapped.exitCode == .network ? "warning" : "error", detail: wrapped.message))542 }543 }544545 let failed = checks.contains { $0.status == "error" }546 let symbols = ["ok": "✓", "warning": "!", "error": "✗"]547 let text = checks.map { "\(symbols[$0.status] ?? "?") \($0.name.padding(toLength: 24, withPad: " ", startingAt: 0)) \($0.detail)\n" }.joined()548 return CommandOutput(549 text: text + (failed ? "\nProblems were found.\n" : "\nNo blocking problem.\n"),550 json: ["checks": .array(checks.map { ["name": .string($0.name), "status": .string($0.status), "detail": .string($0.detail)] })],551 exitCode: failed ? .failure : .success552 )553 }554}555