🐚 ShellOut

欢迎使用 ShellOut,一个简单的包,使您能够轻松地从 Swift 脚本或命令行工具中“调用 shell”。

即使您可以使用原生 Swift 代码完成您需要的大部分任务,有时您仍然需要从脚本或工具中调用命令行,而这正是 ShellOut 让其变得如此简单的原因。

用法

只需调用 shellOut(),并指定您想要运行的命令,以及您想要传递的任何参数

let output = try shellOut(to: "echo", arguments: ["Hello world"])
print(output) // Hello world

您还可以一次轻松运行一系列命令,可以选择在给定的路径下运行

try shellOut(to: ["mkdir NewFolder", "echo \"Hello again\" > NewFolder/File"], at: "~/CurrentFolder")
let output = try shellOut(to: "cat File", at: "~/CurrentFolder/NewFolder")
print(output) // Hello again

如果发生错误,ShellOut 将自动读取 STDERR 并将其很好地格式化为类型化的 Swift 错误

do {
    try shellOut(to: "totally-invalid")
} catch {
    let error = error as! ShellOutError
    print(error.message) // Prints STDERR
    print(error.output) // Prints STDOUT
}

预定义命令

使用 ShellOut 的另一种方法是执行预定义的命令,使您能够轻松地执行常见的任务,而无需使用字符串构建命令。它还附带一组这样的预定义命令,用于常见的任务,例如使用 Git、操作文件系统以及使用像 MarathonCocoaPodsfastlane 这样的工具。

使用 Git

try shellOut(to: .gitInit())
try shellOut(to: .gitClone(url: repositoryURL))
try shellOut(to: .gitCommit(message: "A scripted commit!"))
try shellOut(to: .gitPush())
try shellOut(to: .gitPull(remote: "origin", branch: "release"))
try shellOut(to: .gitSubmoduleUpdate())
try shellOut(to: .gitCheckout(branch: "my-feature"))

处理文件、文件夹和符号链接

try shellOut(to: .createFolder(named: "folder"))
try shellOut(to: .createFile(named: "file", contents: "Hello world"))
try shellOut(to: .moveFile(from: "path/a", to: "path/b"))
try shellOut(to: .copyFile(from: "path/a", to: "path/b"))
try shellOut(to: .openFile(at: "Project.xcodeproj"))
try shellOut(to: .readFile(at: "Podfile"))
try shellOut(to: .removeFile(from: "path/a"))
try shellOut(to: .createSymlink(to: "target", at: "link"))
try shellOut(to: .expandSymlink(at: "link"))

对于一种更强大和面向对象的方式来处理 Swift 中的文件和文件夹,请查看 Files

使用 Marathon

try shellOut(to: .runMarathonScript(at: "~/scripts/MyScript", arguments: ["One", "Two"]))
try shellOut(to: .updateMarathonPackages())

使用 Swift 包管理器

try shellOut(to: .createSwiftPackage(withType: .executable))
try shellOut(to: .updateSwiftPackages())
try shellOut(to: .generateSwiftPackageXcodeProject())
try shellOut(to: .buildSwiftPackage())
try shellOut(to: .testSwiftPackage())

使用 fastlane

try shellOut(to: .runFastlane(usingLane: "appstore"))

使用 CocoaPods

try shellOut(to: .updateCocoaPods())
try shellOut(to: .installCocoaPods())

在上面的列表中没有找到您想要的? 您可以使用 ShellOutCommand 轻松定义您自己的命令。如果您创建了一个您认为应该包含在内置命令中的命令,请随时打开一个 PR

安装

对于脚本

对于命令行工具

帮助、反馈或建议?