Files
Lyrebird/Sources/LyrebirdCLI/InteractiveShell.swift
T
josh b6fdee8bfc Lyrebird 2.0.0 — Linux support
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>
2026-09-10 21:09:11 -07:00

301 lines
12 KiB
Swift

// InteractiveShell.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LineNoise
/// Commands recognised by the `lyrebird>` interactive shell.
public enum ShellCommand: Equatable {
/// Build the current package, then launch `swift repl` with Lyrebird available.
case repl
/// Scaffold a new Lyrebird project with the given name and template.
case new(name: String, template: ProjectTemplate, lyrebirdPath: String?)
/// Build and run the current project, optionally in release mode.
case run(release: Bool)
/// Export a Synthesizer template to a `.swift` file.
/// When `overwrite` is `true`, an existing file at the destination is replaced.
case export(name: String, to: String?, overwrite: Bool)
/// Install Xcode file templates to the user template directory.
case installTemplates(force: Bool)
/// Remove Xcode file templates from the user template directory.
case uninstallTemplates
/// Print the help text.
case help
/// Print the lyrebird version.
case version
/// Exit the interactive shell.
case quit
/// Empty input — no-op.
case none
/// Unrecognised input.
case unknown(String)
}
/// The LineNoise-powered `lyrebird>` interactive command shell.
///
/// Launched when `lyrebird` is run with no subcommand. Provides:
/// - Arrow-key line editing (via LineNoise / linenoise C library)
/// - Persistent command history saved to `~/.lyrebird_history`
/// - Tab completion for all recognised subcommands
///
/// Typing `repl` builds the current package and hands off to `swift repl` (with
/// Lyrebird linked in via `-I`/`-L`/`-l` flags) for a full Swift REPL session.
/// Ctrl+D or `quit` exits.
public enum InteractiveShell {
/// The list of top-level subcommand names used for tab completion.
private static let subcommands: [String] = [
"new", "run", "export", "install-templates", "uninstall-templates",
"repl", "help", "version", "quit"
]
/// Maximum number of entries retained in the LineNoise history ring buffer.
private static let historyMaxLength: UInt = 500
/// Path to the history file shared with `REPLLauncher`.
public static var historyFilePath: String { REPLLauncher.historyFilePath }
/// Returns completions for the given line prefix (used by LineNoise tab completion).
public static func completions(for prefix: String) -> [String] {
subcommands.filter { $0.hasPrefix(prefix) }
}
/// Parses a raw input string (from `LineNoise.getLine`) into a `ShellCommand`.
public static func command(from input: String) -> ShellCommand {
let trimmed: String = input.trimmingCharacters(in: .whitespaces)
let tokens: [String] = trimmed.split(separator: " ", omittingEmptySubsequences: true)
.map(String.init)
// Lowercase only the verb so commands are case-insensitive, but argument values
// (e.g. class names like "MySynth") preserve the user's original casing.
switch tokens.first?.lowercased() ?? "" {
case "":
return .none
case "repl":
return .repl
case "help":
return .help
case "version":
return .version
case "quit", "exit", ":quit":
return .quit
case "new":
guard tokens.count >= 2 else {
return .unknown("new: missing <name>")
}
// If the positional argument looks like a flag, the user omitted the name.
guard !tokens[1].hasPrefix("-") else {
return .unknown("new: missing <name>")
}
let template: ProjectTemplate
if let tIdx: Array<String>.Index = tokens.firstIndex(of: "--template"),
tIdx + 1 < tokens.count,
let t: ProjectTemplate = ProjectTemplate(string: tokens[tIdx + 1]) {
template = t
} else {
template = .basic
}
let lyrebirdPath: String?
if let pIdx: Array<String>.Index = tokens.firstIndex(of: "--lyrebird-path"),
pIdx + 1 < tokens.count,
!tokens[pIdx + 1].hasPrefix("-") {
lyrebirdPath = tokens[pIdx + 1]
} else {
lyrebirdPath = nil
}
return .new(name: tokens[1],
template: template,
lyrebirdPath: lyrebirdPath)
case "run":
let release: Bool = tokens.contains("--release")
return .run(release: release)
case "install-templates":
let force: Bool = tokens.contains("--force")
return .installTemplates(force: force)
case "uninstall-templates":
return .uninstallTemplates
case "export":
guard tokens.count >= 2 else {
return .unknown("export: missing <name>")
}
let synthName: String = tokens[1]
// If the positional argument looks like a flag, the user omitted the name.
guard !synthName.hasPrefix("-") else {
return .unknown("export: missing <name>")
}
// Guard that the value following `--to` is not itself a flag token.
let toPath: String?
if let toIdx: Array<String>.Index = tokens.firstIndex(of: "--to"),
toIdx + 1 < tokens.count,
!tokens[toIdx + 1].hasPrefix("-") {
toPath = tokens[toIdx + 1]
} else {
toPath = nil
}
let overwrite: Bool = tokens.contains("--overwrite")
return .export(name: synthName, to: toPath, overwrite: overwrite)
default:
return .unknown(trimmed)
}
}
/// Runs the interactive shell loop until the user quits or hits Ctrl+D.
///
/// Uses LineNoise for line editing, history, and tab completion.
/// On `repl`, hands off to `REPLLauncher.launch()` and resumes the shell on return.
public static func run() {
let ln: LineNoise = LineNoise()
ln.setHistoryMaxLength(historyMaxLength)
try? ln.loadHistory(fromFile: historyFilePath)
ln.setCompletionCallback { currentLine in
completions(for: currentLine)
}
printHelp()
// Labeled loop so `.quit` can break directly without a redundant re-parse.
shellLoop: while true {
let input: String
do {
input = try ln.getLine(prompt: "lyrebird> ")
} catch LinenoiseError.CTRL_C, LinenoiseError.EOF {
// Ctrl+C or Ctrl+D — clean exit.
break shellLoop
} catch {
printError("lyrebird: input error: \(error)\n")
break shellLoop
}
ln.addHistory(input)
switch command(from: input) {
case .repl:
do {
try REPLLauncher.launch()
} catch CLIError.swiftNotFound {
printError("error: swift not found. Install Xcode or a Swift toolchain.\n")
} catch CLIError.buildFailed(let code) {
printError("error: swift build failed (exit code \(code)). REPL not started.\n")
} catch {
printError("error: \(error)\n")
}
case .new(let name, let template, let lyrebirdPath):
let resolvedPath: String? = lyrebirdPath.map {
URL(fileURLWithPath: $0).standardizedFileURL.path
}
do {
try ProjectScaffolder.scaffold(
name: name,
template: template,
lyrebirdPath: resolvedPath
)
print("Created \(name)/")
} catch ProjectScaffolder.Error.projectExists(let n) {
print("error: directory '\(n)' already exists.")
} catch ProjectScaffolder.Error.invalidName(let n) {
print("error: '\(n)' is not a valid Swift module name.")
} catch ProjectScaffolder.Error.fileSystemError(let path, let reason) {
print("error: could not create '\(path)': \(reason)")
} catch {
print("error: \(error)")
}
case .run(let release):
do {
try ProjectRunner.run(release: release)
} catch ProjectRunner.Error.swiftNotFound {
printError("error: swift not found. Install Xcode or a Swift toolchain.\n")
} catch ProjectRunner.Error.buildFailed(let code) {
print("Build failed (exit code \(code)).")
} catch {
print("error: \(error)")
}
case .export(let name, let toPath, let overwrite):
do {
try SynthExporter.export(name: name, to: toPath, overwrite: overwrite)
let dest: String = toPath ?? SynthExporter.defaultOutputPath(for: name)
print("Exported \(dest)")
} catch SynthExporter.Error.invalidName(let n) {
print("error: '\(n)' is not a valid Swift identifier.")
} catch SynthExporter.Error.fileExists(let p) {
print("error: '\(p)' already exists. Pass --overwrite to replace it.")
} catch SynthExporter.Error.fileSystemError(let p, let reason) {
print("error: could not write '\(p)': \(reason)")
} catch {
print("error: \(error)")
}
case .installTemplates(let force):
do {
let count: Int = try TemplateInstaller.install(force: force)
print("Installed \(count) Lyrebird Xcode templates → \(TemplateInstaller.destinationURL.path)")
} catch TemplateInstaller.Error.destinationExists(let path) {
print("error: '\(path)' already exists. Pass --force to replace it.")
} catch TemplateInstaller.Error.bundleMissingTemplates(let path) {
print("error: bundled templates not found at \(path).")
} catch TemplateInstaller.Error.fileSystemError(let p, let reason) {
print("error: could not write '\(p)': \(reason)")
} catch {
print("error: \(error)")
}
case .uninstallTemplates:
do {
let removed: Bool = try TemplateInstaller.uninstall()
if removed {
print("Removed Lyrebird templates from \(TemplateInstaller.destinationURL.path)")
} else {
print("Nothing to remove. Templates not installed at \(TemplateInstaller.destinationURL.path)")
}
} catch TemplateInstaller.Error.fileSystemError(let p, let reason) {
print("error: could not remove '\(p)': \(reason)")
} catch {
print("error: \(error)")
}
case .help:
printHelp()
case .version:
print("lyrebird \(lyrebirdVersion)")
case .quit:
break shellLoop
case .none:
continue shellLoop
case .unknown(let cmd):
print("unknown command '\(cmd)'. Type 'help' for options.")
}
}
try? ln.saveHistory(toFile: historyFilePath)
}
private static func printHelp() {
print("""
Commands:
new <name> [--template <t>] Scaffold a new Lyrebird Swift Package
Templates: quickstart (fastest sound), basic (default),
demo, ui-demo, nrt, score
run [--release] Build and run the current project
export <name> [--to p] Export a Synthesizer template to a .swift file
install-templates [--force] Install Xcode file templates to user dir
uninstall-templates Remove installed Xcode file templates
repl Launch Swift REPL with Lyrebird available
version Print lyrebird version
help Show this help
quit Exit (also Ctrl+D)
""")
}
}