Skip to content

Commit

Permalink
Expose command: Command in CommandIOApp
Browse files Browse the repository at this point in the history
If you want to show the help when handling errors in the `IO` part of
the app, you need to call `.showHelp` on the command instance.
This is not possible with `CommandIOApp` since it doesn't expose the
app but creates and uses it on the fly.
This PR adds a `val command: Command[IO[ExitCode]]` to `CommandIOApp`
so you can have similar errors to the errors printed by `validate` but
when handling IO errors in the app with `.handleErrorWith` in the
application logic
  • Loading branch information
lolgab committed May 29, 2024
1 parent 24b2f9b commit 06578d6
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,18 @@ class CommandIOAppSpec extends AnyFlatSpec with Matchers {
runApp() shouldBe ExitCode.Error
}

it should "expose command so showHelp can be called" in {
PureHelloWorld.command.showHelp shouldBe """Usage: pure-hello <to-greet>
|
|Pure Hello World with Decline
|
|Options and flags:
| --help
| Display this help text.
| --version, -v
| Print the version number and exit.""".stripMargin
}

private[this] def runApp(args: String*): ExitCode =
PureHelloWorld.run(args.toList).unsafeRunSync()(IORuntime.global)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,17 @@ abstract class CommandIOApp(

def main: Opts[IO[ExitCode]]

val command: Command[IO[ExitCode]] =
CommandIOApp.createCommand(
name = name,
header = header,
helpFlag = helpFlag,
version = Option(version).filter(_.nonEmpty),
main
)

override final def run(args: List[String]): IO[ExitCode] =
CommandIOApp
.run[IO](name, header, helpFlag, Option(version).filter(_.nonEmpty))(main, args)
CommandIOApp.run[IO](command, args)

}

Expand Down Expand Up @@ -54,6 +62,14 @@ object CommandIOApp {
else ExitCode.Success
}

private[CommandIOApp] def createCommand(
name: String,
header: String,
helpFlag: Boolean,
version: Option[String],
opts: Opts[IO[ExitCode]]
) = Command(name, header, helpFlag)(version.map(addVersionFlag(opts)).getOrElse(opts))

private[CommandIOApp] def addVersionFlag[F[_]: Console: Functor](
opts: Opts[F[ExitCode]]
)(version: String): Opts[F[ExitCode]] = {
Expand Down

0 comments on commit 06578d6

Please sign in to comment.