首先,声明一个类型来定义你需要从命令行收集的信息。使用 ArgumentParser
的属性包装器装饰每个存储的属性,然后声明遵循 ParsableCommand
并添加 @main
属性。(注意,对于 run
的 async
版本,应该遵循 AsyncParsableCommand
而不是 ParsableCommand
。)最后,在 run()
方法中实现你的命令逻辑。
import ArgumentParser
@main
struct Repeat: ParsableCommand {
@Flag(help: "Include a counter with each repetition.")
var includeCounter = false
@Option(name: .shortAndLong, help: "The number of times to repeat 'phrase'.")
var count: Int? = nil
@Argument(help: "The phrase to repeat.")
var phrase: String
mutating func run() throws {
let repeatCount = count ?? 2
for i in 1...repeatCount {
if includeCounter {
print("\(i): \(phrase)")
} else {
print(phrase)
}
}
}
}
ArgumentParser
库会解析命令行参数,实例化你的命令类型,然后执行你的 run()
方法或退出并显示有用的消息。
ArgumentParser
使用你的属性名称和类型信息,以及你使用属性包装器提供的详细信息,来提供有用的错误消息和详细的帮助信息。
$ repeat hello --count 3
hello
hello
hello
$ repeat --count 3
Error: Missing expected argument 'phrase'.
Help: <phrase> The phrase to repeat.
Usage: repeat [--count <count>] [--include-counter] <phrase>
See 'repeat --help' for more information.
$ repeat --help
USAGE: repeat [--count <count>] [--include-counter] <phrase>
ARGUMENTS:
<phrase> The phrase to repeat.
OPTIONS:
--include-counter Include a counter with each repetition.
-c, --count <count> The number of times to repeat 'phrase'.
-h, --help Show help for this command.
有关指南、文章和 API 文档,请参阅 Web 上的库文档 或 Xcode。
此存储库包含一些使用该库的示例。
repeat
是上面显示的示例。roll
是一个简单的实用程序,实现为一个直线脚本。math
是一个使用嵌套命令和子命令的带注释的示例。count-lines
在其实现中使用 async
/await
代码。你还可以查看 Swift 项目工具中采用 ArgumentParser
的示例
swift-format
使用了一些高级功能,例如自定义选项值和隐藏标志。swift-package-manager
包括一个深层的命令层次结构和对选项组的广泛使用。Swift Argument Parser 包是源代码稳定的;版本号遵循语义化版本控制。对公共 API 的源代码破坏性更改只能出现在新的主要版本中。
swift-argument-parser
包 1.0.0 版本的公共 API 由 ArgumentParser
模块中标记为 public 的非下划线声明组成。不属于公共 API 的接口可能会在任何版本中继续更改,包括自动生成的帮助和错误消息的确切措辞和格式,以及包的示例、测试、实用程序和文档。
未来该软件包的次要版本可能会根据需要对这些规则进行更改。
我们希望该软件包能够快速采用与其任务相关的 Swift 语言和工具链的改进。 因此,我们预计该软件包的新版本会不时要求客户端升级到更新的 Swift 工具链版本。 需要新的 Swift 版本只会需要次要版本升级。
要在 SwiftPM 项目中使用 ArgumentParser
库,请将其添加到你的软件包和命令行可执行目标文件的依赖项中。
let package = Package(
// name, platforms, products, etc.
dependencies: [
// other dependencies
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.3.0"),
],
targets: [
.executableTarget(name: "<command-line-tool>", dependencies: [
// other dependencies
.product(name: "ArgumentParser", package: "swift-argument-parser"),
]),
// other targets
]
)
swift-argument-parser 版本支持的最低 Swift 版本详述如下
swift-argument-parser | 最低 Swift 版本 |
---|---|
0.0.1 ..< 0.2.0 |
5.1 |
0.2.0 ..< 1.1.0 |
5.2 |
1.1.0 ..< 1.3.0 |
5.5 |
1.3.0 ... |
5.7 |