Skip to content

Commit 37355c4

Browse files
committed
Replace runMain with mainBody
runMain was error-prone, as it encouraged construction of args object outside of try-catch block.
1 parent ea6a2e2 commit 37355c4

File tree

2 files changed

+14
-10
lines changed

2 files changed

+14
-10
lines changed

README.md

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -186,14 +186,19 @@ throw a `SystemExitException` when parsing fails.
186186
Additional post-parsing validation can be performed on a delegate using
187187
`addValidator`.
188188

189-
As a convenience, these exceptions can be handled by using the `runMain`
190-
extension function:
189+
As a convenience, these exceptions can be handled by using the `mainBody`
190+
function:
191191

192192
```kotlin
193-
fun main(args: Array<String>) =
194-
MyArgs(ArgParser(args)).runMain(PROGRAM_NAME) {
193+
class ParsedArgs(parser: ArgParser) {
194+
val name by positional("The user's name").default("world")
195+
}
196+
197+
fun main(args: Array<String>) = mainBody("hello") {
198+
ParsedArgs(ArgParser(args)).run {
195199
println("Hello, {name}!")
196200
}
201+
}
197202
```
198203

199204
Note that parsing does not take place until at least one delegate is read, or

src/main/kotlin/SystemExitException.kt

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -57,19 +57,18 @@ open class SystemExitException(message: String, val returnCode: Int) : Exception
5757
}
5858

5959
/**
60-
* Like [kotlin.run], but calls [SystemExitException.printAndExit] on any
61-
* `SystemExitException` that is caught.
60+
* Calls [SystemExitException.printAndExit] on any `SystemExitException` that
61+
* is caught.
6262
*
6363
* @param progName the name of the program, or null if not known
6464
* @param columns the number of columns to wrap any caught
6565
* `SystemExitException` to. Specify null for reasonable defaults, or 0 to not
6666
* wrap at all.
67-
* @param f the main body. If a `SystemExitException` is caught its
68-
* `printAndExit` method will be invoked.
67+
* @param body the code that may throw a `SystemExitException`
6968
*/
70-
fun <T, R> T.runMain(progName: String? = null, columns: Int? = null, f: T.() -> R): R {
69+
fun <R> mainBody(progName: String? = null, columns: Int? = null, body: () -> R): R {
7170
try {
72-
return f()
71+
return body()
7372
} catch (e: SystemExitException) {
7473
e.printAndExit(progName, columns ?: System.getenv("COLUMNS")?.toInt() ?: 80)
7574
}

0 commit comments

Comments
 (0)