欢迎使用 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、操作文件系统以及使用像 Marathon、CocoaPods 和 fastlane 这样的工具。
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
try shellOut(to: .runMarathonScript(at: "~/scripts/MyScript", arguments: ["One", "Two"]))
try shellOut(to: .updateMarathonPackages())
try shellOut(to: .createSwiftPackage(withType: .executable))
try shellOut(to: .updateSwiftPackages())
try shellOut(to: .generateSwiftPackageXcodeProject())
try shellOut(to: .buildSwiftPackage())
try shellOut(to: .testSwiftPackage())
try shellOut(to: .runFastlane(usingLane: "appstore"))
try shellOut(to: .updateCocoaPods())
try shellOut(to: .installCocoaPods())
在上面的列表中没有找到您想要的? 您可以使用 ShellOutCommand
轻松定义您自己的命令。如果您创建了一个您认为应该包含在内置命令中的命令,请随时打开一个 PR!
$ marathon add https://github.com/JohnSundell/ShellOut.git
将 ShellOut 添加到 Marathon。https://github.com/JohnSundell/ShellOut.git
添加到您的 Marathonfile
。$ marathon run yourScript.swift
运行它。.package(url: "https://github.com/JohnSundell/ShellOut.git", from: "2.0.0")
添加到您的 Package.swift
文件的 dependencies
中。$ swift package update
更新您的包。