gitbay/MRs/MRDetailViewModel.swift

v1.2.0
gitbay-ios/gitbay/MRs/MRDetailViewModel.swift history · blame · raw

198 lines · 7607 bytes

  1import Foundation
  2import Observation
  3
  4/// One merge request: `mr show`, the parsed diff, the review threads, and
  5/// every write the review cycle needs. Writes reload — the server's state
  6/// is the state.
  7@Observable
  8@MainActor
  9final class MRDetailViewModel {
 10
 11    private(set) var state: LoadState<MRDetail> = .loading
 12    private(set) var diff: UnifiedDiff?
 13    private(set) var threads: [ReviewThread] = []
 14    private(set) var revisions: [MRRevision] = []
 15    /// A write failed; the server's sentence, shown until the next action.
 16    private(set) var actionError: String?
 17    private(set) var working = false
 18
 19    private let client: GitbayClient
 20    let repoPath: String
 21    let number: Int64
 22
 23    init(client: GitbayClient, repoPath: String, number: Int64) {
 24        self.client = client
 25        self.repoPath = repoPath
 26        self.number = number
 27    }
 28
 29    private var ref: [String] { [repoPath, String(number)] }
 30
 31    func load() async {
 32        do {
 33            let detail = try await client.read(["mr", "show"] + ref, as: MRDetail.self)
 34            state = .loaded(detail)
 35        } catch {
 36            state = .from(error)
 37            return
 38        }
 39        // The diff and threads are secondary: their failure leaves the
 40        // header usable rather than sinking the screen.
 41        async let diffText = try? client.readText(["mr", "diff"] + ref)
 42        async let threadList = try? client.readList(["mr", "threads"] + ref, of: ReviewThread.self)
 43        async let revisionList = try? client.readList(["mr", "revisions"] + ref, of: MRRevision.self)
 44        diff = (await diffText).map(UnifiedDiff.parse)
 45        threads = await threadList ?? []
 46        revisions = await revisionList ?? []
 47    }
 48
 49    var unresolvedCount: Int {
 50        threads.count { !$0.isResolved }
 51    }
 52
 53    // MARK: - Writes
 54
 55    enum Verdict: String, Sendable {
 56        case approve = "--approve"
 57        case requestChanges = "--request-changes"
 58    }
 59
 60    func review(_ verdict: Verdict) async {
 61        await perform(["mr", "review"] + ref + [verdict.rawValue])
 62    }
 63
 64    /// Both fields are always sent; an empty body clears it. `format` is
 65    /// appended only when given; omitting it lets the server default.
 66    func edit(title: String, body: String, format: String? = nil) async {
 67        var argv = ["mr", "edit"] + ref + ["--title", title, "--file", "-"]
 68        if let format { argv.append(contentsOf: ["--format", format]) }
 69        await perform(argv, stdin: body)
 70    }
 71
 72    /// Open milestones for the picker; fetched on first use.
 73    private(set) var availableMilestones: [Milestone]?
 74
 75    func loadMilestones() async {
 76        guard availableMilestones == nil else { return }
 77        availableMilestones = (try? await client.readList(
 78            ["milestone", "list", repoPath, "--state", "open"], of: Milestone.self
 79        )) ?? []
 80    }
 81
 82    /// nil clears it; the command spells that "none".
 83    func setMilestone(_ title: String?) async {
 84        await perform(["mr", "milestone"] + ref + [title ?? "none"])
 85    }
 86
 87    func comment(_ text: String, format: String? = nil) async {
 88        // Long text travels in stdin, but the server only reads it when
 89        // argv says so: --file - is required, not implied.
 90        var argv = ["mr", "comment"] + ref + ["--file", "-"]
 91        if let format { argv.append(contentsOf: ["--format", format]) }
 92        await perform(argv, stdin: text)
 93    }
 94
 95    func merge(strategy: String? = nil) async {
 96        var argv = ["mr", "merge"] + ref
 97        if let strategy { argv.append(contentsOf: ["--strategy", strategy]) }
 98        await perform(argv)
 99    }
100
101    /// `--by` records which merge request replaces this one; the server
102    /// refuses a closed, merged or self reference.
103    func close(inFavourOf successor: Int64? = nil) async {
104        var argv = ["mr", "close"] + ref
105        if let successor { argv.append(contentsOf: ["--by", String(successor)]) }
106        await perform(argv)
107    }
108
109    /// The repository's other open merge requests, for the close-in-
110    /// favour picker. Fetched on demand and cached like `loadBranches()`;
111    /// this merge request is dropped since it cannot supersede itself.
112    private(set) var openMergeRequests: [MergeRequest]?
113    private(set) var openMergeRequestsError: String?
114
115    func loadOpenMergeRequests() async {
116        guard openMergeRequests == nil else { return }
117        openMergeRequestsError = nil
118        do {
119            let rows = try await client.readList(
120                ["mr", "list", repoPath, "--state", "open"], of: MergeRequest.self)
121            openMergeRequests = rows.filter { $0.number != number }
122        } catch let error as GitbayError {
123            openMergeRequestsError = error.userFacingMessage
124        } catch {
125            openMergeRequestsError = GitbayError.transport(error).userFacingMessage
126        }
127    }
128
129    func setResolved(_ thread: ReviewThread, _ resolved: Bool) async {
130        await perform(["mr", resolved ? "resolve" : "unresolve"] + ref + [String(thread.id)])
131    }
132
133    func reply(to thread: ReviewThread, _ text: String) async {
134        await perform(
135            ["mr", "diff-comment"] + ref + ["--reply", String(thread.id), "--file", "-"],
136            stdin: text
137        )
138    }
139
140    func setDraft(_ draft: Bool) async {
141        await perform(["mr", draft ? "draft" : "ready"] + ref)
142    }
143
144    func retarget(to branch: String) async {
145        await perform(["mr", "retarget"] + ref + [branch])
146    }
147
148    func requestReview(from user: String) async {
149        await perform(["mr", "review", "request"] + ref + ["--add", user])
150    }
151
152    func removeReviewRequest(_ user: String) async {
153        await perform(["mr", "review", "request"] + ref + ["--remove", user])
154    }
155
156    /// Branches for the retarget picker, fetched on demand from `repo refs`.
157    /// `nil` means "not yet loaded" so the picker can tell that apart from
158    /// a repository that genuinely has no other branches; a failed fetch
159    /// leaves `branches` nil and sets `branchesError` instead of silently
160    /// showing an empty list.
161    private(set) var branches: [String]?
162    private(set) var branchesError: String?
163
164    /// Cached for the life of this view model, same as `loadMilestones()`:
165    /// branches can go stale after a push, but re-opening the retarget
166    /// picker should not re-fetch every time. A pull-to-refresh of the
167    /// whole screen doesn't clear this cache either — retarget is a
168    /// secondary action, not the primary content `load()` refreshes.
169    func loadBranches() async {
170        guard branches == nil else { return }
171        branchesError = nil
172        do {
173            let refs = try await client.read(["repo", "refs", repoPath], as: RepoRefs.self)
174            branches = refs.branches.map(\.name)
175        } catch let error as GitbayError {
176            branchesError = error.userFacingMessage
177        } catch {
178            branchesError = GitbayError.transport(error).userFacingMessage
179        }
180    }
181
182    private func perform(_ argv: [String], stdin: String? = nil) async {
183        working = true
184        actionError = nil
185        defer { working = false }
186        do {
187            try await client.run(argv, stdin: stdin)
188            await load()
189        } catch let error as GitbayError {
190            // A refusal explains the rule (approvals missing, threads
191            // unresolved, checks red). Surface it verbatim; never route
192            // around it.
193            actionError = error.userFacingMessage
194        } catch {
195            actionError = GitbayError.transport(error).userFacingMessage
196        }
197    }
198}