SPB Git

Repository Public MIT

InstallPlanner.swift 12.0 KB 253 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/GlassCLICore/InstallPlanner.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 SPGlassRegistry4344public struct FilePlan: Equatable, Sendable, Encodable {45    public enum Action: String, Sendable, Encodable {46        /// The file does not exist locally and will be written.47        case create48        /// The local file is the unmodified previous version and will be replaced.49        case replace50        /// The local file already has the wanted content.51        case unchanged52        /// The local file was modified, or is not tracked; nothing is written without consent.53        case conflict54        /// The modified local file is replaced with consent; its content is saved next to it as `.orig`.55        case overwrite56        /// The modified local file is kept; the registry version is written next to it as `.incoming`.57        case incoming58        /// The file left the item and its local copy is unmodified: it is deleted.59        case delete60        /// The file left the item but was modified locally: it is kept and no longer tracked.61        case keepModified = "keep-modified"62    }63    public let path: String64    public let action: Action65}6667public struct ItemPlan: Equatable, Sendable, Encodable {68    public enum Action: String, Sendable, Encodable { case install, update, repair, unchanged }69    public let id: String70    public let name: String71    public let fromVersion: String?72    public let toVersion: String73    public let action: Action74    public let requested: Bool75    public let files: [FilePlan]76}7778public struct InstallPlan: Sendable {79    public var items: [ItemPlan] = []80    var changes: [FileChange] = []81    var lock: ProjectLock82    var conflicts: [(path: String, diff: String)] = []8384    public var hasConflicts: Bool { !conflicts.isEmpty }85    public var isNoOp: Bool { items.allSatisfy { $0.action == .unchanged } }86}8788public struct InstallOptions: Sendable {89    public var overwrite = false90    public var writeIncoming = false91    /// `add` keeps the installed version of an item unless a version is given; `update` moves to the latest.92    public var preferInstalledVersion = true93    public init(overwrite: Bool = false, writeIncoming: Bool = false, preferInstalledVersion: Bool = true) {94        self.overwrite = overwrite; self.writeIncoming = writeIncoming; self.preferInstalledVersion = preferInstalledVersion95    }96}9798/// Decides what installing or updating a set of items would do, without changing anything.99public struct InstallPlanner: Sendable {100    public let project: Project101    public let config: ProjectConfig102    public let client: RegistryClient103104    public init(project: Project, config: ProjectConfig, client: RegistryClient) {105        self.project = project; self.config = config; self.client = client106    }107108    public func plan(roots: [String], version: String?, lock: ProjectLock, options: InstallOptions) async throws -> InstallPlan {109        for root in roots { try RegistryPath.validateIdentifier(root) }110        if let version { _ = try SemanticVersion(version) }111        let index = try await client.index()112113        // Fetch the manifests of the roots and of everything they depend on.114        var manifests: [String: ComponentManifest] = [:]115        var queue = roots116        while let id = queue.popLast() {117            if manifests[id] != nil { continue }118            let wanted: String?119            if roots.contains(id) {120                wanted = version ?? (options.preferInstalledVersion ? lock.item(id)?.version : nil)121            } else {122                wanted = nil123            }124            var manifest = try await client.manifest(id: id, version: wanted, index: index)125            if !roots.contains(id) {126                // A dependency is installed at the version its dependants pin, never below the installed one.127                let pinned = manifests.values.flatMap(\.dependencies).filter { $0.id == id }.compactMap { try? SemanticVersion($0.version) }.max()128                let installed = lock.item(id).flatMap { try? SemanticVersion($0.version) }129                if let target = [pinned, installed].compactMap({ $0 }).max(), target.description != manifest.version {130                    manifest = try await client.manifest(id: id, version: target.description, index: index)131                }132            }133            manifests[id] = manifest134            queue.append(contentsOf: manifest.dependencies.map(\.id))135        }136        let order = try DependencyGraph.installationOrder(roots: roots) { id throws(RegistryError) -> [String] in137            guard let manifest = manifests[id] else { throw .unknownItem(id) }138            return manifest.dependencies.map(\.id)139        }140141        var plan = InstallPlan(lock: lock)142        plan.lock.registry = client.identity143        var claimed: [String: String] = [:]144        for id in order {145            guard let manifest = manifests[id] else { continue }146            let locked = lock.item(id)147            var files: [FilePlan] = []148            var lockedFiles: [ManifestFile] = []149150            for file in manifest.files {151                let destination = config.sourcesPath + "/" + file.path152                try RegistryPath.validate(destination)153                let key = RegistryPath.collisionKey(destination)154                if let other = claimed[key] ?? lock.owner(of: destination).map(\.id), other != id {155                    throw CLIError(RegistryError.pathCollision("\(other): \(destination)", "\(id): \(destination)"))156                }157                claimed[key] = id158                lockedFiles.append(ManifestFile(path: destination, sha256: file.sha256, bytes: file.bytes))159160                let local = try project.read(destination)161                let previous = locked?.files.first { $0.path == destination }162                let action: FilePlan.Action163                if let local {164                    let localHash = RegistryHash.sha256(local)165                    if localHash == file.sha256 {166                        action = .unchanged167                    } else if let previous, previous.sha256 == localHash {168                        action = .replace169                    } else if options.overwrite {170                        action = .overwrite171                    } else if options.writeIncoming {172                        action = .incoming173                    } else {174                        action = .conflict175                    }176                } else {177                    action = .create178                }179                files.append(FilePlan(path: destination, action: action))180181                switch action {182                case .create, .replace:183                    plan.changes.append(.write(destination, try await client.file(file, of: manifest)))184                case .overwrite:185                    plan.changes.append(.write(destination + ".orig", local ?? Data()))186                    plan.changes.append(.write(destination, try await client.file(file, of: manifest)))187                case .incoming:188                    plan.changes.append(.write(destination + ".incoming", try await client.file(file, of: manifest)))189                case .conflict:190                    let incoming = try await client.file(file, of: manifest)191                    plan.conflicts.append((destination, LineDiff.unified(192                        old: String(decoding: local ?? Data(), as: UTF8.self), new: String(decoding: incoming, as: UTF8.self),193                        oldLabel: "local/\(destination)", newLabel: "registry/\(destination) (\(manifest.version))"194                    )))195                case .unchanged, .delete, .keepModified:196                    break197                }198            }199200            // Files of the installed version that the new version no longer ships.201            for old in locked?.files ?? [] where !lockedFiles.contains(where: { $0.path == old.path }) {202                guard let local = try project.read(old.path) else { continue }203                if RegistryHash.sha256(local) == old.sha256 {204                    files.append(FilePlan(path: old.path, action: .delete))205                    plan.changes.append(.delete(old.path))206                } else {207                    files.append(FilePlan(path: old.path, action: .keepModified))208                }209            }210211            let action: ItemPlan.Action212            if locked == nil {213                action = .install214            } else if locked?.version != manifest.version {215                action = .update216            } else {217                action = files.allSatisfy { $0.action == .unchanged } ? .unchanged : .repair218            }219            let requested = roots.contains(id) || (locked?.requested ?? false)220            plan.items.append(ItemPlan(id: id, name: manifest.name, fromVersion: locked?.version, toVersion: manifest.version, action: action, requested: requested, files: files.sorted { $0.path < $1.path }))221            plan.lock.set(LockedItem(id: id, version: manifest.version, kind: manifest.kind, requested: requested, dependencies: manifest.dependencies.map(\.id).sorted(), digest: manifest.sha256, files: lockedFiles.sorted { $0.path < $1.path }))222        }223        return plan224    }225226    /// Applies a plan: all file changes and the lock file in one transaction.227    public func apply(_ plan: InstallPlan, transaction: FileTransaction? = nil) async throws {228        if plan.hasConflicts {229            throw Self.conflictError(plan.conflicts)230        }231        var changes = plan.changes232        changes.append(.write(ProjectLock.fileName, try RegistryJSON.encode(plan.lock)))233        try await (transaction ?? FileTransaction(project: project)).apply(changes)234    }235236    static func conflictError(_ conflicts: [(path: String, diff: String)]) -> CLIError {237        var details = ""238        for conflict in conflicts {239            let lines = conflict.diff.split(separator: "\n", omittingEmptySubsequences: false)240            details += lines.prefix(80).joined(separator: "\n")241            if lines.count > 80 { details += "\n… (\(lines.count - 80) more lines; run `spglass diff` for the whole file)" }242            details += "\n"243        }244        return CLIError(245            code: "local_modifications",246            message: "\(conflicts.count) file\(conflicts.count == 1 ? " has" : "s have") local changes or would be overwritten: " + conflicts.map(\.path).joined(separator: ", ") + ". Nothing was changed.",247            hint: "Merge by hand: re-run with --write-incoming to get the registry version next to each file as <file>.incoming. Or re-run with --overwrite to replace them (the current content is saved as <file>.orig).",248            details: details,249            exitCode: .conflict250        )251    }252}253
Files main
Menu

Theme