一个轻量级的 SwiftPM 包,提供了一个库和一个 SwiftUI 按钮,用于在 macOS 的 Terminal.app 或 iTerm2.app 中打开文件夹。
由于显而易见的原因,这个包仅适用于 macOS。Apple Events 只能在带有临时异常的沙盒中使用,但即使你设法获得一个异常,该应用程序很可能无法通过 App Store 的审核流程。
struct OpenInTerminalButton: View
- 一个 SwiftUI 按钮,用于在 Terminal.app 或 iTerm2.app 中打开当前 Finder 窗口。struct BorderlessButton: View
- 一个没有边框和背景的 SwiftUI 按钮。enum OpenInTerminalError
— 可能的错误枚举。enum SupportedTerminal
— 可能的终端应用程序枚举。func openInTerminal(location: URL, commands: [String]?) async throws -> Result<SupportedTerminal, OpenInTerminalError>
— 一个函数,用于在 Terminal.app 或 iTerm2.app 中打开指定位置,并运行指定的命令。Package.swift
中添加依赖项.package(url: "https://github.com/kukushechkin/OpenInTerminalButton", .upToNextMajor(from: "1.0.0"))
Info.plist
中<key>NSAppleEventsUsageDescription</key>
<string>Allow this app to open terminal app and execute commands.</string>
OpenInTerminalButton
视图import SwiftUI
import OpenInTerminalButton
struct ContentView: View {
var body: some View {
OpenInTerminalButton(
location: URL(fileURLWithPath: "~/Desktop"),
commands: [
"echo 'Hello, world!'",
"ls -la"
]
)
}
}
点击按钮后,会打开一个新的 iTerm2.app (如果已安装) 或 Terminal 窗口,并执行指定的命令。 如果你在 iTerm2.app 中使用 Hotkey Window,则会在现有窗口中打开一个新的标签页。
openInTerminal(location:commands:)
函数,例如,如果你想创建一个自定义按钮import OpenInTerminalButton
let result = openInTerminal(location: URL(fileURLWithPath: "~/Desktop"), commands: ["echo 'Hello, world!'"])
switch result {
case .success(let terminal):
print("Opened in \(terminal)")
case .failure(let error):
print("Error: \(error)")
}