native macOS codings agent orchestrator
1import Foundation
2
3enum GitWorktreeHeadResolver {
4 static func headURL(for worktreeURL: URL, fileManager: FileManager) -> URL? {
5 let gitURL = worktreeURL.appending(path: ".git")
6 var isDirectory = ObjCBool(false)
7 guard
8 fileManager.fileExists(
9 atPath: gitURL.path(percentEncoded: false),
10 isDirectory: &isDirectory
11 )
12 else {
13 return nil
14 }
15 if isDirectory.boolValue {
16 return gitURL.appending(path: "HEAD")
17 }
18 guard let contents = try? String(contentsOf: gitURL, encoding: .utf8) else {
19 return nil
20 }
21 guard let line = contents.split(whereSeparator: \.isNewline).first else {
22 return nil
23 }
24 let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
25 let prefix = "gitdir:"
26 guard trimmed.hasPrefix(prefix) else {
27 return nil
28 }
29 let pathPart = trimmed.dropFirst(prefix.count).trimmingCharacters(in: .whitespacesAndNewlines)
30 guard !pathPart.isEmpty else {
31 return nil
32 }
33 let gitdirURL = URL(fileURLWithPath: String(pathPart), relativeTo: worktreeURL)
34 .standardizedFileURL
35 return gitdirURL.appending(path: "HEAD")
36 }
37}