forked from swiftwasm/JavaScriptKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTS2Swift.swift
More file actions
169 lines (155 loc) · 5.76 KB
/
Copy pathTS2Swift.swift
File metadata and controls
169 lines (155 loc) · 5.76 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
@preconcurrency import class Foundation.Process
@preconcurrency import class Foundation.Pipe
@preconcurrency import class Foundation.ProcessInfo
@preconcurrency import class Foundation.FileManager
@preconcurrency import struct Foundation.URL
@preconcurrency import struct Foundation.Data
@preconcurrency import struct Foundation.ObjCBool
@preconcurrency import func Foundation.kill
@preconcurrency import var Foundation.SIGINT
@preconcurrency import var Foundation.SIGTERM
import protocol Dispatch.DispatchSourceSignal
import class Dispatch.DispatchSource
import SwiftParser
import SwiftSyntax
#if os(Windows)
import WinSDK
#endif
#if canImport(BridgeJSCore)
import BridgeJSCore
#endif
#if canImport(BridgeJSSkeleton)
import BridgeJSSkeleton
#endif
#if os(Windows)
let PATH_SEPARATOR: Character = ";"
#else
let PATH_SEPARATOR: Character = ":"
#endif
internal func which(
_ executable: String,
environment: [String: String] = ProcessInfo.processInfo.environment
) -> URL? {
func checkCandidate(_ candidate: URL) -> Bool {
var isDirectory: ObjCBool = false
let fileExists = FileManager.default.fileExists(atPath: candidate.path, isDirectory: &isDirectory)
return fileExists && !isDirectory.boolValue && FileManager.default.isExecutableFile(atPath: candidate.path)
}
do {
// Check overriding environment variable
let envVariable = "JAVASCRIPTKIT_" + executable.uppercased().replacingOccurrences(of: "-", with: "_") + "_EXEC"
if let executablePath = environment[envVariable] {
let url = URL(fileURLWithPath: executablePath)
if checkCandidate(url) {
return url
}
}
}
let paths = environment["PATH"]?.split(separator: PATH_SEPARATOR) ?? []
for path in paths {
let url = URL(fileURLWithPath: String(path)).appendingPathComponent(executable)
if checkCandidate(url) {
return url
}
}
return nil
}
extension BridgeJSConfig {
/// Find a tool from the system PATH, using environment variable override, or bridge-js.config.json
public func findTool(_ name: String, targetDirectory: URL) throws -> URL {
if let tool = tools?[name] {
return URL(fileURLWithPath: tool)
}
if let url = which(name) {
return url
}
// Emit a helpful error message with a suggestion to create a local config override.
throw BridgeJSCoreError(
"""
Executable "\(name)" not found in PATH. \
Hint: Try setting the JAVASCRIPTKIT_\(name.uppercased().replacingOccurrences(of: "-", with: "_"))_EXEC environment variable, \
or create a local config override with:
echo '{ "tools": { "\(name)": "'$(which \(name))'" } }' > \(targetDirectory.appendingPathComponent("bridge-js.config.local.json").path)
"""
)
}
}
/// Invokes ts2swift to convert TypeScript definitions to macro-annotated Swift
/// - Parameters:
/// - dtsFile: Path to the TypeScript definition file
/// - tsconfigPath: Path to the TypeScript project configuration file
/// - nodePath: Path to the node executable
/// - progress: Progress reporting instance
/// - outputPath: Optional path to write the output file. If nil, output is collected from stdout (for testing)
/// - Returns: The generated Swift source code (always collected from stdout for return value)
public func invokeTS2Swift(
dtsFile: String,
globalDtsFiles: [String] = [],
tsconfigPath: String,
nodePath: URL,
progress: ProgressReporting,
outputPath: String? = nil
) throws -> String {
let ts2swiftPath = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent()
.appendingPathComponent("JavaScript")
.appendingPathComponent("bin")
.appendingPathComponent("ts2swift.js")
var arguments = [ts2swiftPath.path, dtsFile, "--project", tsconfigPath]
for global in globalDtsFiles {
arguments.append(contentsOf: ["--global", global])
}
if let outputPath = outputPath {
arguments.append(contentsOf: ["--output", outputPath])
}
progress.print("Running ts2swift...")
progress.print(" \(([nodePath.path] + arguments).joined(separator: " "))")
let process = Process()
let stdoutPipe = Pipe()
nonisolated(unsafe) var stdoutData = Data()
process.executableURL = nodePath
process.arguments = arguments
process.standardOutput = stdoutPipe
stdoutPipe.fileHandleForReading.readabilityHandler = { handle in
let data = handle.availableData
if data.count > 0 {
stdoutData.append(data)
}
}
try process.forwardTerminationSignals {
try process.run()
process.waitUntilExit()
}
if process.terminationStatus != 0 {
throw BridgeJSCoreError("ts2swift returned \(process.terminationStatus)")
}
return String(decoding: stdoutData, as: UTF8.self)
}
extension Foundation.Process {
// Monitor termination/interrruption signals to forward them to child process
func setSignalForwarding(_ signalNo: Int32) -> DispatchSourceSignal {
let signalSource = DispatchSource.makeSignalSource(signal: signalNo)
signalSource.setEventHandler { [self] in
signalSource.cancel()
#if os(Windows)
_ = TerminateProcess(processHandle, 0)
#else
kill(processIdentifier, signalNo)
#endif
}
signalSource.resume()
return signalSource
}
func forwardTerminationSignals(_ body: () throws -> Void) rethrows {
let sources = [
setSignalForwarding(SIGINT),
setSignalForwarding(SIGTERM),
]
defer {
for source in sources {
source.cancel()
}
}
try body()
}
}