SPB Git

Repository Public MIT

FileTransaction.swift 8.8 KB 192 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/GlassCLICore/FileTransaction.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/// One change to a file of the project.45public struct FileChange: Equatable, Sendable {46    public enum Action: String, Codable, Sendable { case write, delete }47    public let path: String48    public let action: Action49    public let data: Data?5051    public static func write(_ path: String, _ data: Data) -> FileChange { FileChange(path: path, action: .write, data: data) }52    public static func delete(_ path: String) -> FileChange { FileChange(path: path, action: .delete, data: nil) }53}5455/// Applies a set of file changes so that either all of them are kept or none.56///57/// New content is first written to a staging directory inside the project (same volume, so the final step58/// is a rename). Every original that is replaced or deleted is moved into the staging directory first, and59/// each step is recorded in a journal before it happens. If a step fails, if the task is cancelled, or if60/// the process dies, the journal is replayed backwards: new files are removed and originals put back.61public struct FileTransaction: Sendable {62    public static let stagingDirectoryName = ".spglass-staging"6364    public let project: Project65    /// Test hook: throws after this many changes have been applied.66    public var failAfterChanges: Int?67    /// Test hook: stops after this many changes without rolling back, as a killed process would.68    public var abandonAfterChanges: Int?6970    public init(project: Project) {71        self.project = project72    }7374    struct Journal: Codable {75        struct Entry: Codable {76            var path: String77            var action: FileChange.Action78            /// Staging-relative path of the saved original, when there was one.79            var backup: String?80        }81        var entries: [Entry] = []82    }8384    struct Abandoned: Error {}8586    private var stagingRoot: URL { project.root.appendingPathComponent(Self.stagingDirectoryName) }8788    public func apply(_ changes: [FileChange]) async throws {89        guard !changes.isEmpty else { return }90        try RegistryPath.validateSet(changes.map(\.path))91        let fileManager = FileManager.default92        let staging = stagingRoot.appendingPathComponent(UUID().uuidString)93        let journalURL = staging.appendingPathComponent("journal.json")94        var journal = Journal()9596        do {97            try fileManager.createDirectory(at: staging.appendingPathComponent("new"), withIntermediateDirectories: true)98            try fileManager.createDirectory(at: staging.appendingPathComponent("backup"), withIntermediateDirectories: true)99            // Stage every new file before touching the project.100            for (index, change) in changes.enumerated() where change.action == .write {101                try (change.data ?? Data()).write(to: staging.appendingPathComponent("new/\(index)"))102            }103            for (index, change) in changes.enumerated() {104                try Task.checkCancellation()105                if let limit = failAfterChanges, index >= limit {106                    throw CLIError(code: "injected_failure", message: "Injected failure after \(limit) changes.")107                }108                if let limit = abandonAfterChanges, index >= limit { throw Abandoned() }109110                let destination = try project.url(for: change.path)111                let exists = fileManager.fileExists(atPath: destination.path)112                let entry = Journal.Entry(path: change.path, action: change.action, backup: exists ? "backup/\(index)" : nil)113                journal.entries.append(entry)114                try JSONEncoder().encode(journal).write(to: journalURL, options: .atomic)115116                if exists {117                    try fileManager.moveItem(at: destination, to: staging.appendingPathComponent("backup/\(index)"))118                }119                if change.action == .write {120                    try fileManager.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)121                    try fileManager.moveItem(at: staging.appendingPathComponent("new/\(index)"), to: destination)122                }123            }124        } catch is Abandoned {125            return126        } catch {127            Self.rollBack(staging: staging, project: project)128            throw error129        }130        try? fileManager.removeItem(at: staging)131        Self.removeIfEmpty(stagingRoot)132        for change in changes where change.action == .delete {133            removeEmptyParents(of: change.path)134        }135    }136137    /// Rolls back transactions left behind by an interrupted run. Returns the number recovered.138    @discardableResult139    public static func recover(project: Project) -> Int {140        let root = project.root.appendingPathComponent(stagingDirectoryName)141        guard let leftovers = try? FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil) else { return 0 }142        var count = 0143        for staging in leftovers {144            rollBack(staging: staging, project: project)145            count += 1146        }147        removeIfEmpty(root)148        return count149    }150151    static func rollBack(staging: URL, project: Project) {152        let fileManager = FileManager.default153        if let data = try? Data(contentsOf: staging.appendingPathComponent("journal.json")),154           let journal = try? JSONDecoder().decode(Journal.self, from: data) {155            for entry in journal.entries.reversed() {156                guard let destination = try? project.url(for: entry.path) else { continue }157                if let backup = entry.backup {158                    let saved = staging.appendingPathComponent(backup)159                    // The original was moved away only if its backup exists; otherwise it is still in place.160                    if fileManager.fileExists(atPath: saved.path) {161                        try? fileManager.removeItem(at: destination)162                        try? fileManager.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)163                        try? fileManager.moveItem(at: saved, to: destination)164                    }165                } else if entry.action == .write {166                    // There was no original: anything at the destination was written by this transaction.167                    try? fileManager.removeItem(at: destination)168                }169            }170        }171        try? fileManager.removeItem(at: staging)172        removeIfEmpty(project.root.appendingPathComponent(stagingDirectoryName))173    }174175    private static func removeIfEmpty(_ directory: URL) {176        if let contents = try? FileManager.default.contentsOfDirectory(atPath: directory.path), contents.isEmpty {177            try? FileManager.default.removeItem(at: directory)178        }179    }180181    /// Removes directories emptied by a deletion, stopping at the project root.182    private func removeEmptyParents(of path: String) {183        var components = path.split(separator: "/").dropLast()184        while !components.isEmpty {185            let directory = project.root.appendingPathComponent(components.joined(separator: "/"))186            guard let contents = try? FileManager.default.contentsOfDirectory(atPath: directory.path), contents.isEmpty else { return }187            try? FileManager.default.removeItem(at: directory)188            components = components.dropLast()189        }190    }191}192
Files main
Menu

Theme