-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathOpt.scala
246 lines (216 loc) · 7.99 KB
/
Opt.scala
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
package com.concurrentthought.cla
import scala.util.{Try, Success, Failure}
/**
* Abstraction or a command-line option, with or without a corresponding value.
* It has the following fields:
* <ol>
* <li>`name` - serve as a lookup key for retrieving the value.</li>
* <li>`flags` - the arguments that invoke the option, e.g., `-h` and `--help`.</li>
* <li>`help` - a message displayed for command-line help.</li>
* <li>`default` - an optional default value, for when the user doesn't specify the option.</li>
* <li>`parser` - An implementation feature for parsing arguments.</li>
* </ol>
*/
sealed trait Opt[V] {
val name: String
val flags: Seq[String]
val help: String
val default: Option[V]
val parser: Opt.Parser[V]
require (name.length != 0, "The Opt name can't be empty.")
}
object Opt {
/**
* Each option attempts to parse one or more tokens in the argument list.
* If successful, it returns the option's name and extracted value as a tuple,
* along with the rest of the arguments.
*/
type Parser[V] = PartialFunction[Seq[String], ((String, Try[V]), Seq[String])]
/**
* Lift `String => V` to `String => Try[V]`.
*/
def toTry[V](to: String => V): String => Try[V] = s => Try(to(s))
/**
* Lift `String => V` to `String => Seq[V]`.
*/
def toSeq[V](to: String => V): String => Seq[V] = s => Vector(to(s))
/**
* Exception raised when an invalid value string is given. Not all errors
* are detected and reported this way. For example, calls to `s.toInt` for
* an invalid string will result in `NumberFormatException`.
*/
case class InvalidValueString(
flag: String, valueMessage: String, cause: Option[Throwable] = None)
extends RuntimeException(s"$valueMessage for option $flag",
if (cause == None) null else cause.get) {
/** Override toString to show a nicer name for the exception than the FQN. */
override def toString = {
val causeStr = if (cause == None) "" else s" (cause: ${cause.get})"
"Invalid value string: " + getMessage + causeStr
}
}
/**
* Construct an option that takes a value. For an option that doesn't
* take a value, see `Flag`.
*/
def apply[V](
name: String,
flags: Seq[String],
default: Option[V] = None,
help: String = "")(fromString: String => Try[V]) =
OptWithValue[V](name, flags, default, help)(fromString)
// Helper methods to create options.
/** Create a String option */
def string(
name: String,
flags: Seq[String],
default: Option[String] = None,
help: String = "") =
apply(name, flags, default, help)(toTry(identity))
/** Create a Byte option. */
def byte(
name: String,
flags: Seq[String],
default: Option[Byte] = None,
help: String = "") =
apply(name, flags, default, help)(toTry(_.toByte))
/** Create a Char option. Just takes the first character in the value string. */
def char(
name: String,
flags: Seq[String],
default: Option[Char] = None,
help: String = "") =
apply(name, flags, default, help)(toTry(_(0)))
/** Create an Int option. */
def int(
name: String,
flags: Seq[String],
default: Option[Int] = None,
help: String = "") =
apply(name, flags, default, help)(toTry(_.toInt))
/** Create a Long option. */
def long(
name: String,
flags: Seq[String],
default: Option[Long] = None,
help: String = "") =
apply(name, flags, default, help)(toTry(_.toLong))
/** Create a Float option. */
def float(
name: String,
flags: Seq[String],
default: Option[Float] = None,
help: String = "") =
apply(name, flags, default, help)(toTry(_.toFloat))
/** Create a Double option. */
def double(
name: String,
flags: Seq[String],
default: Option[Double] = None,
help: String = "") =
apply(name, flags, default, help)(toTry(_.toDouble))
/**
* Create an option where the value string represents a sequence with a delimiter.
* The delimiter string is treated as a regex. For matching on several possible
* delimiter characters, use "[;-_]", for example. The resulting substrings won't
* be trimmed of whitespace, in case you want it, but you can also remove any
* internal whitespace (i.e., not at the beginning or end of the input string),
* e.g., "\\s*[;-_]\\s*". The delimiter is given as a separate argument list so
* that the list of common Opt arguments is consistent with the other helper
* methods.
*/
def seq[V](delimsRE: String)(
name: String,
flags: Seq[String],
default: Option[Seq[V]] = None,
help: String = "")(fromString: String => Try[V]) = {
require (delimsRE.trim.length > 0, "The delimiters RE string can't be empty.")
apply(name, flags, default, help) {
s => seqSupport(name, s, delimsRE, fromString)
}
}
/**
* A helper method when the substrings are returned without further processing required.
*/
def seqString(delimsRE: String)(
name: String,
flags: Seq[String],
default: Option[Seq[String]] = None,
help: String = "") =
seq[String](delimsRE)(name, flags, default, help)(toTry(_.toString))
/**
* A helper method for path-like structures, where the default delimiter
* for the platform is used, e.g., ':' for *nix systems and ';' for Windows.
*/
def path(
name: String,
flags: Seq[String],
default: Option[Seq[String]] = None,
help: String = "List of file system paths") =
seqString(sys.props.getOrElse("path.separator",":"))(
name, flags, default, help)
private def seqSupport[V](name: String, str: String, delimsRE: String,
fromString: String => Try[V]): Try[Seq[V]] = {
def f(strs: Seq[String], vect: Vector[V]): Try[Vector[V]] = strs match {
case head +: tail => fromString(head) match {
case Success(value) => f(tail, vect :+ value)
case Failure(ex) => Failure(ex)
}
case Nil => Success(vect)
}
f(str.split(delimsRE), Vector.empty[V])
}
}
/**
* A command line argument where an explicit value should follow.
* In addition to the fields in `Opt`, this type adds the following:
* <ol>
* <li>`fromString: String => V` - convert the found value from a String to the correct type.</li>
* </ol>
*/
case class OptWithValue[V] (
name: String,
flags: Seq[String],
default: Option[V] = None,
help: String = "")(fromString: String => Try[V]) extends Opt[V] {
protected val opteqRE = "^([^=]+)=(.*)$".r
val parser: Opt.Parser[V] = {
case opteqRE(flag, value) +: tail if flags.contains(flag) => parserHelper(flag, value, tail)
case flag +: value +: tail if flags.contains(flag) => parserHelper(flag, value, tail)
}
protected def parserHelper(flag: String, value: String, tail: Seq[String]) = fromString(value) match {
case sv @ Success(v) => ((name, sv), tail)
case Failure(ex) => ex match {
case ivs: Opt.InvalidValueString => ((name, Failure(ivs)), tail)
case ex => ((name, Failure(Opt.InvalidValueString(flag, value, Some(ex)))), tail)
}
}
}
/**
* An option that is just a flag, with no value. By default, its presence
* indicates "true" for the corresponding option and if the flag isn't specified
* by the user, then "false" is indicated. However, you can construct a `Flag`
* with the sense "flipped" using `Flag.reverseSense()`.
*/
case class Flag (
name: String,
flags: Seq[String],
help: String = "") extends Opt[Boolean] {
val default = Some(false)
val parser: Opt.Parser[Boolean] = {
case flag +: tail if flags.contains(flag) => ((name, Try(!default.get)), tail)
}
}
/** Companion object for `Flag`. */
object Flag {
/**
* Like `apply`, but the value is "flipped"; it defaults to `true`, but if the
* user supplies the flag, the value is `false`.
*/
def reverseSense(
name: String,
flags: Seq[String],
help: String = "") = new Flag(name, flags, help) {
override val default = Some(true)
}
}