Open History to see the last commit
1import Foundation
2
3enum NativeWorkspaceMapper {
4 static func files(
5 _ entries: [ProjectEntry],
6 directory: String?,
7 workspaceRoot: String
8 ) -> [FeatureFileEntry] {
9 let directory = directoryPath(directory, workspaceRoot: workspaceRoot)
10 let prefix = directory.isEmpty ? "" : "\(directory)/"
11 var children: [String: FeatureFileEntry] = [:]
12
13 for entry in entries {
14 let fullPath = directoryPath(entry.path, workspaceRoot: workspaceRoot)
15 guard fullPath.hasPrefix(prefix) else { continue }
16 let remainder = String(fullPath.dropFirst(prefix.count))
17 guard !remainder.isEmpty else { continue }
18
19 let component = remainder.split(separator: "/", maxSplits: 1).first.map(String.init)!
20 let childPath = prefix + component
21 let isNested = remainder.contains("/")
22 let kind: FeatureFileKind = isNested || entry.kind == .directory
23 ? .directory
24 : .file
25 // Older servers ignore directoryPath and return the recursive index.
26 // Infer its immediate folders, but prefer each folder's own metadata.
27 if isNested, children[childPath] != nil {
28 continue
29 }
30 children[childPath] = FeatureFileEntry(
31 path: childPath,
32 name: component,
33 kind: kind,
34 isHidden: component.hasPrefix("."),
35 isIgnored: !isNested && entry.ignored == true
36 )
37 }
38
39 return Array(children.values).featureFiltered(by: "", includesHidden: true)
40 }
41
42 static func language(for path: String) -> String? {
43 switch URL(fileURLWithPath: path).pathExtension.lowercased() {
44 case "swift": "swift"
45 case "ts", "tsx": "typescript"
46 case "js", "jsx", "mjs", "cjs": "javascript"
47 case "json": "json"
48 case "md", "mdx": "markdown"
49 case "css", "scss": "css"
50 case "html", "htm": "html"
51 case "xml", "svg": "xml"
52 case "sh", "zsh", "bash": "shell"
53 case "py": "python"
54 case "rs": "rust"
55 case "go": "go"
56 case "rb": "ruby"
57 case "sql": "sql"
58 case "toml": "toml"
59 case "yml", "yaml": "yaml"
60 default: nil
61 }
62 }
63
64 static func review(_ preview: ReviewDiffPreview) -> FeatureReview {
65 FeatureReview(
66 title: "Working tree",
67 baseReference: preview.sources.compactMap(\.baseRef).first,
68 files: preview.sources.flatMap(parseDiff),
69 isTruncated: preview.sources.contains(where: \.truncated)
70 )
71 }
72
73 static func sourceControl(_ status: VCSStatus) -> FeatureSourceControlStatus {
74 sourceControl(
75 isRepository: status.isRepo,
76 branch: status.refName,
77 files: status.workingTree.files,
78 aheadCount: status.aheadCount,
79 behindCount: status.behindCount,
80 pullRequest: status.pr
81 )
82 }
83
84 static func sourceControl(
85 local: VCSLocalStatus,
86 remote: VCSRemoteStatus?
87 ) -> FeatureSourceControlStatus {
88 sourceControl(
89 isRepository: local.isRepo,
90 branch: local.refName,
91 files: local.workingTree.files,
92 aheadCount: remote?.aheadCount ?? 0,
93 behindCount: remote?.behindCount ?? 0,
94 pullRequest: remote?.pr
95 )
96 }
97
98 private static func sourceControl(
99 isRepository: Bool,
100 branch: String?,
101 files: [VCSWorkingTreeFile],
102 aheadCount: Int,
103 behindCount: Int,
104 pullRequest: VCSChangeRequest?,
105 isRemoteKnown: Bool = true
106 ) -> FeatureSourceControlStatus {
107 FeatureSourceControlStatus(
108 isRepository: isRepository,
109 branch: branch,
110 aheadCount: aheadCount,
111 behindCount: behindCount,
112 isRemoteKnown: isRemoteKnown,
113 files: files.map {
114 FeatureSourceControlFile(
115 path: $0.path,
116 state: .modified,
117 isStaged: false
118 )
119 },
120 pullRequest: pullRequest.map {
121 FeaturePullRequest(
122 number: $0.number,
123 title: $0.title,
124 state: $0.state,
125 url: URL(string: $0.url),
126 updatedAt: $0.updatedAt
127 )
128 }
129 )
130 }
131
132 /// The streamed counterpart, where the remote half arrives separately and
133 /// may still be pending.
134 static func sourceControl(
135 local: VCSLocalStatus,
136 remote: VCSRemoteStatus?,
137 isRemoteKnown: Bool
138 ) -> FeatureSourceControlStatus {
139 sourceControl(
140 isRepository: local.isRepo,
141 branch: local.refName,
142 files: local.workingTree.files,
143 aheadCount: remote?.aheadCount ?? 0,
144 behindCount: remote?.behindCount ?? 0,
145 pullRequest: remote?.pr,
146 isRemoteKnown: isRemoteKnown
147 )
148 }
149
150 static func gitAction(_ action: FeatureSourceControlAction) -> GitStackedAction {
151 switch action {
152 case .commit: .commit
153 case .push: .push
154 case .createPullRequest: .createPullRequest
155 case .commitAndPush: .commitAndPush
156 case .commitPushAndCreatePullRequest: .commitPushAndPullRequest
157 case .pull:
158 // Pull has a dedicated VCS endpoint and never reaches this mapping.
159 .push
160 }
161 }
162
163 static func terminal(_ snapshot: TerminalSessionSnapshot) -> FeatureTerminalSnapshot {
164 FeatureTerminalSnapshot(
165 threadID: snapshot.threadId,
166 terminalID: snapshot.terminalId,
167 state: terminalState(snapshot.status),
168 title: snapshot.label,
169 workingDirectory: snapshot.cwd,
170 buffer: snapshot.history,
171 exitCode: snapshot.exitCode,
172 updatedAt: snapshot.updatedAt
173 )
174 }
175
176 static func terminal(_ summary: TerminalSummary) -> FeatureTerminalSnapshot {
177 FeatureTerminalSnapshot(
178 threadID: summary.threadId,
179 terminalID: summary.terminalId,
180 state: terminalState(summary.status),
181 title: summary.label,
182 workingDirectory: summary.cwd,
183 exitCode: summary.exitCode,
184 hasRunningSubprocess: summary.hasRunningSubprocess,
185 updatedAt: summary.updatedAt
186 )
187 }
188
189 private static func terminalState(_ status: TerminalSessionStatus) -> FeatureTerminalState {
190 switch status {
191 case .starting: .starting
192 case .running: .running
193 case .exited: .exited
194 case .error: .failed
195 }
196 }
197
198 static func directoryPath(_ path: String?, workspaceRoot: String) -> String {
199 let isWindows = workspaceRoot.hasPrefix("\\\\") || workspaceRoot.hasPrefix("//")
200 || workspaceRoot.range(of: #"^[A-Za-z]:[/\\]"#, options: .regularExpression) != nil
201 let path = path ?? ""
202 return (isWindows ? path.replacingOccurrences(of: "\\", with: "/") : path)
203 .split(separator: "/", omittingEmptySubsequences: true)
204 .joined(separator: "/")
205 }
206
207 private static func parseDiff(_ source: ReviewDiffSource) -> [FeatureReviewFile] {
208 let rawLines = source.diff.split(
209 separator: "\n",
210 omittingEmptySubsequences: false
211 ).map(String.init)
212 var files: [FeatureReviewFile] = []
213 var currentPath: String?
214 var previousPath: String?
215 var change = FeatureReviewChangeKind.modified
216 var lines: [FeatureDiffLine] = []
217 var oldLine: Int?
218 var newLine: Int?
219 var additions = 0
220 var deletions = 0
221
222 func finishFile() {
223 guard let currentPath else { return }
224 files.append(
225 FeatureReviewFile(
226 path: currentPath,
227 previousPath: previousPath,
228 change: change,
229 additions: additions,
230 deletions: deletions,
231 lines: annotateChangedSpans(lines),
232 sourceKind: source.kind,
233 sourceBaseReference: source.baseRef,
234 sourceHeadReference: source.headRef
235 )
236 )
237 }
238
239 for (index, line) in rawLines.enumerated() {
240 if line.hasPrefix("diff --git ") {
241 finishFile()
242 let parts = line.split(separator: " ")
243 currentPath = parts.count > 3 ? stripDiffPrefix(String(parts[3])) : source.title
244 previousPath = parts.count > 2 ? stripDiffPrefix(String(parts[2])) : nil
245 change = .modified
246 lines = []
247 oldLine = nil
248 newLine = nil
249 additions = 0
250 deletions = 0
251 continue
252 }
253 if line.hasPrefix("new file mode ") {
254 change = .added
255 continue
256 }
257 if line.hasPrefix("deleted file mode ") {
258 change = .deleted
259 continue
260 }
261 if line.hasPrefix("rename from ") {
262 previousPath = String(line.dropFirst("rename from ".count))
263 change = .renamed
264 continue
265 }
266 if line.hasPrefix("rename to ") {
267 currentPath = String(line.dropFirst("rename to ".count))
268 change = .renamed
269 continue
270 }
271 if line.hasPrefix("Binary files ") || line == "GIT binary patch" {
272 change = .binary
273 continue
274 }
275 if line.hasPrefix("+++ ") {
276 let path = String(line.dropFirst(4))
277 if path != "/dev/null" { currentPath = stripDiffPrefix(path) }
278 continue
279 }
280 if line.hasPrefix("--- ") {
281 let path = String(line.dropFirst(4))
282 if path != "/dev/null" { previousPath = stripDiffPrefix(path) }
283 continue
284 }
285 if line.hasPrefix("@@") {
286 let ranges = line.split(separator: " ")
287 oldLine = ranges.count > 1 ? rangeStart(String(ranges[1])) : nil
288 newLine = ranges.count > 2 ? rangeStart(String(ranges[2])) : nil
289 lines.append(
290 FeatureDiffLine(
291 id: "\(source.id)-\(index)",
292 kind: .hunk,
293 text: line
294 )
295 )
296 continue
297 }
298
299 let kind: FeatureDiffLineKind
300 let rendered: String
301 let renderedOld: Int?
302 let renderedNew: Int?
303 if line.hasPrefix("+") {
304 kind = .addition
305 rendered = String(line.dropFirst())
306 renderedOld = nil
307 renderedNew = newLine
308 newLine = newLine.map { $0 + 1 }
309 additions += 1
310 } else if line.hasPrefix("-") {
311 kind = .deletion
312 rendered = String(line.dropFirst())
313 renderedOld = oldLine
314 renderedNew = nil
315 oldLine = oldLine.map { $0 + 1 }
316 deletions += 1
317 } else if line.hasPrefix(" ") {
318 kind = .context
319 rendered = String(line.dropFirst())
320 renderedOld = oldLine
321 renderedNew = newLine
322 oldLine = oldLine.map { $0 + 1 }
323 newLine = newLine.map { $0 + 1 }
324 } else {
325 continue
326 }
327 lines.append(
328 FeatureDiffLine(
329 id: "\(source.id)-\(index)",
330 kind: kind,
331 oldLine: renderedOld,
332 newLine: renderedNew,
333 text: rendered
334 )
335 )
336 }
337 finishFile()
338
339 if files.isEmpty, !source.diff.isEmpty {
340 return [
341 FeatureReviewFile(
342 path: source.title,
343 change: .modified,
344 additions: additions,
345 deletions: deletions,
346 lines: annotateChangedSpans(lines),
347 sourceKind: source.kind,
348 sourceBaseReference: source.baseRef,
349 sourceHeadReference: source.headRef
350 ),
351 ]
352 }
353 return files
354 }
355
356 /// Git presents replacements as adjacent deletion/addition blocks. Pairing those
357 /// lines here keeps the view dumb and makes word-level highlighting stable on scroll.
358 private static func annotateChangedSpans(
359 _ source: [FeatureDiffLine]
360 ) -> [FeatureDiffLine] {
361 var lines = source
362 var index = 0
363 while index < lines.count {
364 guard lines[index].kind == .deletion || lines[index].kind == .addition else {
365 index += 1
366 continue
367 }
368 let start = index
369 while index < lines.count,
370 lines[index].kind == .deletion || lines[index].kind == .addition {
371 index += 1
372 }
373 let changedIndices = start ..< index
374 let deletions = changedIndices.filter { lines[$0].kind == .deletion }
375 let additions = changedIndices.filter { lines[$0].kind == .addition }
376 for (deletionIndex, additionIndex) in zip(deletions, additions) {
377 let spans = FeatureDiffWordHighlighter.spans(
378 old: lines[deletionIndex].text,
379 new: lines[additionIndex].text
380 )
381 lines[deletionIndex].spans = spans.old
382 lines[additionIndex].spans = spans.new
383 }
384 }
385 return lines
386 }
387
388 private static func stripDiffPrefix(_ path: String) -> String {
389 if path.hasPrefix("a/") || path.hasPrefix("b/") {
390 return String(path.dropFirst(2))
391 }
392 return path
393 }
394
395 private static func rangeStart(_ range: String) -> Int? {
396 Int(
397 range
398 .drop(while: { $0 == "-" || $0 == "+" })
399 .split(separator: ",", maxSplits: 1)
400 .first
401 ?? ""
402 )
403 }
404}
405
406/// Folds `vcs.subscribeStatus` events into successive UI statuses. Modelled on
407/// `applyGitStatusStreamEvent` in packages/shared — a snapshot replaces both
408/// halves, while the last known remote half is carried across same-branch local
409/// updates and discarded when the branch changes. The explicit pending state is
410/// needed because this client presents partial status.
411struct NativeSourceControlStatusAccumulator {
412 private var local: VCSLocalStatus?
413 private var remote: VCSRemoteStatus?
414 /// Tracked separately from `remote` because the remote half can legitimately
415 /// resolve to nil — "known to be absent" is not the same as "still pending".
416 private var isRemoteResolved = false
417 private(set) var isComplete = false
418
419 mutating func consume(_ event: VCSStatusEvent) -> FeatureSourceControlStatus? {
420 switch event {
421 case let .snapshot(nextLocal, nextRemote):
422 local = nextLocal
423 remote = nextRemote
424 isRemoteResolved = nextRemote != nil
425 case let .localUpdated(nextLocal):
426 if let previousLocal = local, previousLocal.refName != nextLocal.refName {
427 remote = nil
428 isRemoteResolved = false
429 }
430 local = nextLocal
431 case let .remoteUpdated(nextRemote):
432 remote = nextRemote
433 isRemoteResolved = true
434 }
435
436 guard let local else { return nil }
437 // A workspace with no repository or no primary remote never receives a
438 // remote half, so nothing is pending in those cases.
439 let isRemoteKnown = isRemoteResolved || !local.isRepo || !local.hasPrimaryRemote
440 isComplete = isRemoteKnown
441 return NativeWorkspaceMapper.sourceControl(
442 local: local,
443 remote: remote,
444 isRemoteKnown: isRemoteKnown
445 )
446 }
447
448 func validateEnd() throws {
449 guard isComplete else {
450 throw RPCError.protocolViolation(
451 "The source-control status stream ended before completion."
452 )
453 }
454 }
455}