Commandant 0.18.0

Commandant 0.18.0

Ben ChatelainSyo Ikedagiginet维护。



Commandant 0.18.0

  • Carthage贡献者

Commandant

Commandant是一个Swift框架,用于解析命令行参数,灵感来自Argo(它本身是由Haskell库Aeson启发的)。

Reviewed by Hound

示例

使用Commandant,一个命令及其相关的选项可以定义如下

struct LogCommand: CommandProtocol {
	typealias Options = LogOptions

	let verb = "log"
	let function = "Reads the log"

	func run(_ options: Options) -> Result<(), YourErrorType> {
		// Use the parsed options to do something interesting here.
		return ()
	}
}

struct LogOptions: OptionsProtocol {
	let lines: Int
	let verbose: Bool
	let logName: String

	static func create(_ lines: Int) -> (Bool) -> (String) -> LogOptions {
		return { verbose in { logName in LogOptions(lines: lines, verbose: verbose, logName: logName) } }
	}

	static func evaluate(_ m: CommandMode) -> Result<LogOptions, CommandantError<YourErrorType>> {
		return create
			<*> m <| Option(key: "lines", defaultValue: 0, usage: "the number of lines to read from the logs")
			<*> m <| Option(key: "verbose", defaultValue: false, usage: "show verbose output")
			<*> m <| Argument(usage: "the log to read")
	}
}

然后,将每个可用的命令添加到注册表中

let commands = CommandRegistry<YourErrorType>()
commands.register(LogCommand())
commands.register(VersionCommand())

之后,通过简单调用注册表即可解析参数

var arguments = CommandLine.arguments

// Remove the executable name.
assert(!arguments.isEmpty)
arguments.remove(at: 0)

if let verb = arguments.first {
	// Remove the command name.
	arguments.remove(at: 0)

	if let result = commands.run(command: verb, arguments: arguments) {
		// Handle success or failure.
	} else {
		// Unrecognized command.
	}
} else {
	// No command given.
}

有关实际应用的示例,请参考Carthage命令行工具的实现。

许可证

Commandant遵循MIT许可证