SPB Git

Repository Public MIT

CLI.swift 6.3 KB 127 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/GlassCLICore/CLI.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/// The outcome of one invocation: what to print and the exit code.45public struct CLIOutcome: Sendable {46    public var exitCode: Int3247    public var standardOutput: String48    public var standardError: String49}5051/// Entry point of `spglass`, independent of the process so that tests can call it directly.52public enum CLI {53    public static func run(54        arguments: [String],55        currentDirectory: URL,56        environment: [String: String] = [:],57        sourceOverride: (any RegistrySource)? = nil,58        failAfterChanges: Int? = nil59    ) async -> CLIOutcome {60        let wantsJSON = arguments.contains("--json")61        do {62            let parsed = try ArgumentParser.parse(arguments)63            if parsed.flag("version"), parsed.command.isEmpty {64                return success(CommandOutput(text: "spglass \(CLIVersion.current)\n", json: ["version": .string(CLIVersion.current), "schemaVersion": .int(RegistrySchema.version)]), command: "version", json: wantsJSON)65            }66            if parsed.command.isEmpty || parsed.flag("help") {67                let text = ArgumentParser.help(for: parsed.command) ?? ArgumentParser.helpText68                return success(CommandOutput(text: text, json: ["help": .string(text)]), command: "help", json: wantsJSON)69            }70            var root = currentDirectory71            if let cwd = parsed.option("cwd") {72                root = URL(fileURLWithPath: cwd, relativeTo: currentDirectory)73                var isDirectory: ObjCBool = false74                guard FileManager.default.fileExists(atPath: root.path, isDirectory: &isDirectory), isDirectory.boolValue else {75                    throw CLIError.usage("--cwd \"\(RegistryText.clip(cwd))\" is not a directory.")76                }77            }78            let context = CommandContext(arguments: parsed, project: Project(root: root), environment: environment, sourceOverride: sourceOverride, failAfterChanges: failAfterChanges)79            let output: CommandOutput80            switch parsed.command {81            case "init": output = try Commands.initialize(context)82            case "list": output = try await Commands.list(context)83            case "info": output = try await Commands.info(context)84            case "add": output = try await Commands.add(context, update: false)85            case "update": output = try await Commands.add(context, update: true)86            case "remove": output = try await Commands.remove(context)87            case "diff": output = try await Commands.diff(context)88            case "verify": output = try Commands.verify(context)89            case "doctor": output = await Commands.doctor(context)90            case "theme add": output = try await Commands.themeAdd(context)91            case "theme list": output = try await Commands.list(context, themesOnly: true)92            case "export": output = try await Commands.export(context)93            default: throw CLIError.usage("Unknown command \"\(RegistryText.clip(parsed.command))\".")94            }95            return success(output, command: parsed.command, json: wantsJSON)96        } catch {97            return failure(CLIError.wrap(error), json: wantsJSON)98        }99    }100101    private static func success(_ output: CommandOutput, command: String, json: Bool) -> CLIOutcome {102        guard json else { return CLIOutcome(exitCode: output.exitCode.rawValue, standardOutput: output.text, standardError: "") }103        let envelope: JSONValue = ["ok": .bool(output.exitCode == .success), "command": .string(command), "result": output.json]104        return CLIOutcome(exitCode: output.exitCode.rawValue, standardOutput: encode(envelope), standardError: "")105    }106107    private static func failure(_ error: CLIError, json: Bool) -> CLIOutcome {108        if json {109            let envelope: JSONValue = ["ok": false, "error": [110                "code": .string(error.code), "message": .string(error.message), "hint": .optional(error.hint), "details": .optional(error.details),111            ]]112            return CLIOutcome(exitCode: error.exitCode.rawValue, standardOutput: encode(envelope), standardError: "")113        }114        var text = "error: \(error.message)\n"115        if let details = error.details, !details.isEmpty { text += "\n\(details)\n" }116        if let hint = error.hint { text += "hint: \(hint)\n" }117        return CLIOutcome(exitCode: error.exitCode.rawValue, standardOutput: "", standardError: text)118    }119120    private static func encode(_ value: JSONValue) -> String {121        let encoder = JSONEncoder()122        encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]123        guard let data = try? encoder.encode(value) else { return "{\"ok\":false}\n" }124        return String(decoding: data, as: UTF8.self) + "\n"125    }126}127
Files main
Menu

Theme