gitbay/Repos/RepoSettingsViewModel.swift
242 lines · 8988 bytes
1import Foundation
2import Observation
3
4/// The repo settings screen: `repo settings show` for the admin knobs,
5/// `repo show` for description/topics/visibility, and one write command
6/// per control. Non-admins get the server's refusal verbatim.
7@Observable
8@MainActor
9final class RepoSettingsViewModel {
10
11 nonisolated struct Loaded: Sendable, Hashable {
12 let settings: RepoSettings
13 let detail: RepoDetail
14 }
15
16 private(set) var state: LoadState<Loaded> = .loading
17 private(set) var actionError: String?
18 private(set) var working = false
19
20 /// `repo deps status`, exposed as an optional plus a separate error
21 /// string rather than folded into one state: `nil` with no error means
22 /// "not loaded yet", `nil` with an error means "the read failed". The
23 /// settings screen must never render "checks are off" when it means
24 /// "we could not ask".
25 private(set) var deps: DepsStatus?
26 private(set) var depsError: String?
27
28 /// `repo access list`, with the same nil-plus-error shape as `deps`:
29 /// "not loaded" and "could not ask" must not read as "nobody granted".
30 private(set) var grants: [AccessGrant]?
31 private(set) var grantsError: String?
32
33 /// Branch names from `repo refs`, for the default-branch picker.
34 private(set) var branches: [String] = []
35
36 private let client: GitbayClient
37 let repoPath: String
38
39 init(client: GitbayClient, repoPath: String) {
40 self.client = client
41 self.repoPath = repoPath
42 }
43
44 func load() async {
45 do {
46 async let settings = client.read(
47 ["repo", "settings", "show", repoPath], as: RepoSettings.self)
48 async let detail = client.read(["repo", "show", repoPath], as: RepoDetail.self)
49 state = .loaded(Loaded(settings: try await settings, detail: try await detail))
50 } catch {
51 state = .from(error)
52 }
53 }
54
55 /// `repo deps status` — three words, unlike every other `repo` command
56 /// in this file, which is exactly why it's easy to get wrong.
57 func loadDeps() async {
58 depsError = nil
59 deps = nil
60 do {
61 deps = try await client.read(["repo", "deps", "status", repoPath], as: DepsStatus.self)
62 } catch let error as GitbayError {
63 depsError = error.userFacingMessage
64 } catch {
65 depsError = GitbayError.transport(error).userFacingMessage
66 }
67 }
68
69 /// `enable`/`disable` are two distinct commands, not one command with a
70 /// flag. Reloads the status afterward so the report reflects the
71 /// change; a refused write leaves `deps` untouched.
72 func setDepsEnabled(_ on: Bool) async {
73 await perform(["repo", "deps", on ? "enable" : "disable", repoPath], reload: loadDeps)
74 }
75
76 // MARK: - Writes, one command per knob
77
78 func setDescription(_ text: String) async {
79 await perform(["repo", "settings", "description", repoPath, text])
80 }
81
82 func setWebsite(_ url: String) async {
83 await perform(["repo", "settings", "website", repoPath, url])
84 }
85
86 func setVisibility(_ visibility: String) async {
87 await perform(["repo", "settings", "visibility", repoPath, visibility])
88 }
89
90 func setGitDaemon(_ on: Bool) async {
91 await perform(["repo", "settings", "git-daemon", repoPath, on ? "on" : "off"])
92 }
93
94 func protectBranch(_ branch: String) async {
95 await perform(["repo", "settings", "protect", repoPath, branch])
96 }
97
98 func unprotectBranch(_ branch: String) async {
99 await perform(["repo", "settings", "unprotect", repoPath, branch])
100 }
101
102 func setRequireApprovals(_ count: Int) async {
103 await perform(["repo", "settings", "require-approvals", repoPath, String(count)])
104 }
105
106 func setRequireResolved(_ on: Bool) async {
107 await perform(["repo", "settings", "require-resolved", repoPath, on ? "on" : "off"])
108 }
109
110 func setRequireChecks(_ on: Bool) async {
111 await perform(["repo", "settings", "require-checks", repoPath, on ? "on" : "off"])
112 }
113
114 /// `repo settings require-contexts` replaces the list, so the whole
115 /// list goes each time. Naming one turns the checks gate on.
116 /// Returns whether the field can be cleared: the server took it, or
117 /// it was already listed. A refused name stays in the field to fix.
118 @discardableResult
119 func addRequiredContext(_ context: String) async -> Bool {
120 let context = context.trimmingCharacters(in: .whitespaces)
121 let current = state.value?.settings.contexts ?? []
122 guard !context.isEmpty, !working else { return false }
123 guard !current.contains(context) else { return true }
124 await setRequiredContexts(current + [context])
125 return actionError == nil
126 }
127
128 /// Removing the last one leaves the gate as it was, waiting on every check.
129 func removeRequiredContext(_ context: String) async {
130 await setRequiredContexts((state.value?.settings.contexts ?? []).filter { $0 != context })
131 }
132
133 private func setRequiredContexts(_ contexts: [String]) async {
134 await perform(["repo", "settings", "require-contexts", repoPath] + contexts)
135 }
136
137 func setRequireSigned(_ on: Bool) async {
138 await perform(["repo", "settings", "require-signed", repoPath, on ? "on" : "off"])
139 }
140
141 func setRequireCodeowners(_ on: Bool) async {
142 await perform(["repo", "settings", "require-codeowners", repoPath, on ? "on" : "off"])
143 }
144
145 func setRequireMR(_ on: Bool) async {
146 await perform(["repo", "settings", "require-mr", repoPath, on ? "on" : "off"])
147 }
148
149 func protectTag(_ glob: String) async {
150 await perform(["repo", "settings", "protect-tag", repoPath, glob])
151 }
152
153 func unprotectTag(_ glob: String) async {
154 await perform(["repo", "settings", "unprotect-tag", repoPath, glob])
155 }
156
157 /// `repo settings default-branch`: moves HEAD and the record. The
158 /// server refuses a branch that does not exist, so the picker only
159 /// offers what `repo refs` listed.
160 func setDefaultBranch(_ branch: String) async {
161 await perform(["repo", "settings", "default-branch", repoPath, branch])
162 }
163
164 nonisolated private struct Renamed: Decodable, Sendable {
165 let repo: String
166 }
167
168 /// `repo rename <owner/name> <new-name>`: the row and the directory
169 /// move together and clone URLs change. Returns the new path; the
170 /// caller navigates there, since this screen's path is now gone.
171 func rename(to name: String) async -> String? {
172 let name = name.trimmingCharacters(in: .whitespaces)
173 guard !name.isEmpty else { return nil }
174 working = true
175 actionError = nil
176 defer { working = false }
177 do {
178 let renamed = try await client.run(["repo", "rename", repoPath, name], as: Renamed.self)
179 return renamed?.repo
180 } catch let error as GitbayError {
181 actionError = error.userFacingMessage
182 } catch {
183 actionError = GitbayError.transport(error).userFacingMessage
184 }
185 return nil
186 }
187
188 func loadBranches() async {
189 let refs = try? await client.read(["repo", "refs", repoPath], as: RepoRefs.self)
190 branches = refs?.branches.map(\.name) ?? []
191 }
192
193 func loadGrants() async {
194 grantsError = nil
195 grants = nil
196 do {
197 grants = try await client.readList(["repo", "access", "list", repoPath], of: AccessGrant.self)
198 } catch let error as GitbayError {
199 grantsError = error.userFacingMessage
200 } catch {
201 grantsError = GitbayError.transport(error).userFacingMessage
202 }
203 }
204
205 /// `repo access grant <repo> <user> read|write|admin` — granting again
206 /// changes an existing user's role.
207 func grant(user: String, role: String) async {
208 let user = user.trimmingCharacters(in: .whitespaces)
209 guard !user.isEmpty else { return }
210 await perform(["repo", "access", "grant", repoPath, user, role], reload: loadGrants)
211 }
212
213 func revoke(user: String) async {
214 await perform(["repo", "access", "revoke", repoPath, user], reload: loadGrants)
215 }
216
217 func addTopic(_ topic: String) async {
218 await perform(["repo", "topics", "add", repoPath, topic])
219 }
220
221 func removeTopic(_ topic: String) async {
222 await perform(["repo", "topics", "remove", repoPath, topic])
223 }
224
225 private func perform(_ argv: [String]) async {
226 await perform(argv, reload: load)
227 }
228
229 private func perform(_ argv: [String], reload: () async -> Void) async {
230 working = true
231 actionError = nil
232 defer { working = false }
233 do {
234 try await client.run(argv)
235 await reload()
236 } catch let error as GitbayError {
237 actionError = error.userFacingMessage
238 } catch {
239 actionError = GitbayError.transport(error).userFacingMessage
240 }
241 }
242}