gitbay/MRs/MRDetailViewModel.swift

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

174 lines · 6444 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    func close() async {
102        await perform(["mr", "close"] + ref)
103    }
104
105    func setResolved(_ thread: ReviewThread, _ resolved: Bool) async {
106        await perform(["mr", resolved ? "resolve" : "unresolve"] + ref + [String(thread.id)])
107    }
108
109    func reply(to thread: ReviewThread, _ text: String) async {
110        await perform(
111            ["mr", "diff-comment"] + ref + ["--reply", String(thread.id), "--file", "-"],
112            stdin: text
113        )
114    }
115
116    func setDraft(_ draft: Bool) async {
117        await perform(["mr", draft ? "draft" : "ready"] + ref)
118    }
119
120    func retarget(to branch: String) async {
121        await perform(["mr", "retarget"] + ref + [branch])
122    }
123
124    func requestReview(from user: String) async {
125        await perform(["mr", "review", "request"] + ref + ["--add", user])
126    }
127
128    func removeReviewRequest(_ user: String) async {
129        await perform(["mr", "review", "request"] + ref + ["--remove", user])
130    }
131
132    /// Branches for the retarget picker, fetched on demand from `repo refs`.
133    /// `nil` means "not yet loaded" so the picker can tell that apart from
134    /// a repository that genuinely has no other branches; a failed fetch
135    /// leaves `branches` nil and sets `branchesError` instead of silently
136    /// showing an empty list.
137    private(set) var branches: [String]?
138    private(set) var branchesError: String?
139
140    /// Cached for the life of this view model, same as `loadMilestones()`:
141    /// branches can go stale after a push, but re-opening the retarget
142    /// picker should not re-fetch every time. A pull-to-refresh of the
143    /// whole screen doesn't clear this cache either — retarget is a
144    /// secondary action, not the primary content `load()` refreshes.
145    func loadBranches() async {
146        guard branches == nil else { return }
147        branchesError = nil
148        do {
149            let refs = try await client.read(["repo", "refs", repoPath], as: RepoRefs.self)
150            branches = refs.branches.map(\.name)
151        } catch let error as GitbayError {
152            branchesError = error.userFacingMessage
153        } catch {
154            branchesError = GitbayError.transport(error).userFacingMessage
155        }
156    }
157
158    private func perform(_ argv: [String], stdin: String? = nil) async {
159        working = true
160        actionError = nil
161        defer { working = false }
162        do {
163            try await client.run(argv, stdin: stdin)
164            await load()
165        } catch let error as GitbayError {
166            // A refusal explains the rule (approvals missing, threads
167            // unresolved, checks red). Surface it verbatim; never route
168            // around it.
169            actionError = error.userFacingMessage
170        } catch {
171            actionError = GitbayError.transport(error).userFacingMessage
172        }
173    }
174}