clip is a library for parsing command line interface options.
import argv
import clip.{type Command}
import clip/help
import clip/opt.{type Opt}
import gleam/io
import gleam/string
type Person {
Person(name: String, age: Int)
}
fn name_opt() -> Opt(String) {
opt.new("name") |> opt.help("Your name")
}
fn age_opt() -> Opt(Int) {
opt.new("age") |> opt.int |> opt.help("Your age")
}
fn command() -> Command(Person) {
clip.command({
use name <- clip.parameter
use age <- clip.parameter
Person(name, age)
})
|> clip.opt(name_opt())
|> clip.opt(age_opt())
}
pub fn main() -> Nil {
let result =
command()
|> clip.help(help.simple("person", "Create a person"))
|> clip.run(argv.load().arguments)
case result {
Error(e) -> io.println_error(e)
Ok(person) -> person |> string.inspect |> io.println
}
}$ gleam run -- --help
Compiled in 0.00s
Running cli.main
person
Create a person
Usage:
person [OPTIONS]
Options:
(--name NAME) Your name
(--age AGE) Your age
[--help,-h] Print this help
$ gleam run -- --name Drew --age 42
Compiled in 0.00s
Running cli.main
Person("Drew", 42)
clip is an "applicative style" options parser. To use clip, follow these
steps:
- First, invoke
clip.commandproviding a function to be called with your parsed options. This function can be built using the parameter syntax. Alternatively, you can directly provide a curried function, meaning a two argument function looks likefn(a) { fn(b) { do_stuff(a, b) } }. - Next, use the
|>operator along withclip.opt,clip.flag, andclip.argto parse command line arguments and provide them as parameters to the function given toclip.command. - Optionally use
clip.helpandclip/helpto generate help text for your command. The user can view this help text via the--help,-hflag. - Finally, run your parser with
clip.run, giving it the command you have built and the list arguments to parse. I recommend using theargvlibrary to access these arguments from both erlang and javascript.
clip provides three types of options:
- An
Optionis a named option with a value, like--name "Drew". You createOptions with theclip/optmodule and add them to your command with theclip.optfunction. - A
Flagis a named option without a value, like--verbose. If provided, it producesTrue, if not provided it producesFalse. You createFlags with theclip/flagmodule and add them to your command with theclip.flagfunction. - An
Argumentis a positional value passed to your command. You createArguments with theclip/argmodule and add them to your command with theclip.arg,clip.arg_many, andclip.arg_many1functions.
Take a look at the examples for more information.