Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadPullRequests.swift

213 lines10.2 KB

1import Foundation
2​
3public struct ThreadPullRequestKey: Codable, Hashable, Sendable {
4 public let host: String
5 public let repository: String
6 public let number: Int
7​
8 public init(host: String, repository: String, number: Int) {
9 let host = host.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
10 let repository = repository.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
11 let suffix = ".visualstudio.com"
12 let parts = repository.split(separator: "/")
13 if ["ssh.dev.azure.com", "vs-ssh.visualstudio.com"].contains(host), parts.count == 4, parts[0] == "v3" {
14 self.host = "dev.azure.com"
15 self.repository = "\(parts[1])/\(parts[2])/_git/\(parts[3])"
16 } else if host.hasSuffix(suffix), repository.contains("/_git/") {
17 let organization = String(host.dropLast(suffix.count))
18 self.host = "dev.azure.com"
19 self.repository = "\(organization)/\(repository.hasPrefix("defaultcollection/") ? String(repository.dropFirst("defaultcollection/".count)) : repository)"
20 } else {
21 self.host = host
22 self.repository = repository
23 }
24 self.number = number
25 }
26​
27 public func matchesRepository(_ canonicalKey: String) -> Bool {
28 guard let slash = canonicalKey.firstIndex(of: "/") else { return false }
29 return self == Self(host: String(canonicalKey[..<slash]),
30 repository: String(canonicalKey[canonicalKey.index(after: slash)...]), number: number)
31 }
33​
34public struct ThreadPullRequestSnapshot: Codable, Hashable, Sendable {
35 public let state: PullRequestState
36 public let title: String
37 public let headBranch: String
38 public let baseBranch: String
39 public let isDraft: Bool
40 public let updatedAt: String?
41 public let syncedAt: String
42 public var closedAt: String? = nil
43 public var mergedAt: String? = nil
44 public var author: PullRequestActor? = nil
45 public var additions: Int? = nil
46 public var deletions: Int? = nil
47 public var changedFiles: Int? = nil
48 public var reviewDecision: PullRequestReviewDecision? = nil
49 public var checksState: PullRequestChecksState? = nil
50 public var mergeability: PullRequestMergeability? = nil
52​
53public struct ThreadPullRequestStack: Codable, Hashable, Sendable {
54 public struct Layer: Codable, Hashable, Sendable {
55 public let number: Int
56 public let headBranch: String
57 public let state: PullRequestState
58 }
59 public let kind: String
60 public let id: String
61 public let number: Int
62 public let url: String
63 public let base: String
64 public let layers: [Layer]
66​
67public struct ThreadPullRequestLink: Codable, Hashable, Sendable, Identifiable {
68 public let host: String
69 public let repository: String
70 public let number: Int
71 public let url: String
72 // Keep unknown sources decodable. Only stack-dismissed is hidden.
73 public var source: String
74 public let linkedAt: String
75 public var snapshot: ThreadPullRequestSnapshot?
76 public var stack: ThreadPullRequestStack?
77​
78 public var id: ThreadPullRequestKey {
79 let parsed = URL(string: url)
80 let authority: String
81 if let port = parsed?.port, let hostname = parsed?.host,
82 hostname.caseInsensitiveCompare(host) == .orderedSame {
83 authority = "\(hostname):\(port)"
84 } else { authority = host }
85 return ThreadPullRequestKey(host: authority, repository: repository, number: number)
86 }
87 public var isVisible: Bool { source != "stack-dismissed" }
88 public var isOpen: Bool { snapshot == nil || snapshot?.state == .open }
90​
91/// Shared selection rules for badges, search and the thread's external PR link.
92public enum ThreadPullRequests {
93 public static func authority(of text: String) -> String? {
94 guard let url = URL(string: text), let host = url.host else { return nil }
95 return url.port.map { "\(host):\($0)" } ?? host
96 }
97​
98 public static func parseURL(_ text: String) -> ThreadPullRequestKey? {
99 guard let url = URL(string: text.trimmingCharacters(in: .whitespacesAndNewlines)),
100 ["https", "http"].contains(url.scheme?.lowercased() ?? ""),
101 let host = url.host?.lowercased(), url.user == nil, url.password == nil else { return nil }
102 var routes: [(pattern: String, host: String)] = []
103 if host == "github.com" || host.hasSuffix(".github.com") || host.split(separator: ".").contains("github") {
104 routes.append((#"^/([^/]+/[^/]+)/pull/([0-9]+)(?:/|$)"#, host))
105 }
106 routes.append((#"^/([^/]+(?:/[^/]+)+)/-/merge_requests/([0-9]+)(?:/|$)"#, host))
107 routes.append((#"^/([^/]+(?:/[^/]+)+)/pulls/([0-9]+)(?:/|$)"#, authority(of: url.absoluteString) ?? host))
108 if host == "bitbucket.org" || host.hasSuffix(".bitbucket.org") || host.split(separator: ".").contains("bitbucket") {
109 routes.append((#"^/([^/]+/[^/]+)/pull-requests/([0-9]+)(?:/|$)"#, host))
110 }
111 if host == "dev.azure.com" || host.hasSuffix(".dev.azure.com") || host.hasSuffix(".visualstudio.com") {
112 routes.append((#"^/((?:[^/]+/)*_git/[^/]+)/pullrequest/([0-9]+)(?:/|$)"#, host))
113 }
114 let path = url.path
115 for route in routes {
116 guard let regex = try? NSRegularExpression(pattern: route.pattern),
117 let match = regex.firstMatch(in: path, range: NSRange(path.startIndex..., in: path)),
118 let repositoryRange = Range(match.range(at: 1), in: path),
119 let numberRange = Range(match.range(at: 2), in: path),
120 let number = Int(path[numberRange]), number > 0 else { continue }
121 return ThreadPullRequestKey(host: route.host, repository: String(path[repositoryRange]), number: number)
122 }
123 return nil
124 }
125​
126 public static func mutation(threadID: String, key: ThreadPullRequestKey, url: String,
127 linked: Bool, multiple: Bool, legacyProjectID: String?, legacyRepository: String? = nil,
128 commandID: String = UUID().uuidString) -> JSONValue? {
129 var payload: [String: JSONValue] = ["commandId": .string(commandID), "threadId": .string(threadID)]
130 if multiple {
131 payload["type"] = .string(linked ? "thread.pull-request.link" : "thread.pull-request.unlink")
132 payload["host"] = .string(key.host)
133 payload["repository"] = .string(key.repository)
134 payload["number"] = .number(Double(key.number))
135 if linked {
136 payload["url"] = .string(url)
137 payload["source"] = .string("manual")
138 }
139 } else {
140 guard !linked || legacyProjectID != nil else { return nil }
141 payload["type"] = .string("thread.meta.update")
142 payload["linkedPullRequest"] = linked ? .object([
143 "projectId": .string(legacyProjectID ?? ""), "repository": .string(legacyRepository ?? key.repository),
144 "number": .number(Double(key.number)), "url": .string(url),
145 ]) : .null
146 }
147 return .object(payload)
148 }
149​
150 public static func visible(_ links: [ThreadPullRequestLink]) -> [ThreadPullRequestLink] {
151 links.filter(\.isVisible)
152 }
153​
154 public static func chains(_ links: [ThreadPullRequestLink]) -> [[ThreadPullRequestLink]] {
155 let links = visible(links)
156 var placed: Set<ThreadPullRequestKey> = []
157 var result: [[ThreadPullRequestLink]] = []
158 for link in links where link.stack != nil && !placed.contains(link.id) {
159 guard let stack = link.stack else { continue }
160 let members = links.filter {
161 $0.id.host == link.id.host && $0.id.repository == link.id.repository && $0.stack?.id == stack.id
162 }
163 let ordered = members.sorted { left, right in
164 (stack.layers.firstIndex { $0.number == left.number } ?? 0)
165 < (stack.layers.firstIndex { $0.number == right.number } ?? 0)
166 }
167 placed.formUnion(ordered.map(\.id))
168 result.append(ordered)
169 }
170 let remaining = links.filter { !placed.contains($0.id) }
171 func parent(of link: ThreadPullRequestLink) -> ThreadPullRequestLink? {
172 guard let base = link.snapshot?.baseBranch else { return nil }
173 let matches = remaining.filter {
174 $0.id.host == link.id.host && $0.id.repository == link.id.repository
175 && $0.snapshot?.headBranch == base
176 }
177 return matches.count == 1 && matches[0].id != link.id ? matches[0] : nil
178 }
179 let parents = Set(remaining.compactMap { parent(of: $0)?.id })
180 for top in remaining where !parents.contains(top.id) {
181 var chain: [ThreadPullRequestLink] = []
182 var cursor: ThreadPullRequestLink? = top
183 while let link = cursor, placed.insert(link.id).inserted {
184 chain.insert(link, at: 0)
185 cursor = parent(of: link)
186 }
187 if !chain.isEmpty { result.append(chain) }
188 }
189 for link in remaining where !placed.contains(link.id) { result.append([link]) }
190 return result
191 }
192​
193 public static func current(_ links: [ThreadPullRequestLink]) -> ThreadPullRequestLink? {
194 let visible = visible(links)
195 let open = visible.filter(\.isOpen)
196 if open.count == 1 { return open.first }
197 let chains = chains(visible)
198 if !open.isEmpty {
199 return chains.map { $0.reversed().filter(\.isOpen) }.filter { !$0.isEmpty }
200 .sorted { ($0.map(\.linkedAt).max() ?? "") > ($1.map(\.linkedAt).max() ?? "") }
201 .first?.first
202 }
203 if chains.count == 1 { return chains.first?.last }
204 return visible.max { ($0.snapshot?.updatedAt ?? $0.linkedAt) < ($1.snapshot?.updatedAt ?? $1.linkedAt) }
205 }
206​
207 public static func searchTerms(_ links: [ThreadPullRequestLink]?, legacy: ThreadLinkedPullRequest?) -> [String] {
208 if let links, !links.isEmpty {
209 return visible(links).flatMap { ["#\($0.number)", "\($0.repository)#\($0.number)", $0.url, $0.snapshot?.title ?? ""] }
210 }
211 return legacy.map { ["#\($0.number)", "\($0.repository)#\($0.number)", $0.url] } ?? []
212 }