-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathHelpCommand.swift
More file actions
78 lines (63 loc) · 2.19 KB
/
HelpCommand.swift
File metadata and controls
78 lines (63 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//
// HelpCommand.swift
// Commandant
//
// Created by Justin Spahr-Summers on 2014-10-10.
// Copyright (c) 2014 Carthage. All rights reserved.
//
import Foundation
/// A basic implementation of a `help` command, using information available in a
/// `CommandRegistry`.
///
/// If you want to use this command, initialize it with the registry, then add
/// it to that same registry:
///
/// let commands: CommandRegistry<MyErrorType> = …
/// let helpCommand = HelpCommand(registry: commands)
/// commands.register(helpCommand)
public struct HelpCommand<ClientError: Error>: CommandProtocol {
public typealias Options = HelpOptions<ClientError>
public let verb = "help"
public let aliases: [String] = []
public let function: String
private let registry: CommandRegistry<ClientError>
/// Initializes the command to provide help from the given registry of
/// commands.
public init(registry: CommandRegistry<ClientError>, function: String? = nil) {
self.registry = registry
self.function = function ?? "Display general or command-specific help"
}
public func run(_ options: Options) -> Result<(), ClientError> {
if let verb = options.verb {
if let command = self.registry[verb] {
print(command.function)
if let usageError = command.usage() {
print("\n\(usageError)")
}
return .success(())
} else {
fputs("Unrecognized command: '\(verb)'\n", stderr)
}
}
print("Available commands:\n")
let maxVerbLength = self.registry.commands.map { $0.verb.count }.max() ?? 0
for command in self.registry.commands {
let padding = repeatElement(Character(" "), count: maxVerbLength - command.verb.count)
print(" \(command.verb)\(String(padding)) \(command.function)")
}
return .success(())
}
}
public struct HelpOptions<ClientError: Error>: OptionsProtocol {
fileprivate let verb: String?
private init(verb: String?) {
self.verb = verb
}
private static func create(_ verb: String) -> HelpOptions {
return self.init(verb: (verb == "" ? nil : verb))
}
public static func evaluate(_ m: CommandMode) -> Result<HelpOptions, CommandantError<ClientError>> {
return create
<*> m <| Argument(defaultValue: "", usage: "the command to display help for")
}
}