-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPackage.swift
More file actions
203 lines (184 loc) · 6.79 KB
/
Package.swift
File metadata and controls
203 lines (184 loc) · 6.79 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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
/*
* Package.swift
* SwiftPython
* -----
* Copyright (c) 2025 - 2026 Hunter Baker hunter@literallyanything.net
* Licensed under the MIT License
*/
// swift-tools-version: 6.2
import CompilerPluginSupport
import PackageDescription
import Foundation
import RegexBuilder
func findExecutableInPath(executableName: String) -> String? {
guard let path = ProcessInfo.processInfo.environment["PATH"] else {
print("PATH environment variable not found.")
return nil
}
let pathComponents = path.split(separator: ":").map(String.init)
for directory in pathComponents {
let fullPath = (directory as NSString).appendingPathComponent(executableName)
if FileManager.default.isExecutableFile(atPath: fullPath) {
return fullPath
}
}
return nil
}
func findPythonInfo() -> (cFlags: [String], linkerFlags: [String], extSuffix: String, versionStr: String)? {
let executablePath: String? = ProcessInfo.processInfo.environment["SWIFTPYTHON_PY_PATH"]
let pythonConfigExecutable: String?
if let executablePath {
// Check if it is the name of the executable in PATH, otherwise, use it directly as the path
pythonConfigExecutable = findExecutableInPath(executableName: executablePath) ?? executablePath
} else {
// By default, use the first `python3-config` executable in PATH (not free-threaded)
pythonConfigExecutable = findExecutableInPath(executableName: "python3-config")
}
guard let pythonConfigExecutable else {
return nil
}
func getOutput(_ arguments: [String]) -> [String]? {
let task = Process()
task.executableURL = URL(fileURLWithPath: pythonConfigExecutable)
task.arguments = arguments
let pipe = Pipe()
task.standardOutput = pipe
do {
try task.run()
} catch {
print(error)
return nil
}
let data = pipe.fileHandleForReading.readDataToEndOfFile()
task.waitUntilExit()
guard let output = String(data: data, encoding: .utf8) else {
return nil
}
return output.split(separator: "\n").compactMap { $0.isEmpty ? nil : $0.trimmingCharacters(in: .whitespacesAndNewlines) }
}
func getArgs(_ output: String?) -> [String]? {
return output?.split(separator: " ").compactMap { $0.isEmpty ? nil : $0.trimmingCharacters(in: .whitespacesAndNewlines) }
}
let outputs = getOutput(["--cflags", "--ldflags", "--extension-suffix", "--prefix"])
guard let outputs else {
return nil
}
let cFlags = getArgs(outputs[0])
guard let cFlags else {
return nil
}
let ldFlags = getArgs(outputs[1])
guard let ldFlags else {
return nil
}
let extSuffix = outputs[2]
let libDir = outputs[3] + "/lib"
let files = try? FileManager.default.contentsOfDirectory(atPath: libDir)
guard let files else {
fatalError("Failed to list dir: \(libDir)")
}
var versionStr: String? = nil
for file in files {
let regex = Regex {
"libpython"
Capture {
"3."
OneOrMore {
CharacterClass.digit
}
}
"."
ChoiceOf {
"dylib"
"so"
}
}
if let match = file.wholeMatch(of: regex) {
versionStr = String(match.output.1)
}
}
guard let versionStr else {
fatalError("Could not find python version. Found no binary in \(libDir).")
}
return (cFlags, ldFlags, extSuffix, versionStr)
}
let swiftArgs: [SwiftSetting] = [
.interoperabilityMode(.Cxx)
]
var cArgs: [CSetting] = [
.unsafeFlags(["-Wno-module-import-in-extern-c", "-fapinotes-modules"])
]
var cxxArgs: [CXXSetting] = [
.unsafeFlags(["-Wno-module-import-in-extern-c", "-fapinotes-modules"])
]
var linkerArgs: [LinkerSetting] = []
if let pythonInfo = findPythonInfo() {
cArgs.append(.unsafeFlags(pythonInfo.cFlags))
cxxArgs.append(.unsafeFlags(pythonInfo.cFlags))
linkerArgs.append(.unsafeFlags(pythonInfo.linkerFlags))
linkerArgs.append(.linkedLibrary("python\(pythonInfo.versionStr)"))
} else {
fatalError("Failed to find a python install. `python-config` must be in PATH.")
}
let package = Package(
name: "SwiftPython",
platforms: [.macOS(.v26)],
products: [
.library(
name: "SwiftPython",
targets: ["SwiftPython", "CPython"]
),
.library(name: "example.cpython-314-darwin", type: .dynamic, targets: ["Example"]),
.plugin(name: "SwiftPythonPlugin", targets: ["SwiftPythonPlugin"])
],
dependencies: [
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.5.0"),
.package(url: "https://github.com/swiftlang/swift-syntax", from: "602.0.0"),
.package(url: "https://github.com/swiftlang/swift-docc-symbolkit.git", branch: "main"),
.package(url: "https://github.com/apple/swift-collections.git", from: "1.3.0")
],
targets: [
.target(
name: "CPython",
cSettings: cArgs,
cxxSettings: cxxArgs,
swiftSettings: swiftArgs,
linkerSettings: linkerArgs
),
.target(
name: "SwiftPython",
dependencies: [
"CPython",
.product(name: "BasicContainers", package: "swift-collections")
],
cSettings: cArgs,
cxxSettings: cxxArgs,
swiftSettings: [
.enableExperimentalFeature("Lifetimes")
] + swiftArgs,
linkerSettings: linkerArgs
),
.executableTarget(
name: "SwiftPythonTool",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
.product(name: "SymbolKit", package: "swift-docc-symbolkit"),
.product(name: "SwiftBasicFormat", package: "swift-syntax"),
.product(name: "SwiftSyntax", package: "swift-syntax"),
.product(name: "SwiftSyntaxBuilder", package: "swift-syntax")
]
),
.plugin(
name: "SwiftPythonPlugin",
capability: .command(
intent: .custom(verb: "swift-python-gen", description: "Generate python bindings for a target."),
permissions: [.writeToPackageDirectory(reason: "To output the bindings.")]
),
dependencies: [
"SwiftPythonTool"
]
),
// This is temporary. It's just a bit easier to test quickly with this here.
.target(name: "Example", dependencies: ["SwiftPython", "CPython"], path: "Samples/Example", cSettings: cArgs, cxxSettings: cxxArgs, swiftSettings: swiftArgs, linkerSettings: linkerArgs)
]
)