|
| 1 | +// SPDX-License-Identifier: AGPL-3.0-or-later |
| 2 | +import Foundation |
| 3 | +import Combine |
| 4 | + |
| 5 | +@MainActor |
| 6 | +final class ProtectedBranchCommitController: ObservableObject { |
| 7 | + struct Warning: Identifiable { |
| 8 | + let id = UUID() |
| 9 | + let branch: String |
| 10 | + let remoteBranch: String |
| 11 | + let status: BranchProtectionService.Status |
| 12 | + } |
| 13 | + |
| 14 | + enum Decision { |
| 15 | + case cancel |
| 16 | + case commitAnyway |
| 17 | + case newBranch(String) |
| 18 | + } |
| 19 | + |
| 20 | + @Published var warning: Warning? |
| 21 | + private var continuation: CheckedContinuation<Decision, Never>? |
| 22 | + private var isChecking = false |
| 23 | + |
| 24 | + func authorize( |
| 25 | + repositoryURL: URL, |
| 26 | + settings: RepoSettings, |
| 27 | + credentials: GitProviderCredentialResolver, |
| 28 | + syncState: SyncState, |
| 29 | + undoManager: GitUndoManager? |
| 30 | + ) async -> Bool { |
| 31 | + guard !isChecking else { return false } |
| 32 | + isChecking = true |
| 33 | + defer { isChecking = false } |
| 34 | + guard !settings.skipProtectedBranchCommitWarnings else { return true } |
| 35 | + let git = GitStatusService.shared |
| 36 | + guard let branch = await git.currentBranch(in: repositoryURL), !branch.isEmpty else { return true } |
| 37 | + let oldHead = await git.tipHash(for: "HEAD", in: repositoryURL) |
| 38 | + let remotes = await git.remotes(in: repositoryURL) |
| 39 | + guard !remotes.isEmpty else { return true } |
| 40 | + let upstream = await git.upstreamBranch(for: branch, in: repositoryURL) |
| 41 | + let target = Self.target(branch: branch, upstream: upstream, remotes: remotes, preferredRemote: settings.defaultRemoteName) |
| 42 | + guard let target else { return true } |
| 43 | + let remoteURL = await git.remoteURL(remote: target.remote, in: repositoryURL) |
| 44 | + guard let identity = credentials.remoteIdentity(for: remoteURL) else { return true } |
| 45 | + // API credentials also apply to SSH remotes; never send SSH keys to a provider API. |
| 46 | + let matching = credentials.accounts.filter { |
| 47 | + $0.provider == identity.provider && $0.hostURL.host()?.lowercased() == identity.hostURL.host()?.lowercased() |
| 48 | + && ($0.transportProtocol == .https || !$0.scopes.isEmpty) |
| 49 | + } |
| 50 | + let preferenceKey = GitProviderAccountPreferenceKey.make(for: identity) |
| 51 | + let preferredID = credentials.preferredAccountIDsByRemoteIdentity[preferenceKey] |
| 52 | + let account = matching.first { $0.id == preferredID } ?? (matching.count == 1 ? matching.first : nil) |
| 53 | + let token = account.flatMap { try? credentials.tokenVault.readToken(for: $0) } |
| 54 | + let status = await BranchProtectionService().status(branch: target.branch, identity: identity, token: token) |
| 55 | + guard await git.currentBranch(in: repositoryURL) == branch, |
| 56 | + await git.tipHash(for: "HEAD", in: repositoryURL) == oldHead else { |
| 57 | + syncState.showInfo("The current branch changed. Review your changes and commit again.") |
| 58 | + return false |
| 59 | + } |
| 60 | + guard status == .protected || status == .unavailable else { return true } |
| 61 | + let decision = await withCheckedContinuation { continuation in |
| 62 | + self.continuation = continuation |
| 63 | + warning = Warning(branch: branch, remoteBranch: "\(target.remote)/\(target.branch)", status: status) |
| 64 | + } |
| 65 | + guard case .cancel = decision else { |
| 66 | + guard await git.currentBranch(in: repositoryURL) == branch, |
| 67 | + await git.tipHash(for: "HEAD", in: repositoryURL) == oldHead else { |
| 68 | + syncState.showInfo("The current branch changed. Review your changes and commit again.") |
| 69 | + return false |
| 70 | + } |
| 71 | + if case .newBranch(let name) = decision { |
| 72 | + guard await git.isValidBranchName(name, in: repositoryURL) else { |
| 73 | + syncState.showError("Enter a valid new branch name and try committing again.") |
| 74 | + return false |
| 75 | + } |
| 76 | + do { |
| 77 | + _ = try await git.createBranch(name: name, checkout: true, commit: nil, in: repositoryURL) |
| 78 | + if let oldHead { |
| 79 | + undoManager?.register(GitUndoEntry( |
| 80 | + repositoryURL: repositoryURL, |
| 81 | + label: "Create branch \(name)", |
| 82 | + undoOperation: .deleteLocalBranch(name: name, force: true, expectedTip: oldHead), |
| 83 | + redoOperation: .createLocalBranch(name: name, startPoint: oldHead, checkout: true) |
| 84 | + )) |
| 85 | + } |
| 86 | + await syncState.refresh(repositoryURL: repositoryURL) |
| 87 | + NotificationCenter.default.post(name: .repositoryDidChange, object: nil, userInfo: ["repositoryURL": repositoryURL]) |
| 88 | + } catch { |
| 89 | + syncState.showError(error.localizedDescription) |
| 90 | + return false |
| 91 | + } |
| 92 | + } |
| 93 | + return true |
| 94 | + } |
| 95 | + return false |
| 96 | + } |
| 97 | + |
| 98 | + func finish(_ decision: Decision) { |
| 99 | + let pending = continuation |
| 100 | + continuation = nil |
| 101 | + warning = nil |
| 102 | + pending?.resume(returning: decision) |
| 103 | + } |
| 104 | + |
| 105 | + static func target(branch: String, upstream: String?, remotes: [String], preferredRemote: String?) -> (remote: String, branch: String)? { |
| 106 | + if let upstream, let remote = remotes.sorted(by: { $0.count > $1.count }).first(where: { upstream.hasPrefix($0 + "/") }) { |
| 107 | + return (remote, String(upstream.dropFirst(remote.count + 1))) |
| 108 | + } |
| 109 | + let remote = preferredRemote.flatMap { remotes.contains($0) ? $0 : nil } |
| 110 | + ?? (remotes.contains("origin") ? "origin" : remotes.first) |
| 111 | + return remote.map { ($0, branch) } |
| 112 | + } |
| 113 | +} |
0 commit comments