mirror of
https://github.com/xtool-org/xtool.git
synced 2026-11-21 18:55:56 +03:00
Compare commits
1 Commits
+13
-4
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"originHash" : "372e7c63deb9508728c2f792b06935bafc6dd9a5320c5376c7eb9fa2798f3f9c",
|
||||
"originHash" : "c7a8ecfa1983b2d2cd303da1fc360a5329a8fe77440411341561bb35dd3c197a",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "aexml",
|
||||
@@ -85,7 +85,7 @@
|
||||
{
|
||||
"identity" : "swift-algorithms",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-algorithms.git",
|
||||
"location" : "https://github.com/apple/swift-algorithms",
|
||||
"state" : {
|
||||
"revision" : "87e50f483c54e6efd60e885f7f5aa946cee68023",
|
||||
"version" : "1.2.1"
|
||||
@@ -94,7 +94,7 @@
|
||||
{
|
||||
"identity" : "swift-argument-parser",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-argument-parser.git",
|
||||
"location" : "https://github.com/apple/swift-argument-parser",
|
||||
"state" : {
|
||||
"revision" : "6a52f3251125d74daf04fcbd5e6f08a75d074382",
|
||||
"version" : "1.8.2"
|
||||
@@ -382,12 +382,21 @@
|
||||
{
|
||||
"identity" : "swift-system",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-system.git",
|
||||
"location" : "https://github.com/apple/swift-system",
|
||||
"state" : {
|
||||
"revision" : "869129b7bf4ecc57b97d0193ad29690ca2134750",
|
||||
"version" : "1.8.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swift-tools-protocols",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/swiftlang/swift-tools-protocols",
|
||||
"state" : {
|
||||
"revision" : "d81024558da3bcd53748c4cfdaba10a49242442e",
|
||||
"version" : "0.0.10"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swiftcli",
|
||||
"kind" : "remoteSourceControl",
|
||||
|
||||
@@ -68,6 +68,7 @@ let package = Package(
|
||||
|
||||
.package(url: "https://github.com/swiftlang/swift-docc-plugin", from: "1.0.0"),
|
||||
.package(url: "https://github.com/swiftlang/swift-subprocess", from: "1.0.0"),
|
||||
.package(url: "https://github.com/swiftlang/swift-tools-protocols", exact: "0.0.10"),
|
||||
|
||||
.package(url: "https://github.com/swift-server/async-http-client.git", from: "1.23.0"),
|
||||
.package(url: "https://github.com/swift-server/swift-openapi-async-http-client", from: "1.0.0"),
|
||||
@@ -176,6 +177,7 @@ let package = Package(
|
||||
.product(name: "NIOPosix", package: "swift-nio"),
|
||||
.product(name: "Version", package: "Version"),
|
||||
.product(name: "libunxip", package: "unxip"),
|
||||
.product(name: "LanguageServerProtocolTransport", package: "swift-tools-protocols"),
|
||||
],
|
||||
cSettings: cSettings,
|
||||
swiftSettings: swiftSettings,
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
#include "inotify_shim.h"
|
||||
#include "stdout_shim.h"
|
||||
#include "version.h"
|
||||
#include "mobileprovision.h"
|
||||
@@ -0,0 +1,21 @@
|
||||
#ifndef CINOTIFY_SHIMS_H
|
||||
#define CINOTIFY_SHIMS_H
|
||||
|
||||
#ifdef __linux__
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#include <sys/inotify.h>
|
||||
|
||||
static inline const char *cin_event_name(const struct inotify_event *event) {
|
||||
if (event->len)
|
||||
return event->name;
|
||||
else
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static const uint32_t cin_all_events = IN_ALL_EVENTS;
|
||||
|
||||
#endif
|
||||
|
||||
#endif /* CINOTIFY_SHIMS_H */
|
||||
@@ -67,6 +67,11 @@ public actor Signer {
|
||||
) throws {
|
||||
let encoder = PropertyListEncoder()
|
||||
encoder.outputFormat = .xml
|
||||
var entitlementMapping = entitlementMapping
|
||||
if entitlementMapping.isEmpty {
|
||||
// zsign_sign requires at least one entitlements_data_t
|
||||
entitlementMapping[app] = try Entitlements(entitlements: [])
|
||||
}
|
||||
let entsArray: [entitlements_data_t] = try entitlementMapping.map { url, ents in
|
||||
try url.withUnsafeFileSystemRepresentation { bundlePath in
|
||||
guard let bundlePath = bundlePath else { throw Error.badFilePath }
|
||||
|
||||
@@ -23,10 +23,30 @@ struct PackOperation {
|
||||
|
||||
var triple: String?
|
||||
var buildOptions = BuildOptions(configuration: .debug)
|
||||
var extraOptions: [String] = []
|
||||
var watchMode = false
|
||||
var xcode = false
|
||||
|
||||
func buildSettings() async throws -> BuildSettings {
|
||||
try await BuildSettings(
|
||||
configuration: buildOptions.configuration,
|
||||
triple: triple ?? Self.defaultTriple,
|
||||
options: extraOptions + (
|
||||
watchMode
|
||||
? [
|
||||
"-Xlinker", "-interposable",
|
||||
// https://kyleye.top/posts/debugreplaceableview-multiple-type-erasers/
|
||||
"-Xswiftc", "-enable-experimental-feature", "-Xswiftc", "OpaqueTypeErasure",
|
||||
// https://www.guardsquare.com/blog/behind-swiftui-previews
|
||||
"-Xswiftc", "-Xfrontend", "-Xswiftc", "-enable-private-imports",
|
||||
]
|
||||
: []
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func run() async throws -> URL {
|
||||
func run() async throws -> (Plan, URL) {
|
||||
// TODO: support running inside a child directory
|
||||
|
||||
let contents = try FileManager.default.contentsOfDirectory(atPath: ".")
|
||||
@@ -54,11 +74,7 @@ struct PackOperation {
|
||||
|
||||
await LSPConfig.tryEnsure(using: schema)
|
||||
|
||||
let buildSettings = try await BuildSettings(
|
||||
configuration: buildOptions.configuration,
|
||||
triple: triple ?? Self.defaultTriple,
|
||||
options: []
|
||||
)
|
||||
let buildSettings = try await buildSettings()
|
||||
|
||||
let planner = Planner(
|
||||
buildSettings: buildSettings,
|
||||
@@ -68,7 +84,8 @@ struct PackOperation {
|
||||
|
||||
#if os(macOS)
|
||||
if xcode {
|
||||
return try await XcodePacker(plan: plan).createProject()
|
||||
let url = try await XcodePacker(plan: plan).createProject()
|
||||
return (plan, url)
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -81,28 +98,26 @@ struct PackOperation {
|
||||
let productsWithEntitlements = plan
|
||||
.allProducts
|
||||
.compactMap { p in p.entitlementsPath.map { (p, $0) } }
|
||||
if !productsWithEntitlements.isEmpty {
|
||||
let mapping = try await withThrowingTaskGroup(of: (URL, Entitlements).self) { group in
|
||||
for (product, path) in productsWithEntitlements {
|
||||
group.addTask {
|
||||
let data = try await Data(reading: URL(fileURLWithPath: path))
|
||||
let decoder = PropertyListDecoder()
|
||||
let entitlements = try decoder.decode(Entitlements.self, from: data)
|
||||
return (product.directory(inApp: bundle), entitlements)
|
||||
}
|
||||
let mapping = try await withThrowingTaskGroup(of: (URL, Entitlements?).self) { group in
|
||||
for (product, path) in productsWithEntitlements {
|
||||
group.addTask {
|
||||
let data = try await Data(reading: URL(fileURLWithPath: path))
|
||||
let decoder = PropertyListDecoder()
|
||||
let entitlements = try decoder.decode(Entitlements.self, from: data)
|
||||
return (product.directory(inApp: bundle), entitlements)
|
||||
}
|
||||
return try await group.reduce(into: [:]) { $0[$1.0] = $1.1 }
|
||||
}
|
||||
print("Applying entitlements...")
|
||||
try await Signer.first().sign(
|
||||
app: bundle,
|
||||
identity: .adhoc,
|
||||
entitlementMapping: mapping,
|
||||
progress: { _ in }
|
||||
)
|
||||
return try await group.reduce(into: [:]) { $0[$1.0] = $1.1 }
|
||||
}
|
||||
print("Applying entitlements...")
|
||||
try await Signer.first().sign(
|
||||
app: bundle,
|
||||
identity: .adhoc,
|
||||
entitlementMapping: mapping,
|
||||
progress: { _ in }
|
||||
)
|
||||
|
||||
return bundle
|
||||
return (plan, bundle)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,7 +172,7 @@ struct DevBuildCommand: AsyncParsableCommand {
|
||||
signingAuthToken = nil
|
||||
}
|
||||
|
||||
let url = try await PackOperation(
|
||||
let (_, url) = try await PackOperation(
|
||||
triple: triple,
|
||||
buildOptions: packOptions
|
||||
).run()
|
||||
@@ -222,6 +237,13 @@ struct DevRunCommand: AsyncParsableCommand {
|
||||
help: "Target the iOS Simulator"
|
||||
) var simulator = false
|
||||
|
||||
@Flag(
|
||||
name: .shortAndLong,
|
||||
help: "Hot reload files on change. Requires simulator."
|
||||
) var watch = false
|
||||
|
||||
@Option var xloadPath: String?
|
||||
|
||||
var triple: String? {
|
||||
if simulator {
|
||||
#if arch(arm64)
|
||||
@@ -235,17 +257,37 @@ struct DevRunCommand: AsyncParsableCommand {
|
||||
return nil
|
||||
}
|
||||
#else
|
||||
var watch: Bool { false }
|
||||
var triple: String? { nil }
|
||||
#endif
|
||||
|
||||
@OptionGroup var connectionOptions: ConnectionOptions
|
||||
|
||||
func validate() throws {
|
||||
#if os(macOS)
|
||||
if watch && !simulator {
|
||||
throw ValidationError("--watch requires --simulator")
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
func run() async throws {
|
||||
let output = try await PackOperation(triple: triple, buildOptions: packOptions).run()
|
||||
let operation = PackOperation(
|
||||
triple: triple,
|
||||
buildOptions: packOptions,
|
||||
watchMode: watch,
|
||||
)
|
||||
let (plan, output) = try await operation.run()
|
||||
|
||||
#if os(macOS)
|
||||
if simulator {
|
||||
try await SimInstallOperation(path: output).run()
|
||||
try await SimInstallOperation(
|
||||
operation: operation,
|
||||
plan: plan,
|
||||
path: output,
|
||||
watch: watch,
|
||||
xLoadLibrary: xloadPath,
|
||||
).run()
|
||||
return
|
||||
}
|
||||
#endif
|
||||
@@ -294,24 +336,3 @@ struct DevCommand: AsyncParsableCommand {
|
||||
}
|
||||
|
||||
extension BuildConfiguration: ExpressibleByArgument {}
|
||||
|
||||
#if os(macOS)
|
||||
import Subprocess
|
||||
|
||||
struct SimInstallOperation {
|
||||
var path: URL
|
||||
|
||||
// TODO: allow customizing this
|
||||
var simulator = "booted"
|
||||
|
||||
func run() async throws {
|
||||
try await Subprocess.run(
|
||||
.path("/usr/bin/xcrun"),
|
||||
arguments: ["simctl", "install", simulator, path.path],
|
||||
output: .discarded
|
||||
)
|
||||
.checkSuccess()
|
||||
print("Installed to simulator")
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,101 @@
|
||||
#if os(macOS)
|
||||
|
||||
import Foundation
|
||||
import ArgumentParser
|
||||
import PackLib
|
||||
import XUtils
|
||||
import Subprocess
|
||||
|
||||
struct HotReloadCommand: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "hot-reload",
|
||||
abstract: "Run an app with support for hot reloading",
|
||||
)
|
||||
|
||||
@Flag(
|
||||
help: "Use the SwiftPM build system to determine compile commands"
|
||||
) var swiftpm = false
|
||||
|
||||
@Option(
|
||||
help: .init(
|
||||
"Use the specified Build Server to determine compile commands",
|
||||
discussion: """
|
||||
The file at the specified path should correspond to the BSP \
|
||||
Connection Details specification. See:
|
||||
|
||||
https://build-server-protocol.github.io/docs/overview/server-discovery
|
||||
""",
|
||||
)
|
||||
) var buildServerPath: String?
|
||||
|
||||
@Option(
|
||||
help: "The directory in which to store scratch files"
|
||||
) var scratchDirectory: String?
|
||||
|
||||
@Option(
|
||||
help: "String to prepend to all env var names"
|
||||
) var envPrefix: String = ""
|
||||
|
||||
@Option(
|
||||
help: .hidden
|
||||
) var xloadLibrary: String?
|
||||
|
||||
@Argument(
|
||||
help: .init(
|
||||
"The command to run with hot reloading",
|
||||
discussion: """
|
||||
xtool spawns the provided process with env vars set to enable hot reloading.
|
||||
"""
|
||||
)
|
||||
) var command: [String]
|
||||
|
||||
func run() async throws {
|
||||
let configuration: BuildServerConfiguration
|
||||
switch (swiftpm, buildServerPath) {
|
||||
case (true, _?):
|
||||
throw ValidationError("Both --swiftpm or --build-server-path were provided; please only provide one.")
|
||||
case (true, nil):
|
||||
configuration = try await .swiftPM(settings: BuildSettings(configuration: .debug, triple: "arm64-apple-ios-simulator"))
|
||||
case (false, let serverPath?):
|
||||
configuration = try await .external(definition: URL(filePath: serverPath))
|
||||
case (false, nil):
|
||||
if let discovered = try await BuildServerConfiguration.discover(in: URL(filePath: ".")) {
|
||||
configuration = discovered
|
||||
} else {
|
||||
throw ValidationError("Could not guess build system. Please specify one with --swiftpm or --build-server-path")
|
||||
}
|
||||
}
|
||||
|
||||
let reloader = try await HotReloader(
|
||||
configuration: configuration,
|
||||
scratchDirectory: scratchDirectory.map { FilePath($0) },
|
||||
xLoadLibrary: xloadLibrary
|
||||
)
|
||||
|
||||
let watchTask = Task {
|
||||
do {
|
||||
try await reloader.watch()
|
||||
} catch {
|
||||
print("Error: watcher failed: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
var arguments = command
|
||||
let executable = arguments.removeFirst()
|
||||
|
||||
try await Subprocess.run(
|
||||
.name(executable),
|
||||
arguments: Arguments(arguments),
|
||||
environment: .inherit.updating(reloader.subprocessEnvironment(prefix: envPrefix)),
|
||||
platformOptions: .withGracefulShutDown,
|
||||
output: .currentStandardOutput,
|
||||
error: .currentStandardError,
|
||||
)
|
||||
.checkSuccess()
|
||||
|
||||
watchTask.cancel()
|
||||
await watchTask.value
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,111 @@
|
||||
#if os(macOS)
|
||||
|
||||
import Subprocess
|
||||
import PackLib
|
||||
import Foundation
|
||||
import XUtils
|
||||
import Dependencies
|
||||
import XKit
|
||||
|
||||
actor HotReloader {
|
||||
var configuration: BuildServerConfiguration
|
||||
var scratchDirectory: FilePath
|
||||
var xLoadLibrary: String?
|
||||
|
||||
private let scratchTemporaryDirectory: TemporaryDirectory?
|
||||
private let xLoadPath: String
|
||||
private let buildDirectory: FilePath
|
||||
private let outDirectory: FilePath
|
||||
|
||||
init(
|
||||
configuration: BuildServerConfiguration,
|
||||
scratchDirectory: FilePath? = nil,
|
||||
xLoadLibrary: String? = nil,
|
||||
) async throws {
|
||||
self.configuration = configuration
|
||||
|
||||
if let scratchDirectory {
|
||||
self.scratchDirectory = FilePath(URL(filePath: scratchDirectory.string).absoluteURL.path)
|
||||
self.scratchTemporaryDirectory = nil
|
||||
} else {
|
||||
let scratchTemporaryDirectory = try TemporaryDirectory(name: "scratch")
|
||||
self.scratchDirectory = FilePath(scratchTemporaryDirectory.url.path)
|
||||
self.scratchTemporaryDirectory = consume scratchTemporaryDirectory
|
||||
}
|
||||
|
||||
self.xLoadLibrary = xLoadLibrary
|
||||
|
||||
xLoadPath = if let xLoadLibrary {
|
||||
URL(filePath: xLoadLibrary).absoluteURL.path
|
||||
} else {
|
||||
try await Self.getXLoad(platform: "iphonesimulator").path
|
||||
}
|
||||
|
||||
buildDirectory = self.scratchDirectory.appending("build")
|
||||
try FileManager.default.createDirectory(at: URL(filePath: buildDirectory)!, withIntermediateDirectories: true)
|
||||
|
||||
outDirectory = self.scratchDirectory.appending("out")
|
||||
try FileManager.default.createDirectory(at: URL(filePath: outDirectory)!, withIntermediateDirectories: true)
|
||||
}
|
||||
|
||||
nonisolated func environment(prefix: String = "SIMCTL_CHILD_") -> [String: String] {
|
||||
[
|
||||
"\(prefix)DYLD_INSERT_LIBRARIES": xLoadPath,
|
||||
"\(prefix)XLOAD_WATCH_DIR": outDirectory.string,
|
||||
"\(prefix)XLOAD_INTERCEPT": "1",
|
||||
]
|
||||
}
|
||||
|
||||
nonisolated func subprocessEnvironment(prefix: String = "SIMCTL_CHILD_") -> [Environment.Key: String] {
|
||||
Dictionary(uniqueKeysWithValues: environment(prefix: prefix).map {
|
||||
(Environment.Key(rawValue: $0)!, $1)
|
||||
})
|
||||
}
|
||||
|
||||
func watch() async throws {
|
||||
let workspace = try await SwiftWorkspace(
|
||||
configuration: configuration,
|
||||
buildDirectory: buildDirectory,
|
||||
outDirectory: outDirectory,
|
||||
)
|
||||
|
||||
@Dependency(\.fileSystemMonitor) var fileSystemMonitor
|
||||
let events = try await fileSystemMonitor.watch(FilePath(FileManager.default.currentDirectoryPath))
|
||||
|
||||
for await event in events {
|
||||
do {
|
||||
try await workspace.fileDidChange(event.file)
|
||||
} catch {
|
||||
print("Reload failed: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static func getXLoad(platform: String) async throws -> URL {
|
||||
let version = "0.3.0"
|
||||
let remote = URL(string: "https://github.com/xtool-org/xload/releases/download/v\(version)/libXLoad.\(platform).dylib")!
|
||||
|
||||
@Dependency(\.httpClient) var httpClient
|
||||
@Dependency(\.persistentDirectory) var persistentDirectory
|
||||
|
||||
let platformDir = persistentDirectory.appending(path: "xload/\(platform)")
|
||||
let versionDir = platformDir.appending(path: version)
|
||||
let local = versionDir.appending(path: "libXLoad.dylib")
|
||||
if local.exists { return local }
|
||||
|
||||
print("Downloading xload...")
|
||||
|
||||
try? FileManager.default.removeItem(at: platformDir)
|
||||
try FileManager.default.createDirectory(at: versionDir, withIntermediateDirectories: true)
|
||||
|
||||
let data = try await httpClient.makeRequest(HTTPRequest(url: remote))
|
||||
guard data.response.status.kind == .successful else {
|
||||
throw StringError("Failed to download xload: got HTTP \(data.response.status)")
|
||||
}
|
||||
try data.body.write(to: local)
|
||||
|
||||
return local
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,81 @@
|
||||
#if os(macOS)
|
||||
import Subprocess
|
||||
import PackLib
|
||||
import Foundation
|
||||
import XUtils
|
||||
import Dependencies
|
||||
import XKit
|
||||
|
||||
struct SimInstallOperation {
|
||||
var operation: PackOperation
|
||||
var plan: Plan
|
||||
var path: URL
|
||||
|
||||
var watch = false
|
||||
var xLoadLibrary: String?
|
||||
|
||||
// TODO: allow customizing this
|
||||
var simulator = "booted"
|
||||
|
||||
func run() async throws {
|
||||
try await Subprocess.run(
|
||||
.path("/usr/bin/xcrun"),
|
||||
arguments: ["simctl", "install", simulator, path.path],
|
||||
output: .discarded
|
||||
)
|
||||
.checkSuccess()
|
||||
|
||||
print("Installed to simulator")
|
||||
|
||||
let tmp = URL(filePath: FileManager.default.currentDirectoryPath)
|
||||
.appending(path: "xtool/.xload")
|
||||
try? FileManager.default.removeItem(at: tmp)
|
||||
defer { try? FileManager.default.removeItem(at: tmp) }
|
||||
|
||||
let watchTask: Task<Void, Error>?
|
||||
let envVars: [Environment.Key: String?]
|
||||
if watch {
|
||||
try FileManager.default.createDirectory(at: tmp, withIntermediateDirectories: true)
|
||||
guard let temporaryDirectoryPath = FilePath(tmp) else {
|
||||
throw Console.Error("Bad temporaryDirectory path")
|
||||
}
|
||||
|
||||
let hotReloader = try await HotReloader(
|
||||
configuration: .swiftPM(settings: operation.buildSettings()),
|
||||
scratchDirectory: temporaryDirectoryPath,
|
||||
xLoadLibrary: xLoadLibrary
|
||||
)
|
||||
|
||||
watchTask = Task {
|
||||
do {
|
||||
try await hotReloader.watch()
|
||||
} catch {
|
||||
print("Error: watch task failed: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
envVars = hotReloader.subprocessEnvironment()
|
||||
} else {
|
||||
watchTask = nil
|
||||
envVars = [:]
|
||||
}
|
||||
|
||||
try await Subprocess.run(
|
||||
.path("/usr/bin/xcrun"),
|
||||
arguments: [
|
||||
"simctl", "launch",
|
||||
"--console-pty",
|
||||
simulator, plan.app.bundleID,
|
||||
],
|
||||
environment: .inherit.updating(envVars),
|
||||
platformOptions: .withGracefulShutDown,
|
||||
output: .currentStandardOutput,
|
||||
error: .currentStandardError,
|
||||
)
|
||||
.checkSuccess()
|
||||
|
||||
watchTask?.cancel()
|
||||
try await watchTask?.value
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,397 @@
|
||||
import Foundation
|
||||
import XUtils
|
||||
import PackLib
|
||||
import BuildServerProtocol
|
||||
import LanguageServerProtocol
|
||||
import LanguageServerProtocolTransport
|
||||
import Subprocess
|
||||
import Dependencies
|
||||
|
||||
actor SwiftWorkspace {
|
||||
private let connection: JSONRPCConnection
|
||||
private let buildDirectory: FilePath
|
||||
private let outDirectory: FilePath
|
||||
private var counter = 0
|
||||
|
||||
struct FileInfo {
|
||||
let file: FilePath
|
||||
let target: BuildTarget
|
||||
let sources: SourcesItem
|
||||
let source: SourceItem
|
||||
|
||||
init?(target: BuildTarget, sources: SourcesItem, source: SourceItem) {
|
||||
guard let path = FilePath(source.uri.arbitrarySchemeURL) else { return nil }
|
||||
self.file = path
|
||||
self.target = target
|
||||
self.sources = sources
|
||||
self.source = source
|
||||
}
|
||||
}
|
||||
|
||||
private var filesToWatch: [FilePath: [FileInfo]] = [:]
|
||||
private var sources: [(BuildTarget, SourcesItem)] {
|
||||
didSet { updateFilesToWatch() }
|
||||
}
|
||||
private var cachedCommands: [FilePath: FrontendCommand] = [:]
|
||||
|
||||
struct FrontendCommand {
|
||||
let commandLine: CommandInvocation
|
||||
let output: FilePath
|
||||
let module: String
|
||||
}
|
||||
|
||||
init(
|
||||
configuration: BuildServerConfiguration,
|
||||
buildDirectory: FilePath,
|
||||
outDirectory: FilePath,
|
||||
) async throws {
|
||||
self.buildDirectory = buildDirectory
|
||||
self.outDirectory = outDirectory
|
||||
|
||||
let handler = StreamingMessageHandler()
|
||||
|
||||
let (connection, _) = try JSONRPCConnection.start(
|
||||
executable: configuration.executable,
|
||||
arguments: configuration.arguments,
|
||||
name: "xtool",
|
||||
protocol: .bspProtocol,
|
||||
stderrLoggingCategory: "xtool-error",
|
||||
client: handler,
|
||||
terminationHandler: { print("Terminated: \($0)") }
|
||||
)
|
||||
self.connection = connection
|
||||
|
||||
_ = try await connection.send(InitializeBuildRequest(
|
||||
displayName: "xtool",
|
||||
version: "1.0.0",
|
||||
bspVersion: "2.2.0",
|
||||
rootUri: .init(URL(filePath: FileManager.default.currentDirectoryPath)),
|
||||
capabilities: BuildClientCapabilities(
|
||||
languageIds: [.swift, .c, .cpp, .objective_c, .objective_cpp],
|
||||
)
|
||||
))
|
||||
|
||||
connection.send(OnBuildInitializedNotification())
|
||||
|
||||
// some BSP servers (eg SourceKit-Bazel-BSP) require an initial build targets request
|
||||
// before they send OnBuildTargetDidChange
|
||||
_ = try await connection.send(WorkspaceBuildTargetsRequest())
|
||||
|
||||
for await case _ as OnBuildTargetDidChangeNotification in handler.notifications { break }
|
||||
|
||||
let result = try await connection.send(WorkspaceBuildTargetsRequest())
|
||||
|
||||
let targets = Dictionary(uniqueKeysWithValues: result.targets.map { ($0.id, $0) })
|
||||
|
||||
let targetInfos = try await connection.send(BuildTargetSourcesRequest(
|
||||
targets: result.targets.map(\.id)
|
||||
))
|
||||
sources = targetInfos.items.compactMap {
|
||||
guard let target = targets[$0.target] else { return nil }
|
||||
return (target, $0)
|
||||
}
|
||||
|
||||
updateFilesToWatch()
|
||||
}
|
||||
|
||||
deinit {
|
||||
connection.close()
|
||||
}
|
||||
|
||||
func updateFilesToWatch() {
|
||||
filesToWatch = Dictionary(
|
||||
grouping: sources.flatMap { target, sources in
|
||||
sources.sources.compactMap { source in
|
||||
// guard !target.id.uri.stringValue.contains("&targetGUID=PACKAGE-TARGET:") else { return nil }
|
||||
FileInfo(target: target, sources: sources, source: source)
|
||||
}
|
||||
},
|
||||
by: \.file
|
||||
)
|
||||
}
|
||||
|
||||
func fileDidChange(_ path: FilePath) async throws {
|
||||
guard filesToWatch[path] != nil else { return }
|
||||
print("Reloading \(path)")
|
||||
_ = try await rebuild(path: path)
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func rebuild(path: FilePath) async throws -> FilePath {
|
||||
let command = try await frontendCommand(for: path)
|
||||
|
||||
try await Subprocess.run(
|
||||
.path(FilePath(String(command.commandLine.command))),
|
||||
arguments: .init(command.commandLine.arguments.map { String($0) }),
|
||||
output: .currentStandardOutput,
|
||||
error: .currentStandardError,
|
||||
)
|
||||
.checkSuccess()
|
||||
|
||||
let sdk = try command.commandLine.value(for: "-sdk")
|
||||
.orThrow(Console.Error("Could not find -sdk"))
|
||||
|
||||
let target = try command.commandLine.value(for: "-target")
|
||||
.orThrow(Console.Error("Could not find -target"))
|
||||
|
||||
counter += 1
|
||||
|
||||
let outputFile = outDirectory
|
||||
.appending("lib\(path.lastComponent!.stem).\(counter).dylib")
|
||||
|
||||
// link
|
||||
try await Subprocess.run(
|
||||
.path(try await BuildSettings.swiftcURL()),
|
||||
arguments: [
|
||||
command.output.string,
|
||||
"-emit-library",
|
||||
"-sdk", sdk, "-target", target,
|
||||
"-Xlinker", "-undefined", "-Xlinker", "dynamic_lookup",
|
||||
"-o", outputFile.string
|
||||
],
|
||||
output: .currentStandardOutput,
|
||||
error: .currentStandardError,
|
||||
)
|
||||
.checkSuccess()
|
||||
|
||||
return outputFile
|
||||
}
|
||||
|
||||
func frontendCommand(for path: FilePath) async throws -> FrontendCommand {
|
||||
if let cached = cachedCommands[path] {
|
||||
return cached
|
||||
}
|
||||
|
||||
let targets = filesToWatch[path] ?? []
|
||||
|
||||
let target: FileInfo
|
||||
switch targets.count {
|
||||
case 0:
|
||||
throw Console.Error("No targets for file")
|
||||
case 1:
|
||||
target = targets[0]
|
||||
default:
|
||||
print("warning: multiple targets contain this file: \(targets.map(\.target.id.uri))")
|
||||
target = targets[0]
|
||||
}
|
||||
|
||||
guard let fileURL = URL(filePath: path)?.absoluteURL, let lastComponent = path.lastComponent else {
|
||||
throw Console.Error("Bad file path \(path.string)")
|
||||
}
|
||||
|
||||
let options = try await connection.send(TextDocumentSourceKitOptionsRequest(
|
||||
textDocument: .init(target.source.uri),
|
||||
target: target.target.id,
|
||||
language: .swift,
|
||||
))
|
||||
.orThrow(Console.Error("No options"))
|
||||
|
||||
guard let moduleNameIndex = options.compilerArguments.firstIndex(of: "-module-name"),
|
||||
moduleNameIndex < options.compilerArguments.count - 2 else {
|
||||
throw Console.Error("Could not determine module name for file at \(path)")
|
||||
}
|
||||
let moduleName = options.compilerArguments[moduleNameIndex + 1]
|
||||
let moduleBuildDirectory = buildDirectory.appending(moduleName)
|
||||
let moduleBuildDirectoryURL = try URL(filePath: moduleBuildDirectory).orThrow(Console.Error("Bad module name"))
|
||||
try? FileManager.default.createDirectory(at: moduleBuildDirectoryURL, withIntermediateDirectories: true)
|
||||
|
||||
let swiftcOutput = try await Subprocess.run(
|
||||
.path(try await BuildSettings.swiftcURL()),
|
||||
arguments: .init(
|
||||
["-c", "-driver-print-jobs"]
|
||||
+ options.compilerArguments
|
||||
+ ["-working-directory", moduleBuildDirectory.string]
|
||||
),
|
||||
output: .string(limit: .max),
|
||||
error: .currentStandardError
|
||||
).checkSuccess()
|
||||
|
||||
let frontendCommands = (swiftcOutput.standardOutput ?? "").split(separator: "\n")
|
||||
guard let invocation = frontendCommands.lazy.compactMap({ line -> CommandInvocation? in
|
||||
guard let invocation = CommandInvocation(line) else { return nil }
|
||||
guard invocation.value(for: "-primary-file") == fileURL.path else { return nil }
|
||||
return invocation
|
||||
}).first else { throw Console.Error("Could not find frontend command") }
|
||||
|
||||
let command = FrontendCommand(
|
||||
commandLine: invocation,
|
||||
output: moduleBuildDirectory.appending("\(lastComponent.stem).o"),
|
||||
module: moduleName,
|
||||
)
|
||||
cachedCommands[path] = command
|
||||
return command
|
||||
}
|
||||
|
||||
private final class StreamingMessageHandler: MessageHandler {
|
||||
private let (_notifications, onNotification) = AsyncStream<NotificationType>.makeStream()
|
||||
|
||||
var notifications: AsyncStream<NotificationType> { _notifications }
|
||||
|
||||
deinit { onNotification.finish() }
|
||||
|
||||
func handle(_ notification: some NotificationType) {
|
||||
onNotification.yield(notification)
|
||||
}
|
||||
|
||||
func handle<Request: RequestType>(
|
||||
_ request: Request,
|
||||
id: LanguageServerProtocol.RequestID,
|
||||
reply: @escaping @Sendable (LanguageServerProtocol.LSPResult<Request.Response>) -> Void
|
||||
) {
|
||||
fatalError("Can't handle request \(Request.method)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// https://github.com/swiftlang/sourcekit-lsp/blob/3278ca0e3/Sources/BuildServerIntegration/ExternalBuildServerAdapter.swift#L66
|
||||
struct BuildServerConfiguration {
|
||||
var executable: URL
|
||||
var arguments: [String]
|
||||
}
|
||||
|
||||
// https://build-server-protocol.github.io/docs/overview/server-discovery#the-bsp-connection-details
|
||||
struct BuildServerDefinition: Codable {
|
||||
var name: String
|
||||
var version: String
|
||||
var bspVersion: String
|
||||
var languages: [String]
|
||||
var argv: [String]
|
||||
}
|
||||
|
||||
extension BuildServerConfiguration {
|
||||
static func swiftPM(settings: BuildSettings) async throws -> Self {
|
||||
guard let swiftURL = URL(filePath: try await BuildSettings.swiftURL()) else {
|
||||
throw Console.Error("Swift URL invalid")
|
||||
}
|
||||
return BuildServerConfiguration(
|
||||
executable: swiftURL,
|
||||
arguments: settings.withPackagePath("xtool/.xtool-tmp").buildServerArguments
|
||||
)
|
||||
}
|
||||
|
||||
static func swiftPM(in url: URL) async throws -> Self? {
|
||||
if url.appending(path: "Package.swift").exists {
|
||||
return try await .swiftPM(settings: .init(configuration: .debug, triple: "arm64-apple-ios-simulator"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
static func external(definition: BuildServerDefinition) async throws -> Self {
|
||||
guard !definition.argv.isEmpty else {
|
||||
throw Console.Error("BSP argv must be non-empty")
|
||||
}
|
||||
var arguments = definition.argv
|
||||
let executable = URL(filePath: arguments.removeFirst())
|
||||
return BuildServerConfiguration(
|
||||
executable: executable,
|
||||
arguments: arguments
|
||||
)
|
||||
}
|
||||
|
||||
static func external(definition url: URL) async throws -> Self {
|
||||
let data = try Data(contentsOf: url)
|
||||
let definition = try JSONDecoder().decode(BuildServerDefinition.self, from: data)
|
||||
return try await .external(definition: definition)
|
||||
}
|
||||
|
||||
static func external(in directory: URL) async throws -> Self? {
|
||||
let bsp = directory.appending(path: ".bsp")
|
||||
let bspContents = (try? FileManager.default.contentsOfDirectory(at: bsp, includingPropertiesForKeys: nil)) ?? []
|
||||
let bspFiles = bspContents.filter { $0.pathExtension == "json" }
|
||||
switch bspFiles.count {
|
||||
case 0:
|
||||
return nil
|
||||
case 1:
|
||||
return try await .external(definition: bspFiles[0])
|
||||
default:
|
||||
throw Console.Error("""
|
||||
Found multiple Build Server definitions in '\(bsp.absoluteURL.path)'.
|
||||
|
||||
Please explicitly specify the one you want to use.
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
static func discover(in directory: URL) async throws -> Self? {
|
||||
if let external = try await external(in: directory) {
|
||||
return external
|
||||
}
|
||||
|
||||
if let swiftPM = try await swiftPM(in: directory) {
|
||||
return swiftPM
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
struct CommandInvocation {
|
||||
var command: String
|
||||
var arguments: [String]
|
||||
|
||||
init?(_ string: some StringProtocol) {
|
||||
guard let all = try? CommandParser.parse(string), !all.isEmpty else { return nil }
|
||||
command = all[0]
|
||||
arguments = Array(all.dropFirst())
|
||||
}
|
||||
|
||||
func value(for option: some StringProtocol) -> String? {
|
||||
guard let optionIndex = arguments.firstIndex(where: { $0 == option }) else { return nil }
|
||||
guard optionIndex < arguments.count - 2 else { return nil }
|
||||
return arguments[optionIndex + 1]
|
||||
}
|
||||
}
|
||||
|
||||
enum CommandParser {
|
||||
enum Errors: Error, Hashable {
|
||||
case unclosedQuote
|
||||
case unpairedEscape
|
||||
}
|
||||
|
||||
static func parse(_ string: some StringProtocol) throws -> [String] {
|
||||
try sequence(
|
||||
state: (
|
||||
current: string[...],
|
||||
isInsideQuote: false,
|
||||
)
|
||||
) { state -> Token? in
|
||||
while !state.current.isEmpty {
|
||||
switch state.current.removeFirst() {
|
||||
case "'":
|
||||
state.isInsideQuote.toggle()
|
||||
case "\\" where !state.isInsideQuote:
|
||||
guard !state.current.isEmpty else { return .error(.unpairedEscape) }
|
||||
let actual = state.current.removeFirst()
|
||||
return .value(actual)
|
||||
case " " where !state.isInsideQuote:
|
||||
return .sentinelSpace
|
||||
case let value:
|
||||
return .value(value)
|
||||
}
|
||||
}
|
||||
guard !state.isInsideQuote else {
|
||||
state.isInsideQuote = false
|
||||
return .error(.unclosedQuote)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
.lazy
|
||||
.split(separator: .sentinelSpace)
|
||||
.map {
|
||||
let characters = try $0.compactMap { token -> Character? in
|
||||
switch token {
|
||||
case .sentinelSpace: nil
|
||||
case .error(let error): throw error
|
||||
case .value(let value): value
|
||||
}
|
||||
}
|
||||
return String(characters)
|
||||
}
|
||||
}
|
||||
|
||||
private enum Token: Hashable {
|
||||
case sentinelSpace
|
||||
case value(Character)
|
||||
case error(Errors)
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,13 @@ private struct XToolCommand: AsyncParsableCommand {
|
||||
NewCommand.self,
|
||||
DevCommand.self,
|
||||
DSCommand.self,
|
||||
]
|
||||
] + { () -> [AsyncParsableCommand.Type] in
|
||||
#if os(macOS)
|
||||
[HotReloadCommand.self]
|
||||
#else
|
||||
[]
|
||||
#endif
|
||||
}()
|
||||
),
|
||||
CommandGroup(
|
||||
name: "Device",
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import Testing
|
||||
@testable import XToolSupport
|
||||
|
||||
@Test func commandParser() throws {
|
||||
func sut(_ string: some StringProtocol) throws -> [String] {
|
||||
try CommandParser.parse(string)
|
||||
}
|
||||
|
||||
#expect(try sut(#""#).isEmpty)
|
||||
#expect(try sut(#"foo"#) == ["foo"])
|
||||
#expect(try sut(#"foo "#) == ["foo"])
|
||||
#expect(try sut(#"foo one two"#) == ["foo", "one", "two"])
|
||||
#expect(try sut(#"foo 'one two' three"#) == ["foo", "one two", "three"])
|
||||
#expect(try sut(#"foo 'one!two' three"#) == ["foo", "one!two", "three"])
|
||||
#expect(try sut(#"foo one\!two three"#) == ["foo", "one!two", "three"])
|
||||
#expect(try sut(#"foo one\'two three"#) == ["foo", "one'two", "three"])
|
||||
#expect(try sut(#"foo one'two three'four five"#) == ["foo", "onetwo threefour", "five"])
|
||||
|
||||
#expect(throws: CommandParser.Errors.unclosedQuote) {
|
||||
try sut(#"foo one two' three"#)
|
||||
}
|
||||
#expect(throws: CommandParser.Errors.unpairedEscape) {
|
||||
try sut(#"foo a b \"#)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user