Sitelet https://github.com/twitter/util/commit/cf7860e5c2037a496b596e1688bf5873875e3018
Skip to content

Commit cf7860e

Browse files
cacocojenkins
authored andcommitted
util-app: Allow argument parsing to be overridable
Summary: Problem It is not currently possible to override the argument parsing behavior executed in `c.t.app.App#nonExitingMain` which always attempts to parse flags from the given command line input. Solution By request, allow for the argument parsing to be overridden by creating a protected function: `parseArgs(args: Array[String])` which users can override to customize the behavior therein. Result Users can define how to do argument parsing. From: #210 Differential Revision: https://phabricator.twitter.biz/D181660
1 parent 57533b3 commit cf7860e

2 files changed

Lines changed: 25 additions & 8 deletions

File tree

‎CHANGES‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ Unreleased
88

99
API Changes:
1010

11+
* util-app: Allow users a way to override the argument parsing behavior in
12+
`c.t.app.App#nonExitingMain` which was inlined. Users can override `parseArgs`
13+
to define custom behavior. ``PHAB_ID=D181660``
14+
1115
* util-core: Removed `c.t.u.NonFatal`, use `scala.util.control.NonFatal`
1216
instead. ``PHAB_ID=D181918``
1317

‎util-app/src/main/scala/com/twitter/app/App.scala‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,26 @@ trait App extends Closable with CloseAwaitably {
158158
*/
159159
protected[this] def loadServiceBindings: Seq[LoadService.Binding[_]] = Nil
160160

161+
/**
162+
* Parse the command line arguments as an Array of Strings. The default
163+
* implementation parses the given String[] as [[Flag]] input values.
164+
*
165+
* Users may override this method to specify different functionality.
166+
*
167+
* @param args String Array which represents the command line input given
168+
* to the application.
169+
*/
170+
protected[this] def parseArgs(args: Array[String]): Unit = {
171+
flag.parseArgs(args, allowUndefinedFlags) match {
172+
case Flags.Ok(remainder) =>
173+
_args = remainder.toArray
174+
case Flags.Help(usage) =>
175+
throw FlagUsageError(usage)
176+
case Flags.Error(reason) =>
177+
throw FlagParseException(reason)
178+
}
179+
}
180+
161181
/**
162182
* Invoke `f` before anything else (including flag parsing).
163183
*/
@@ -330,14 +350,7 @@ trait App extends Closable with CloseAwaitably {
330350

331351
for (f <- inits) f()
332352

333-
flag.parseArgs(args, allowUndefinedFlags) match {
334-
case Flags.Ok(remainder) =>
335-
_args = remainder.toArray
336-
case Flags.Help(usage) =>
337-
throw FlagUsageError(usage)
338-
case Flags.Error(reason) =>
339-
throw FlagParseException(reason)
340-
}
353+
parseArgs(args)
341354

342355
for (f <- premains) f()
343356

0 commit comments

Comments
 (0)