gitbay/Repos/FileViewModel.swift
37 lines · 1012 bytes
1import Foundation
2import Observation
3
4/// One file via `repo cat`: text renders (highlighted when the language is
5/// known), binary says so, truncated says so — never a guess.
6@Observable
7@MainActor
8final class FileViewModel {
9
10 private(set) var state: LoadState<FileContent> = .loading
11
12 private let client: GitbayClient
13 let repoPath: String
14 let filePath: String
15 let ref: String?
16
17 init(client: GitbayClient, repoPath: String, filePath: String, ref: String? = nil) {
18 self.client = client
19 self.repoPath = repoPath
20 self.filePath = filePath
21 self.ref = ref
22 }
23
24 var fileName: String {
25 String(filePath.split(separator: "/").last ?? "")
26 }
27
28 func load() async {
29 var argv = ["repo", "cat", repoPath, filePath]
30 if let ref { argv.append(contentsOf: ["--ref", ref]) }
31 do {
32 state = .loaded(try await client.read(argv, as: FileContent.self))
33 } catch {
34 state = .from(error)
35 }
36 }
37}