forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnvironment.swift
More file actions
120 lines (109 loc) · 4.06 KB
/
Environment.swift
File metadata and controls
120 lines (109 loc) · 4.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import AppKit
import Foundation
import CopilotService
private struct NoAccessToAccessibilityAPIError: Error, LocalizedError {
var errorDescription: String? {
"Permission not granted to use Accessibility API. Please turn in on in Settings.app."
}
}
private struct FailedToFetchFileURLError: Error, LocalizedError {
var errorDescription: String? {
"Failed to fetch editing file url."
}
}
enum Environment {
static var now = { Date() }
static func fetchCurrentProjectRootURL() async throws -> URL? {
let appleScript = """
tell application "Xcode"
return path of document of the first window
end tell
"""
let task = Process()
task.launchPath = "/usr/bin/osascript"
task.arguments = ["-e", appleScript]
let outpipe = Pipe()
task.standardOutput = outpipe
try task.run()
await Task.yield()
task.waitUntilExit()
if let data = try outpipe.fileHandleForReading.readToEnd(),
let path = String(data: data, encoding: .utf8)
{
let trimmedNewLine = path.trimmingCharacters(in: .newlines)
var url = URL(fileURLWithPath: trimmedNewLine)
while !FileManager.default.fileIsDirectory(atPath: url.path) ||
!url.pathExtension.isEmpty
{
url = url.deletingLastPathComponent()
}
return url
}
return nil
}
static func fetchCurrentFileURL() async throws -> URL {
var activeXcodes = [NSRunningApplication]()
var retryCount = 0
// Sometimes runningApplications returns 0 items.
while activeXcodes.isEmpty, retryCount < 5 {
activeXcodes = NSRunningApplication
.runningApplications(withBundleIdentifier: "com.apple.dt.Xcode")
.sorted { lhs, _ in
if lhs.isActive { return true }
return false
}
if retryCount > 0 { try await Task.sleep(nanoseconds: 50_000_000) }
retryCount += 1
}
// fetch file path of the frontmost window of Xcode through Accessability API.
for xcode in activeXcodes {
let application = AXUIElementCreateApplication(xcode.processIdentifier)
do {
let frontmostWindow = try application.copyValue(
key: kAXFocusedWindowAttribute,
ofType: AXUIElement.self
)
var path = try frontmostWindow.copyValue(
key: kAXDocumentAttribute,
ofType: String?.self
)
if path == nil {
if let firstWindow = try application.copyValue(
key: kAXWindowsAttribute,
ofType: [AXUIElement].self
).first {
path = try firstWindow.copyValue(
key: kAXDocumentAttribute,
ofType: String.self
)
}
}
if let path {
return URL(fileURLWithPath: path)
}
} catch {
if let axError = error as? AXError, axError == .apiDisabled {
throw NoAccessToAccessibilityAPIError()
}
}
}
throw FailedToFetchFileURLError()
}
static func createAuthService() -> CopilotAuthServiceType {
return CopilotAuthService()
}
static func createSuggestionService(_ projectRootURL: URL) -> CopilotSuggestionServiceType {
return CopilotSuggestionService(projectRootURL: projectRootURL)
}
}
extension AXError: Error {}
extension AXUIElement {
func copyValue<T>(key: String, ofType _: T.Type = T.self) throws -> T {
var value: AnyObject?
let error = AXUIElementCopyAttributeValue(self, key as CFString, &value)
if error == .success, let value = value as? T {
return value
}
throw error
}
}