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

NativeWorkspaceMapper.swift

377 lines13.0 KB

1import Foundation
2​
3enum NativeWorkspaceMapper {
4 static func files(
5 _ entries: [ProjectEntry],
6 directory: String?
7 ) -> [FeatureFileEntry] {
8 let directory = normalize(directory ?? "")
9 let prefix = directory.isEmpty ? "" : "\(directory)/"
10 var children: [String: FeatureFileEntry] = [:]
11​
12 for entry in entries {
13 let fullPath = normalize(entry.path)
14 guard fullPath.hasPrefix(prefix) else { continue }
15 let remainder = String(fullPath.dropFirst(prefix.count))
16 guard !remainder.isEmpty else { continue }
17​
18 let component = remainder.split(separator: "/", maxSplits: 1).first.map(String.init)!
19 let childPath = prefix + component
20 let isNested = remainder.contains("/")
21 let kind: FeatureFileKind = isNested || entry.kind == .directory
22 ? .directory
23 : .file
24 if children[childPath]?.kind == .directory {
25 continue
26 }
27 children[childPath] = FeatureFileEntry(
28 path: childPath,
29 name: component,
30 kind: kind,
31 isHidden: component.hasPrefix(".")
32 )
33 }
34​
35 return Array(children.values).featureFiltered(by: "", includesHidden: true)
36 }
37​
38 static func language(for path: String) -> String? {
39 switch URL(fileURLWithPath: path).pathExtension.lowercased() {
40 case "swift": "swift"
41 case "ts", "tsx": "typescript"
42 case "js", "jsx", "mjs", "cjs": "javascript"
43 case "json": "json"
44 case "md", "mdx": "markdown"
45 case "css", "scss": "css"
46 case "html", "htm": "html"
47 case "xml", "svg": "xml"
48 case "sh", "zsh", "bash": "shell"
49 case "py": "python"
50 case "rs": "rust"
51 case "go": "go"
52 case "rb": "ruby"
53 case "sql": "sql"
54 case "toml": "toml"
55 case "yml", "yaml": "yaml"
56 default: nil
57 }
58 }
59​
60 static func review(_ preview: ReviewDiffPreview) -> FeatureReview {
61 FeatureReview(
62 title: "Working tree",
63 baseReference: preview.sources.compactMap(\.baseRef).first,
64 files: preview.sources.flatMap(parseDiff),
65 isTruncated: preview.sources.contains(where: \.truncated)
66 )
67 }
68​
69 static func sourceControl(_ status: VCSStatus) -> FeatureSourceControlStatus {
70 sourceControl(
71 isRepository: status.isRepo,
72 branch: status.refName,
73 files: status.workingTree.files,
74 aheadCount: status.aheadCount,
75 behindCount: status.behindCount,
76 pullRequest: status.pr
77 )
78 }
79​
80 static func sourceControl(
81 local: VCSLocalStatus,
82 remote: VCSRemoteStatus?
83 ) -> FeatureSourceControlStatus {
84 sourceControl(
85 isRepository: local.isRepo,
86 branch: local.refName,
87 files: local.workingTree.files,
88 aheadCount: remote?.aheadCount ?? 0,
89 behindCount: remote?.behindCount ?? 0,
90 pullRequest: remote?.pr
91 )
92 }
93​
94 private static func sourceControl(
95 isRepository: Bool,
96 branch: String?,
97 files: [VCSWorkingTreeFile],
98 aheadCount: Int,
99 behindCount: Int,
100 pullRequest: VCSChangeRequest?
101 ) -> FeatureSourceControlStatus {
102 FeatureSourceControlStatus(
103 isRepository: isRepository,
104 branch: branch,
105 aheadCount: aheadCount,
106 behindCount: behindCount,
107 files: files.map {
108 FeatureSourceControlFile(
109 path: $0.path,
110 state: .modified,
111 isStaged: false
112 )
113 },
114 pullRequest: pullRequest.map {
115 FeaturePullRequest(
116 number: $0.number,
117 title: $0.title,
118 state: $0.state,
119 url: URL(string: $0.url),
120 updatedAt: $0.updatedAt
121 )
122 }
123 )
124 }
125​
126 static func gitAction(_ action: FeatureSourceControlAction) -> GitStackedAction {
127 switch action {
128 case .commit: .commit
129 case .push: .push
130 case .createPullRequest: .createPullRequest
131 case .commitAndPush: .commitAndPush
132 case .commitPushAndCreatePullRequest: .commitPushAndPullRequest
133 case .pull:
134 // Pull has a dedicated VCS endpoint and never reaches this mapping.
135 .push
136 }
137 }
138​
139 static func terminal(_ snapshot: TerminalSessionSnapshot) -> FeatureTerminalSnapshot {
140 FeatureTerminalSnapshot(
141 threadID: snapshot.threadId,
142 terminalID: snapshot.terminalId,
143 state: terminalState(snapshot.status),
144 title: snapshot.label,
145 workingDirectory: snapshot.cwd,
146 buffer: snapshot.history,
147 exitCode: snapshot.exitCode,
148 updatedAt: snapshot.updatedAt
149 )
150 }
151​
152 static func terminal(_ summary: TerminalSummary) -> FeatureTerminalSnapshot {
153 FeatureTerminalSnapshot(
154 threadID: summary.threadId,
155 terminalID: summary.terminalId,
156 state: terminalState(summary.status),
157 title: summary.label,
158 workingDirectory: summary.cwd,
159 exitCode: summary.exitCode,
160 hasRunningSubprocess: summary.hasRunningSubprocess,
161 updatedAt: summary.updatedAt
162 )
163 }
164​
165 private static func terminalState(_ status: TerminalSessionStatus) -> FeatureTerminalState {
166 switch status {
167 case .starting: .starting
168 case .running: .running
169 case .exited: .exited
170 case .error: .failed
171 }
172 }
173​
174 private static func normalize(_ path: String) -> String {
175 path.replacingOccurrences(of: "\\", with: "/")
176 .split(separator: "/", omittingEmptySubsequences: true)
177 .joined(separator: "/")
178 }
179​
180 private static func parseDiff(_ source: ReviewDiffSource) -> [FeatureReviewFile] {
181 let rawLines = source.diff.split(
182 separator: "\n",
183 omittingEmptySubsequences: false
184 ).map(String.init)
185 var files: [FeatureReviewFile] = []
186 var currentPath: String?
187 var previousPath: String?
188 var change = FeatureReviewChangeKind.modified
189 var lines: [FeatureDiffLine] = []
190 var oldLine: Int?
191 var newLine: Int?
192 var additions = 0
193 var deletions = 0
194​
195 func finishFile() {
196 guard let currentPath else { return }
197 files.append(
198 FeatureReviewFile(
199 path: currentPath,
200 previousPath: previousPath,
201 change: change,
202 additions: additions,
203 deletions: deletions,
204 lines: annotateChangedSpans(lines),
205 sourceKind: source.kind,
206 sourceBaseReference: source.baseRef,
207 sourceHeadReference: source.headRef
208 )
209 )
210 }
211​
212 for (index, line) in rawLines.enumerated() {
213 if line.hasPrefix("diff --git ") {
214 finishFile()
215 let parts = line.split(separator: " ")
216 currentPath = parts.count > 3 ? stripDiffPrefix(String(parts[3])) : source.title
217 previousPath = parts.count > 2 ? stripDiffPrefix(String(parts[2])) : nil
218 change = .modified
219 lines = []
220 oldLine = nil
221 newLine = nil
222 additions = 0
223 deletions = 0
224 continue
225 }
226 if line.hasPrefix("new file mode ") {
227 change = .added
228 continue
229 }
230 if line.hasPrefix("deleted file mode ") {
231 change = .deleted
232 continue
233 }
234 if line.hasPrefix("rename from ") {
235 previousPath = String(line.dropFirst("rename from ".count))
236 change = .renamed
237 continue
238 }
239 if line.hasPrefix("rename to ") {
240 currentPath = String(line.dropFirst("rename to ".count))
241 change = .renamed
242 continue
243 }
244 if line.hasPrefix("Binary files ") || line == "GIT binary patch" {
245 change = .binary
246 continue
247 }
248 if line.hasPrefix("+++ ") {
249 let path = String(line.dropFirst(4))
250 if path != "/dev/null" { currentPath = stripDiffPrefix(path) }
251 continue
252 }
253 if line.hasPrefix("--- ") {
254 let path = String(line.dropFirst(4))
255 if path != "/dev/null" { previousPath = stripDiffPrefix(path) }
256 continue
257 }
258 if line.hasPrefix("@@") {
259 let ranges = line.split(separator: " ")
260 oldLine = ranges.count > 1 ? rangeStart(String(ranges[1])) : nil
261 newLine = ranges.count > 2 ? rangeStart(String(ranges[2])) : nil
262 lines.append(
263 FeatureDiffLine(
264 id: "\(source.id)-\(index)",
265 kind: .hunk,
266 text: line
267 )
268 )
269 continue
270 }
271​
272 let kind: FeatureDiffLineKind
273 let rendered: String
274 let renderedOld: Int?
275 let renderedNew: Int?
276 if line.hasPrefix("+") {
277 kind = .addition
278 rendered = String(line.dropFirst())
279 renderedOld = nil
280 renderedNew = newLine
281 newLine = newLine.map { $0 + 1 }
282 additions += 1
283 } else if line.hasPrefix("-") {
284 kind = .deletion
285 rendered = String(line.dropFirst())
286 renderedOld = oldLine
287 renderedNew = nil
288 oldLine = oldLine.map { $0 + 1 }
289 deletions += 1
290 } else if line.hasPrefix(" ") {
291 kind = .context
292 rendered = String(line.dropFirst())
293 renderedOld = oldLine
294 renderedNew = newLine
295 oldLine = oldLine.map { $0 + 1 }
296 newLine = newLine.map { $0 + 1 }
297 } else {
298 continue
299 }
300 lines.append(
301 FeatureDiffLine(
302 id: "\(source.id)-\(index)",
303 kind: kind,
304 oldLine: renderedOld,
305 newLine: renderedNew,
306 text: rendered
307 )
308 )
309 }
310 finishFile()
311​
312 if files.isEmpty, !source.diff.isEmpty {
313 return [
314 FeatureReviewFile(
315 path: source.title,
316 change: .modified,
317 additions: additions,
318 deletions: deletions,
319 lines: annotateChangedSpans(lines),
320 sourceKind: source.kind,
321 sourceBaseReference: source.baseRef,
322 sourceHeadReference: source.headRef
323 ),
324 ]
325 }
326 return files
327 }
328​
329 /// Git presents replacements as adjacent deletion/addition blocks. Pairing those
330 /// lines here keeps the view dumb and makes word-level highlighting stable on scroll.
331 private static func annotateChangedSpans(
332 _ source: [FeatureDiffLine]
333 ) -> [FeatureDiffLine] {
334 var lines = source
335 var index = 0
336 while index < lines.count {
337 guard lines[index].kind == .deletion || lines[index].kind == .addition else {
338 index += 1
339 continue
340 }
341 let start = index
342 while index < lines.count,
343 lines[index].kind == .deletion || lines[index].kind == .addition {
344 index += 1
345 }
346 let changedIndices = start ..< index
347 let deletions = changedIndices.filter { lines[$0].kind == .deletion }
348 let additions = changedIndices.filter { lines[$0].kind == .addition }
349 for (deletionIndex, additionIndex) in zip(deletions, additions) {
350 let spans = FeatureDiffWordHighlighter.spans(
351 old: lines[deletionIndex].text,
352 new: lines[additionIndex].text
353 )
354 lines[deletionIndex].spans = spans.old
355 lines[additionIndex].spans = spans.new
356 }
357 }
358 return lines
359 }
360​
361 private static func stripDiffPrefix(_ path: String) -> String {
362 if path.hasPrefix("a/") || path.hasPrefix("b/") {
363 return String(path.dropFirst(2))
364 }
365 return path
366 }
367​
368 private static func rangeStart(_ range: String) -> Int? {
369 Int(
370 range
371 .drop(while: { $0 == "-" || $0 == "+" })
372 .split(separator: ",", maxSplits: 1)
373 .first
374 ?? ""
375 )
376 }