Files
Lyrebird/LiveCompile/Sources/LyrebirdLiveCompile/SwiftFormatter.swift
T
josh 62b2f5dbec v1.5.0 release: LyrebirdRandom + Live Scratch editor
LyrebirdRandom scalar distribution sampling (seedable value type + shared
Random) with DistributionKind.sample dispatcher. Live Scratch editor: rename to
LyrebirdScratch, App Support artifact staging, Format Code (⌥⌘F), Render to File
(⌥⌘R offline CAF), line-number gutter, manual completion, Foundation in snippets,
scroll-jump fix, scheduling/NRT docs.
2026-07-22 07:53:12 -07:00

141 lines
5.7 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 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)
/// 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
)
var outData: Data = Data()
var errData: Data = Data()
group.enter()
drainQueue.async { outData = outHandle.readDataToEndOfFile(); group.leave() }
group.enter()
drainQueue.async { errData = errHandle.readDataToEndOfFile(); group.leave() }
group.wait()
process.waitUntilExit()
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
}
}
#endif