b6fdee8bfc
Consolidated release: the cross-platform Linux port (engine, generators, CLI, REPL, NRT, portable DSP), live ALSA audio + ALSA MIDI + POSIX OSC + portable WAV codec, the GTK4 GUI (LyrebirdUI on the SwiftOpenUI backend), and the Linux live-coding scratchpad (LiveCompile). Apple platforms unchanged; all additive. See RELEASES.md and LINUX_README.md. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
156 lines
6.6 KiB
Swift
156 lines
6.6 KiB
Swift
// SwiftFormatter.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
// LyrebirdLiveCompile — snippet source formatting.
|
|
//
|
|
// Shells out to the toolchain's `swift-format` (the same way `LiveCompiler`
|
|
// shells to `swiftc`) to pretty-print a snippet. macOS/Linux only — iOS cannot
|
|
// exec subprocesses. Writes the source to a temp file and runs `swift-format format
|
|
// <file>`, capturing stdout — avoids the write-stdin/read-stdout pipe deadlock
|
|
// a streaming approach risks on large output.
|
|
|
|
import Foundation
|
|
|
|
#if os(macOS) || os(Linux)
|
|
|
|
/// Stateless `swift-format` wrapper.
|
|
public enum SwiftFormatter {
|
|
|
|
/// Format `source` and return the pretty-printed result. Runs synchronously
|
|
/// (spawns `swift-format`); call off the main thread.
|
|
///
|
|
/// - Parameter source: Swift source to format. Top-level snippet code is
|
|
/// accepted — `swift-format` formats whatever parses.
|
|
/// - Returns: The formatted source.
|
|
/// - Throws: ``SwiftFormatterError`` for a missing tool, a non-zero exit
|
|
/// (typically a parse error), or an I/O failure.
|
|
public static func format(source: String) throws -> String {
|
|
let tool: String = try findSwiftFormat()
|
|
|
|
let id: String = UUID().uuidString.replacingOccurrences(of: "-", with: "")
|
|
let workDir: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent("LyrebirdSwiftFormat-\(id)", isDirectory: true)
|
|
let sourcePath: String = workDir.appendingPathComponent("Snippet.swift").path
|
|
do {
|
|
try FileManager.default.createDirectory(at: workDir, withIntermediateDirectories: true)
|
|
} catch {
|
|
throw SwiftFormatterError.ioFailed("\(error)")
|
|
}
|
|
// Register cleanup as soon as the dir exists, so a later write failure
|
|
// doesn't leak it.
|
|
defer { try? FileManager.default.removeItem(at: workDir) }
|
|
do {
|
|
try source.write(toFile: sourcePath, atomically: true, encoding: .utf8)
|
|
} catch {
|
|
throw SwiftFormatterError.ioFailed("\(error)")
|
|
}
|
|
|
|
let process: Process = Process()
|
|
process.executableURL = URL(fileURLWithPath: tool)
|
|
process.arguments = ["format", sourcePath]
|
|
let stdoutPipe: Pipe = Pipe()
|
|
let stderrPipe: Pipe = Pipe()
|
|
process.standardOutput = stdoutPipe
|
|
process.standardError = stderrPipe
|
|
do {
|
|
try process.run()
|
|
} catch {
|
|
throw SwiftFormatterError.ioFailed("swift-format launch failed: \(error)")
|
|
}
|
|
// Drain stdout AND stderr concurrently before waiting. `swift-format` can
|
|
// emit both a large formatted buffer and (on a broken snippet) a large
|
|
// diagnostic stream; reading them sequentially would deadlock if the
|
|
// stream we aren't reading yet fills its OS pipe buffer while the child
|
|
// blocks writing to it.
|
|
let outHandle: FileHandle = stdoutPipe.fileHandleForReading
|
|
let errHandle: FileHandle = stderrPipe.fileHandleForReading
|
|
let group: DispatchGroup = DispatchGroup()
|
|
let drainQueue: DispatchQueue = DispatchQueue(
|
|
label: "net.realizedsound.lyrebird.swift-format-drain",
|
|
attributes: .concurrent
|
|
)
|
|
// Box the drained bytes in reference cells: on Linux the `DispatchQueue`
|
|
// closures are `@Sendable` and cannot mutate a captured `var`. Each
|
|
// closure writes its own box (no shared mutation), and `group.wait()`
|
|
// fences before the reads below.
|
|
let outBox: SwiftFormatterDataBox = SwiftFormatterDataBox()
|
|
let errBox: SwiftFormatterDataBox = SwiftFormatterDataBox()
|
|
group.enter()
|
|
drainQueue.async { outBox.data = outHandle.readDataToEndOfFile(); group.leave() }
|
|
group.enter()
|
|
drainQueue.async { errBox.data = errHandle.readDataToEndOfFile(); group.leave() }
|
|
group.wait()
|
|
process.waitUntilExit()
|
|
let outData: Data = outBox.data
|
|
let errData: Data = errBox.data
|
|
|
|
guard process.terminationStatus == 0 else {
|
|
let stderr: String = String(data: errData, encoding: .utf8) ?? ""
|
|
throw SwiftFormatterError.formatFailed(exitCode: process.terminationStatus, stderr: stderr)
|
|
}
|
|
guard let formatted: String = String(data: outData, encoding: .utf8) else {
|
|
throw SwiftFormatterError.ioFailed("swift-format produced non-UTF8 output")
|
|
}
|
|
return formatted
|
|
}
|
|
|
|
/// Whether a `swift-format` executable is available on this machine.
|
|
public static var isAvailable: Bool {
|
|
(try? findSwiftFormat()) != nil
|
|
}
|
|
|
|
// MARK: - Tool resolution
|
|
|
|
/// First-success search: `xcrun -f swift-format`, then hard-coded paths.
|
|
static func findSwiftFormat() throws -> String {
|
|
if let viaXcrun: String = swiftFormatViaXcrun() {
|
|
return viaXcrun
|
|
}
|
|
let candidates: [String] = [
|
|
"/usr/bin/swift-format",
|
|
"/usr/local/bin/swift-format",
|
|
"/opt/homebrew/bin/swift-format",
|
|
]
|
|
for path: String in candidates where FileManager.default.isExecutableFile(atPath: path) {
|
|
return path
|
|
}
|
|
throw SwiftFormatterError.toolNotFound
|
|
}
|
|
|
|
private static func swiftFormatViaXcrun() -> String? {
|
|
let xcrunPath: String = "/usr/bin/xcrun"
|
|
guard FileManager.default.isExecutableFile(atPath: xcrunPath) else { return nil }
|
|
let process: Process = Process()
|
|
process.executableURL = URL(fileURLWithPath: xcrunPath)
|
|
process.arguments = ["-f", "swift-format"]
|
|
let stdout: Pipe = Pipe()
|
|
process.standardOutput = stdout
|
|
process.standardError = FileHandle.nullDevice
|
|
do {
|
|
try process.run()
|
|
process.waitUntilExit()
|
|
} catch {
|
|
return nil
|
|
}
|
|
guard process.terminationStatus == 0 else { return nil }
|
|
let data: Data = stdout.fileHandleForReading.readDataToEndOfFile()
|
|
guard let raw: String = String(data: data, encoding: .utf8) else { return nil }
|
|
let trimmed: String = raw.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
return trimmed.isEmpty ? nil : trimmed
|
|
}
|
|
}
|
|
|
|
/// Reference cell for one drained pipe's bytes, so the concurrent drain closures
|
|
/// write through a reference instead of mutating a captured `var` (which the
|
|
/// Linux `@Sendable` `DispatchQueue` closures forbid). `@unchecked Sendable`:
|
|
/// each instance is written by exactly one closure and read only after
|
|
/// `DispatchGroup.wait()`.
|
|
private final class SwiftFormatterDataBox: @unchecked Sendable {
|
|
var data: Data = Data()
|
|
}
|
|
|
|
#endif
|