clad

Package Version Hex Docs

Command line argument decoders for Gleam.

Clad makes it easy and familiar to parse command line arguments in Gleam. The goal is to support simple-to-medium complexity command line interfaces while staying as minimal as possible. It is inspired by minimist and gleam/json

Usage

gleam add clad

This program is in the examples directory

import argv
import clad
import decode/zero

pub type Student {
  Student(name: String, age: Int, enrolled: Bool, classes: List(String))
}

pub fn main() {
  let decoder = {
    use name <- zero.field("name", zero.string)
    use age <- zero.field("age", zero.int)
    use enrolled <- zero.field("enrolled", zero.bool)
    use classes <- zero.field("class", zero.list(zero.string))
    zero.success(Student(name:, age:, enrolled:, classes:))
  }

  // args: --name Lucy --age 8 --enrolled true --class math --class art
  let result = clad.decode(argv.load().arguments, decoder)
  let assert Ok(Student("Lucy", 8, True, ["math", "art"])) = result
}

Or, for more flexibility:

import argv
import clad
import decode/zero

pub type Student {
  Student(name: String, age: Int, enrolled: Bool, classes: List(String))
}

pub fn main() {
  let decoder = {
    use name <- clad.opt("name", "n", zero.string)
    use age <- clad.opt("age", "a", zero.int)
    use enrolled <- clad.flag("enrolled", "e")
    use classes <- clad.opt("class", "c", clad.list(zero.string))
    zero.success(Student(name:, age:, enrolled:, classes:))
  }

  // args: --name=Lucy -ea8 -c math -c art
  let result = clad.decode(argv.load().arguments, decoder)
  let assert Ok(Student("Lucy", 8, True, ["math", "art"])) = result
}

Further documentation can be found at https://hexdocs.pm/clad.

Search Document