SPB Git

Repository Public MIT

JSONValue.swift 4.9 KB 112 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/GlassCLICore/JSONValue.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 Foundation4243/// A JSON value assembled by commands for `--json` output.44public enum JSONValue: Encodable, Equatable, Sendable, ExpressibleByStringLiteral, ExpressibleByBooleanLiteral, ExpressibleByIntegerLiteral, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral {45    case null46    case bool(Bool)47    case int(Int)48    case string(String)49    case array([JSONValue])50    case object([String: JSONValue])5152    public init(stringLiteral value: String) { self = .string(value) }53    public init(booleanLiteral value: Bool) { self = .bool(value) }54    public init(integerLiteral value: Int) { self = .int(value) }55    public init(arrayLiteral elements: JSONValue...) { self = .array(elements) }56    public init(dictionaryLiteral elements: (String, JSONValue)...) { self = .object(Dictionary(elements, uniquingKeysWith: { $1 })) }5758    public static func strings(_ values: [String]) -> JSONValue { .array(values.map(JSONValue.string)) }59    public static func optional(_ value: String?) -> JSONValue { value.map(JSONValue.string) ?? .null }6061    /// Converts any `Encodable` value by encoding and re-reading it.62    public static func from<T: Encodable>(_ value: T) -> JSONValue {63        guard let data = try? JSONEncoder().encode(value), let object = try? JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed]) else { return .null }64        return convert(object)65    }6667    private static func convert(_ object: Any) -> JSONValue {68        switch object {69        case let value as String: return .string(value)70        case let value as NSNumber:71            if CFGetTypeID(value) == CFBooleanGetTypeID() { return .bool(value.boolValue) }72            return .int(value.intValue)73        case let value as [Any]: return .array(value.map(convert))74        case let value as [String: Any]: return .object(value.mapValues(convert))75        default: return .null76        }77    }7879    public func encode(to encoder: any Encoder) throws {80        var container = encoder.singleValueContainer()81        switch self {82        case .null: try container.encodeNil()83        case .bool(let value): try container.encode(value)84        case .int(let value): try container.encode(value)85        case .string(let value): try container.encode(value)86        case .array(let value): try container.encode(value)87        case .object(let value): try container.encode(value)88        }89    }9091    public subscript(key: String) -> JSONValue? {92        if case .object(let object) = self { object[key] } else { nil }93    }9495    public var stringValue: String? { if case .string(let value) = self { value } else { nil } }96    public var arrayValue: [JSONValue]? { if case .array(let value) = self { value } else { nil } }97    public var boolValue: Bool? { if case .bool(let value) = self { value } else { nil } }98    public var intValue: Int? { if case .int(let value) = self { value } else { nil } }99}100101/// What a command produced: text for people and a value for `--json`. A command may succeed with a102/// non-zero exit code (for example `verify` finding a missing file).103public struct CommandOutput: Sendable {104    public var text: String105    public var json: JSONValue106    public var exitCode: ExitCode107108    public init(text: String, json: JSONValue, exitCode: ExitCode = .success) {109        self.text = text; self.json = json; self.exitCode = exitCode110    }111}112
Files main
Menu

Theme