gitbay/MRs/MRDetailViewModel.swift
220 lines · 8439 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 /// The repository's labels, for chip colours. Read on first use from
88 /// the Labels section, not in `load()`: colours are secondary, and the
89 /// detail screen's tests count `load()`'s four reads.
90 private(set) var colors = LabelColors()
91 private var labelsLoaded = false
92
93 func loadLabels() async {
94 guard !labelsLoaded else { return }
95 labelsLoaded = true
96 colors = LabelColors(
97 (try? await client.readList(["label", "list", repoPath], of: IssueLabel.self)) ?? [])
98 }
99
100 /// A label that does not exist yet is created on the repository.
101 func addLabel(_ label: String) async {
102 await perform(["mr", "label"] + ref + ["--add", label])
103 }
104
105 func removeLabel(_ label: String) async {
106 await perform(["mr", "label"] + ref + ["--remove", label])
107 }
108
109 func comment(_ text: String, format: String? = nil) async {
110 // Long text travels in stdin, but the server only reads it when
111 // argv says so: --file - is required, not implied.
112 var argv = ["mr", "comment"] + ref + ["--file", "-"]
113 if let format { argv.append(contentsOf: ["--format", format]) }
114 await perform(argv, stdin: text)
115 }
116
117 func merge(strategy: String? = nil) async {
118 var argv = ["mr", "merge"] + ref
119 if let strategy { argv.append(contentsOf: ["--strategy", strategy]) }
120 await perform(argv)
121 }
122
123 /// `--by` records which merge request replaces this one; the server
124 /// refuses a closed, merged or self reference.
125 func close(inFavourOf successor: Int64? = nil) async {
126 var argv = ["mr", "close"] + ref
127 if let successor { argv.append(contentsOf: ["--by", String(successor)]) }
128 await perform(argv)
129 }
130
131 /// The repository's other open merge requests, for the close-in-
132 /// favour picker. Fetched on demand and cached like `loadBranches()`;
133 /// this merge request is dropped since it cannot supersede itself.
134 private(set) var openMergeRequests: [MergeRequest]?
135 private(set) var openMergeRequestsError: String?
136
137 func loadOpenMergeRequests() async {
138 guard openMergeRequests == nil else { return }
139 openMergeRequestsError = nil
140 do {
141 let rows = try await client.readList(
142 ["mr", "list", repoPath, "--state", "open"], of: MergeRequest.self)
143 openMergeRequests = rows.filter { $0.number != number }
144 } catch let error as GitbayError {
145 openMergeRequestsError = error.userFacingMessage
146 } catch {
147 openMergeRequestsError = GitbayError.transport(error).userFacingMessage
148 }
149 }
150
151 func setResolved(_ thread: ReviewThread, _ resolved: Bool) async {
152 await perform(["mr", resolved ? "resolve" : "unresolve"] + ref + [String(thread.id)])
153 }
154
155 func reply(to thread: ReviewThread, _ text: String) async {
156 await perform(
157 ["mr", "diff-comment"] + ref + ["--reply", String(thread.id), "--file", "-"],
158 stdin: text
159 )
160 }
161
162 func setDraft(_ draft: Bool) async {
163 await perform(["mr", draft ? "draft" : "ready"] + ref)
164 }
165
166 func retarget(to branch: String) async {
167 await perform(["mr", "retarget"] + ref + [branch])
168 }
169
170 func requestReview(from user: String) async {
171 await perform(["mr", "review", "request"] + ref + ["--add", user])
172 }
173
174 func removeReviewRequest(_ user: String) async {
175 await perform(["mr", "review", "request"] + ref + ["--remove", user])
176 }
177
178 /// Branches for the retarget picker, fetched on demand from `repo refs`.
179 /// `nil` means "not yet loaded" so the picker can tell that apart from
180 /// a repository that genuinely has no other branches; a failed fetch
181 /// leaves `branches` nil and sets `branchesError` instead of silently
182 /// showing an empty list.
183 private(set) var branches: [String]?
184 private(set) var branchesError: String?
185
186 /// Cached for the life of this view model, same as `loadMilestones()`:
187 /// branches can go stale after a push, but re-opening the retarget
188 /// picker should not re-fetch every time. A pull-to-refresh of the
189 /// whole screen doesn't clear this cache either — retarget is a
190 /// secondary action, not the primary content `load()` refreshes.
191 func loadBranches() async {
192 guard branches == nil else { return }
193 branchesError = nil
194 do {
195 let refs = try await client.read(["repo", "refs", repoPath], as: RepoRefs.self)
196 branches = refs.branches.map(\.name)
197 } catch let error as GitbayError {
198 branchesError = error.userFacingMessage
199 } catch {
200 branchesError = GitbayError.transport(error).userFacingMessage
201 }
202 }
203
204 private func perform(_ argv: [String], stdin: String? = nil) async {
205 working = true
206 actionError = nil
207 defer { working = false }
208 do {
209 try await client.run(argv, stdin: stdin)
210 await load()
211 } catch let error as GitbayError {
212 // A refusal explains the rule (approvals missing, threads
213 // unresolved, checks red). Surface it verbatim; never route
214 // around it.
215 actionError = error.userFacingMessage
216 } catch {
217 actionError = GitbayError.transport(error).userFacingMessage
218 }
219 }
220}