64 lines
1.7 KiB
Markdown
64 lines
1.7 KiB
Markdown
|
|
# Haskell optparse-applicative
|
||
|
|
|
||
|
|
This note covers `33-haskell-optparse-cli/`, which parses a small deployment CLI with `optparse-applicative`.
|
||
|
|
|
||
|
|
---
|
||
|
|
|
||
|
|
## 1. Why This Is Different from the Parser-Combinator Example
|
||
|
|
|
||
|
|
`12-haskell-parser-combinators/` builds a parser for a custom command language.
|
||
|
|
|
||
|
|
This example solves a different problem: parsing a conventional CLI with:
|
||
|
|
|
||
|
|
- subcommands,
|
||
|
|
- long options,
|
||
|
|
- repeated options, and
|
||
|
|
- typed option readers.
|
||
|
|
|
||
|
|
That is a common real-world Haskell task, and `optparse-applicative` is the standard tool for it.
|
||
|
|
|
||
|
|
---
|
||
|
|
|
||
|
|
## 2. What the Pure Parser Gives You
|
||
|
|
|
||
|
|
The example exposes:
|
||
|
|
|
||
|
|
```haskell
|
||
|
|
runCliParser :: [String] -> Either String Command
|
||
|
|
```
|
||
|
|
|
||
|
|
Internally it uses `execParserPure`, which keeps the parsing logic testable without invoking `IO` or shelling out.
|
||
|
|
|
||
|
|
That is the main teaching point here: command-line parsing can still be structured as a pure transformation from argument vectors to typed commands.
|
||
|
|
|
||
|
|
---
|
||
|
|
|
||
|
|
## 3. What Makes the Example Non-Trivial
|
||
|
|
|
||
|
|
The parser handles two shapes of command:
|
||
|
|
|
||
|
|
- `validate`, which parses typed environment, replica, and track options, and
|
||
|
|
- `promote`, which parses repeated `--owner` flags plus a `--dry-run` switch.
|
||
|
|
|
||
|
|
That is enough surface area to show why a dedicated CLI parser library is useful.
|
||
|
|
|
||
|
|
---
|
||
|
|
|
||
|
|
## 4. Commands to Try
|
||
|
|
|
||
|
|
```bash
|
||
|
|
cd 33-haskell-optparse-cli
|
||
|
|
|
||
|
|
nix develop
|
||
|
|
cabal run
|
||
|
|
cabal run -- validate --service api --env production --replicas 3 --track stable
|
||
|
|
cabal run -- promote --service api --from-tag blue --to-tag green --owner platform --owner security --dry-run
|
||
|
|
cabal test
|
||
|
|
|
||
|
|
nix build
|
||
|
|
./result/bin/mini-cli validate --service api --env production --replicas 3 --track stable
|
||
|
|
|
||
|
|
nix run . -- validate --service api --env production --replicas 3 --track stable
|
||
|
|
nix flake check
|
||
|
|
```
|