Sources/OrgPrograms/GitAutoCommit.swift

29b770d6b2f9edcc6607ab4a46db6c659dd12c1d
orgstar/Sources/OrgPrograms/GitAutoCommit.swift

220 lines · 11659 bytes

  1#if os(macOS)
  2import Foundation
  3import Observation
  4
  5/// Whether orgstar commits in each sidebar folder that is a git repository, by root path, in the
  6/// user defaults under `gitAutoCommit`. Off for a folder that isn't listed.
  7@MainActor
  8@Observable
  9public final class GitFolderSettings {
 10    public enum Mode: String, CaseIterable, Sendable {
 11        case off
 12        /// Commit the files orgstar wrote.
 13        case commit
 14        /// Pull with `--ff-only`, commit, then push.
 15        case sync
 16    }
 17
 18    public static let shared = GitFolderSettings()
 19    static let key = "gitAutoCommit"
 20    @ObservationIgnored private let defaults: UserDefaults
 21    public private(set) var modes: [String: Mode]
 22
 23    public init(defaults: UserDefaults = .standard) {
 24        self.defaults = defaults
 25        let saved = defaults.dictionary(forKey: Self.key) as? [String: String] ?? [:]
 26        modes = saved.compactMapValues(Mode.init(rawValue:)).filter { $0.value != .off }
 27    }
 28
 29    public func mode(for root: String) -> Mode { modes[root] ?? .off }
 30
 31    public func set(_ mode: Mode, for root: String) {
 32        modes[root] = mode == .off ? nil : mode
 33        defaults.set(modes.mapValues(\.rawValue), forKey: Self.key)
 34    }
 35}
 36
 37/// Commits the files orgstar writes in folders where `GitFolderSettings` turns it on: a minute
 38/// after the last write in the folder, and on quit. Only those files are committed, so other
 39/// work in progress in the repository stays as it is. With pulling on, it pulls with
 40/// `--ff-only` first and pushes after a commit, and only when the pull succeeded.
 41@MainActor
 42public final class GitAutoCommit {
 43    public static let shared = GitAutoCommit()
 44
 45    public let settings: GitFolderSettings
 46    /// How long after the last write in a folder its files are committed.
 47    public var delay: Duration = .seconds(60)
 48    /// The sidebar's folders.
 49    public var roots: () -> [String] = { [] }
 50    /// Shows a message in the echo area.
 51    public var report: (String) -> Void = { _ in }
 52    /// The git to run; looked up once.
 53    public lazy var git: Git? = Git.find()
 54
 55    /// Files written since their folder's last commit, by root.
 56    private var pending: [String: Set<String>] = [:]
 57    private var timers: [String: Task<Void, Never>] = [:]
 58    private var running: [String: Task<Void, Never>] = [:]
 59
 60    public init(settings: GitFolderSettings = .shared) {
 61        self.settings = settings
 62    }
 63
 64    /// Whether files are waiting to be committed.
 65    public var hasPending: Bool { pending.values.contains { !$0.isEmpty } }
 66
 67    /// The root of the sidebar folder holding `path`, the innermost when folders nest; compared
 68    /// as written and with symbolic links resolved (`/tmp` and `/private/tmp`).
 69    func root(containing path: String) -> String? {
 70        func resolved(_ path: String) -> String { URL(fileURLWithPath: path).resolvingSymlinksInPath().path }
 71        func inside(_ path: String, _ root: String) -> Bool { path.hasPrefix(root.hasSuffix("/") ? root : root + "/") }
 72        let real = resolved(path)
 73        return roots().filter { inside(path, $0) || inside(real, resolved($0)) }.max { $0.count < $1.count }
 74    }
 75
 76    /// Notes that orgstar wrote `path`; its folder commits after `delay` with no further writes.
 77    public func fileWritten(_ path: String) {
 78        guard let root = root(containing: path), settings.mode(for: root) != .off else { return }
 79        pending[root, default: []].insert(path)
 80        timers[root]?.cancel()
 81        timers[root] = Task { [weak self, delay] in
 82            try? await Task.sleep(for: delay)
 83            guard !Task.isCancelled, let self else { return }
 84            self.timers[root] = nil
 85            await self.commit(root)
 86        }
 87    }
 88
 89    /// Commits every folder's waiting files now, as on quit.
 90    public func flush(networkTimeout: Duration = .seconds(15)) async {
 91        for timer in timers.values { timer.cancel() }
 92        timers = [:]
 93        for root in pending.keys.sorted() { await commit(root, networkTimeout: networkTimeout) }
 94        for task in running.values { await task.value }
 95    }
 96
 97    /// Commits `root`'s waiting files, after a commit already running there.
 98    func commit(_ root: String, networkTimeout: Duration = .seconds(60)) async {
 99        while let task = running[root] { await task.value }
100        guard let files = pending.removeValue(forKey: root), !files.isEmpty else { return }
101        let mode = settings.mode(for: root)
102        guard mode != .off else { return }
103        guard let git else { return report(String(localized: "Can't commit automatically: git isn't installed.", table: "DeveloperID")) }
104        let task = Task { [weak self] in
105            let outcome = await Self.run(files: files.sorted(), pullAndPush: mode == .sync, git: git, networkTimeout: networkTimeout)
106            guard let self else { return }
107            for path in outcome.retry { self.pending[root, default: []].insert(path) }
108            for message in outcome.messages { self.report(message) }
109            self.running[root] = nil
110        }
111        running[root] = task
112        await task.value
113    }
114
115    public struct Outcome: Sendable, Equatable {
116        /// Paths committed, relative to their work tree.
117        public var committed: [String] = []
118        public var pushed = false
119        /// What to show, one message per repository.
120        public var messages: [String] = []
121        /// Files to try again with the next commit.
122        public var retry: [String] = []
123    }
124
125    /// Pulls (with `pullAndPush`), commits the changes to `files` and nothing else, then pushes
126    /// (with `pullAndPush`, after a pull that succeeded and a commit), in each repository the
127    /// files are in. Leaves a repository alone while git is in the middle of an operation there.
128    public nonisolated static func run(
129        files: [String], pullAndPush: Bool, git: Git, localTimeout: Duration = .seconds(30), networkTimeout: Duration = .seconds(60)
130    ) async -> Outcome {
131        var outcome = Outcome()
132        var repositories: [(top: URL, gitDir: URL, files: [String])] = []
133        for file in files {
134            guard let repository = await git.repository(containing: URL(fileURLWithPath: file).deletingLastPathComponent()) else { continue }
135            if let index = repositories.firstIndex(where: { $0.top == repository.top }) {
136                repositories[index].files.append(file)
137            } else {
138                repositories.append((repository.top, repository.gitDir, [file]))
139            }
140        }
141        for repository in repositories {
142            let name = repository.top.lastPathComponent
143            if let operation = Git.operationInProgress(repository.gitDir) {
144                outcome.retry += repository.files
145                outcome.messages.append(operation == "index.lock"
146                    ? String(localized: "Didn't commit in \(name): another git command is running there. orgstar tries again after the next save.", table: "DeveloperID")
147                    : String(localized: "Didn't commit in \(name): a git \(operation) is in progress. Finish or abort it; orgstar commits after the next save.", table: "DeveloperID"))
148                continue
149            }
150            var problems: [String] = []
151            var pulled = true
152            if pullAndPush {
153                do {
154                    let pull = try await git.run(["pull", "--no-rebase", "--ff-only"], in: repository.top, timeout: networkTimeout)
155                    if !pull.succeeded {
156                        pulled = false
157                        problems.append(describe(pull, verb: String(localized: "Couldn't pull in \(name)", table: "DeveloperID"))
158                            + " " + String(localized: "Nothing was merged; pull and resolve it in a terminal. Not pushed.", table: "DeveloperID"))
159                    }
160                } catch {
161                    pulled = false
162                    problems.append(String(localized: "Couldn't pull in \(name): \(String(describing: error)). Not pushed.", table: "DeveloperID"))
163                }
164            }
165            var committed: [String] = []
166            do {
167                let paths = repository.files.compactMap { Git.relativePath(URL(fileURLWithPath: $0), in: repository.top) }
168                let status = try await git.run(["status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames", "--"] + paths, in: repository.top, timeout: localTimeout)
169                guard status.succeeded else { throw Git.Failure(description: status.problem) }
170                // `XY path` entries; porcelain paths are relative to the work tree.
171                let changed = status.stdout.split(separator: "\0").filter { $0.count > 3 }.map { String($0.dropFirst(3)) }
172                if !changed.isEmpty {
173                    let add = try await git.run(["add", "--"] + changed, in: repository.top, timeout: localTimeout)
174                    guard add.succeeded else { throw Git.Failure(description: add.problem) }
175                    let commit = try await git.run(["commit", "--only", "-m", message(changed), "--"] + changed, in: repository.top, timeout: localTimeout)
176                    guard commit.succeeded else { throw Git.Failure(description: commit.problem) }
177                    committed = changed
178                }
179            } catch {
180                outcome.retry += repository.files
181                problems.append(String(localized: "Couldn't commit in \(name): \(String(describing: error))", table: "DeveloperID"))
182            }
183            var pushed = false
184            if pullAndPush, pulled, !committed.isEmpty {
185                do {
186                    let push = try await git.run(["push"], in: repository.top, timeout: networkTimeout)
187                    if push.succeeded { pushed = true } else { problems.append(describe(push, verb: String(localized: "Couldn't push \(name)", table: "DeveloperID"))) }
188                } catch {
189                    problems.append(String(localized: "Couldn't push \(name): \(String(describing: error))", table: "DeveloperID"))
190                }
191            }
192            outcome.committed += committed
193            outcome.pushed = outcome.pushed || pushed
194            let names = committed.map { ($0 as NSString).lastPathComponent }.joined(separator: ", ")
195            var parts: [String] = []
196            if !committed.isEmpty {
197                parts.append(pushed
198                    ? String(localized: "Committed and pushed \(names) in \(name).", table: "DeveloperID")
199                    : String(localized: "Committed \(names) in \(name).", table: "DeveloperID"))
200            }
201            parts += problems
202            if !parts.isEmpty { outcome.messages.append(parts.joined(separator: " ")) }
203        }
204        return outcome
205    }
206
207    /// git's complaint after `verb`, saying so when it is about signing in.
208    nonisolated static func describe(_ output: Git.Output, verb: String) -> String {
209        guard Git.isAuthenticationFailure(output.stderr) else { return "\(verb): \(output.problem)." }
210        return String(localized: "\(verb): git couldn't sign in to the remote (\(output.problem)). orgstar can't answer prompts; use an SSH key in the agent or a credential helper.", table: "DeveloperID")
211    }
212
213    /// `Update a.org, b.org`, or `Update N files` with the paths in the body.
214    nonisolated static func message(_ paths: [String]) -> String {
215        let names = paths.map { ($0 as NSString).lastPathComponent }
216        if paths.count <= 3 { return "Update " + names.joined(separator: ", ") }
217        return "Update \(paths.count) files\n\n" + paths.joined(separator: "\n")
218    }
219}
220#endif
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form