OpenInTerminalButton

一个轻量级的 SwiftPM 包,提供了一个库和一个 SwiftUI 按钮,用于在 macOS 的 Terminal.app 或 iTerm2.app 中打开文件夹。

兼容性

由于显而易见的原因,这个包仅适用于 macOS。Apple Events 只能在带有临时异常的沙盒中使用,但即使你设法获得一个异常,该应用程序很可能无法通过 App Store 的审核流程

公共接口

用法

  1. 在你的 Package.swift 中添加依赖项
.package(url: "https://github.com/kukushechkin/OpenInTerminalButton", .upToNextMajor(from: "1.0.0"))
  1. 将 Apple Events 添加到你的应用程序的 Info.plist
<key>NSAppleEventsUsageDescription</key>
<string>Allow this app to open terminal app and execute commands.</string> 
  1. 使用 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,则会在现有窗口中打开一个新的标签页。

  1. 直接使用 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)")
}