ArgumentParserKit 1.0.0

ArgumentParserKit 1.0.0

Christian Elies 维护。



  • Apple Inc. 和 Swift 项目作者

ArgumentParserKit

为 macOS 命令行工具安全解析命令行参数的简单方法

Version Swift4 Platform License

ArgumentParser 默认支持 --help-h 参数。它将打印出您的命令行工具使用的精美概述。

👻  Welcome to this awesome Command Line Tool  😊
OVERVIEW: Does amazing things for you

USAGE: CommandLineTool <options>

OPTIONS:
  --name, -n        A name
  --help, -h        Display available options

示例

do {
    // The first argument is always the executable, drop it
    let arguments = Array(CommandLine.arguments.dropFirst())

    let parser = ArgumentParser(usage: "<options>", overview: "A description")
    let nameOption = parser.add(option: "--name", shortName: "-n", kind: String.self, usage: "A name")

    let parsedArguments = try parser.parse(arguments)
    let name = parsedArguments.get(nameOption)
    print(name)
} catch {
    // handle parsing error
}

如何使用

如果您使用 ArgumentParser,解析参数值只需四个步骤。

1. 创建一个解析器

使用 ArgumentParser 类的初始化器。

/// Create an argument parser.
///
/// - Parameters:
///   - commandName: If provided, this will be substitued in "usage" line of the generated usage text.
///   Otherwise, first command line argument will be used.
///   - usage: The "usage" line of the generated usage text.
///   - overview: The "overview" line of the generated usage text.
///   - seeAlso: The "see also" line of generated usage text.
///
init(commandName: String? = nil, usage: String, overview: String, seeAlso: String? = nil)

2. 告诉解析器要解析的参数

使用 add 方法告诉解析器您的命令行工具提供的参数(对于 ArgumentParser,参数是 OptionArgument 的实例)。

/// Add an argument to a parser.
///
/// - Parameters:
///   - option: The name of the argument, for example "--name".
///   - shortName: The shortened name of the argument, e.g. "-n".
///   - kind: The concrete type of the argument.
///   - usage: The description of the argument.
///
func add<T: ArgumentKind>(option: String, shortName: String? = nil, kind: T.Type, usage: String? = nil)

3. 实现对传递给命令行工具的参数的解析

将您的参数数组传递给解析实例的 parse 方法。

/// Parses the provided array and returns the result.
///
func parse(_ arguments: [String] = []) throws -> Result

4. 获取传递参数的值

在解析后,您可以通过在由 ArgumentParserparse 方法返回的 Result 类型上调用 get 方法来访问参数值。只需将 ArgumentParseradd 方法返回的 OptionArgument 传递进去即可。

/// Get an option argument's value from the results.
///
/// Since the options are optional, their result may or may not be present.
///
func get<T>(_ argument: OptionArgument<T>) -> T?

要求

部署目标版本需大于等于10.10。

安装

ArgumentParserKit 可通过 CocoaPods 获取。要安装它,只需将以下行添加到您的 Podfile 中

pod 'ArgumentParserKit'

其他资源

请参阅 使用 Swift Package Manager 内部的 ArgumentParser 解析命令行参数

作者

Apple Inc. 和 Swift 项目作者

许可

ArgumentParserKit 在 Apache License v2.0 运行库特例下可用。有关更多信息,请参阅 LICENSE 文件。