forked from apple/swift-argument-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.swift
246 lines (201 loc) · 7.95 KB
/
main.swift
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
//===----------------------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Argument Parser open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import ArgumentParser
struct Math: ParsableCommand {
// Customize your command's help and subcommands by implementing the
// `configuration` property.
static var configuration = CommandConfiguration(
// Optional abstracts and discussions are used for help output.
abstract: "A utility for performing maths.",
// Commands can define a version for automatic '--version' support.
version: "1.0.0",
// Pass an array to `subcommands` to set up a nested tree of subcommands.
// With language support for type-level introspection, this could be
// provided by automatically finding nested `ParsableCommand` types.
subcommands: [Add.self, Multiply.self, Statistics.self],
// A default subcommand, when provided, is automatically selected if a
// subcommand is not given on the command line.
defaultSubcommand: Add.self)
}
struct Options: ParsableArguments {
@Flag(name: [.customLong("hex-output"), .customShort("x")],
help: "Use hexadecimal notation for the result.")
var hexadecimalOutput = false
@Argument(
help: "A group of integers to operate on.")
var values: [Int] = []
}
extension Math {
static func format(_ result: Int, usingHex: Bool) -> String {
usingHex ? String(result, radix: 16)
: String(result)
}
struct Add: ParsableCommand {
static var configuration =
CommandConfiguration(abstract: "Print the sum of the values.")
// The `@OptionGroup` attribute includes the flags, options, and
// arguments defined by another `ParsableArguments` type.
@OptionGroup var options: Options
mutating func run() {
let result = options.values.reduce(0, +)
print(format(result, usingHex: options.hexadecimalOutput))
}
}
struct Multiply: ParsableCommand {
static var configuration =
CommandConfiguration(abstract: "Print the product of the values.")
@OptionGroup var options: Options
mutating func run() {
let result = options.values.reduce(1, *)
print(format(result, usingHex: options.hexadecimalOutput))
}
}
}
// In practice, these nested types could be broken out into different files.
extension Math {
struct Statistics: ParsableCommand {
static var configuration = CommandConfiguration(
// Command names are automatically generated from the type name
// by default; you can specify an override here.
commandName: "stats",
abstract: "Calculate descriptive statistics.",
subcommands: [Average.self, StandardDeviation.self, Quantiles.self])
}
}
extension Math.Statistics {
struct Average: ParsableCommand {
static var configuration = CommandConfiguration(
abstract: "Print the average of the values.",
version: "1.5.0-alpha")
enum Kind: String, ExpressibleByArgument, CaseIterable {
case mean, median, mode
}
@Option(help: "The kind of average to provide.")
var kind: Kind = .mean
@Argument(help: "A group of floating-point values to operate on.")
var values: [Double] = []
func validate() throws {
if (kind == .median || kind == .mode) && values.isEmpty {
throw ValidationError("Please provide at least one value to calculate the \(kind).")
}
}
func calculateMean() -> Double {
guard !values.isEmpty else {
return 0
}
let sum = values.reduce(0, +)
return sum / Double(values.count)
}
func calculateMedian() -> Double {
guard !values.isEmpty else {
return 0
}
let sorted = values.sorted()
let mid = sorted.count / 2
if sorted.count.isMultiple(of: 2) {
return (sorted[mid - 1] + sorted[mid]) / 2
} else {
return sorted[mid]
}
}
func calculateMode() -> [Double] {
guard !values.isEmpty else {
return []
}
let grouped = Dictionary(grouping: values, by: { $0 })
let highestFrequency = grouped.lazy.map { $0.value.count }.max()!
return grouped.filter { _, v in v.count == highestFrequency }
.map { k, _ in k }
}
mutating func run() {
switch kind {
case .mean:
print(calculateMean())
case .median:
print(calculateMedian())
case .mode:
let result = calculateMode()
.map(String.init(describing:))
.joined(separator: " ")
print(result)
}
}
}
struct StandardDeviation: ParsableCommand {
static var configuration = CommandConfiguration(
commandName: "stdev",
abstract: "Print the standard deviation of the values.")
@Argument(help: "A group of floating-point values to operate on.")
var values: [Double] = []
mutating func run() {
if values.isEmpty {
print(0.0)
} else {
let sum = values.reduce(0, +)
let mean = sum / Double(values.count)
let squaredErrors = values
.map { $0 - mean }
.map { $0 * $0 }
let variance = squaredErrors.reduce(0, +)
let result = variance.squareRoot()
print(result)
}
}
}
struct Quantiles: ParsableCommand {
static var configuration = CommandConfiguration(
abstract: "Print the quantiles of the values (TBD).")
@Argument(completion: .list(["alphabet", "alligator", "branch", "braggart"]))
var oneOfFour: String?
@Argument(completion: .custom { _ in ["alabaster", "breakfast", "crunch", "crash"] })
var customArg: String?
@Argument(help: "A group of floating-point values to operate on.")
var values: [Double] = []
// These args and the validation method are for testing exit codes:
@Flag(help: .hidden)
var testSuccessExitCode = false
@Flag(help: .hidden)
var testFailureExitCode = false
@Flag(help: .hidden)
var testValidationExitCode = false
@Option(help: .hidden)
var testCustomExitCode: Int32?
// These args are for testing custom completion scripts:
@Option(completion: .file(extensions: ["txt", "md"]))
var file: String?
@Option(completion: .directory)
var directory: String?
@Option(completion: .shellCommand("head -100 /usr/share/dict/words | tail -50"))
var shell: String?
@Option(completion: .custom(customCompletion))
var custom: String?
func validate() throws {
if testSuccessExitCode {
throw ExitCode.success
}
if testFailureExitCode {
throw ExitCode.failure
}
if testValidationExitCode {
throw ExitCode.validationFailure
}
if let exitCode = testCustomExitCode {
throw ExitCode(exitCode)
}
}
}
}
func customCompletion(_ s: [String]) -> [String] {
return (s.last ?? "").starts(with: "a")
? ["aardvark", "aaaaalbert"]
: ["hello", "helicopter", "heliotrope"]
}
Math.main()