Packages
glint
0.18.1
1.3.0
1.2.1
1.2.0
1.1.1
1.1.0
1.0.1
1.0.0
1.0.0-rc5
1.0.0-rc4
1.0.0-rc3
1.0.0-rc2
1.0.0-rc1
0.18.1
0.18.0
0.17.1
0.17.0
0.16.0
0.16.0-rc1
0.15.0
0.15.0-rc2
0.15.0-rc1
0.14.0
0.13.0
0.12.0
0.12.0-rc6
0.12.0-rc5
0.12.0-rc4
0.12.0-rc3
0.12.0-rc2
0.12.0-rc1
0.11.4
0.11.3
0.11.2
0.11.0
0.10.0
0.9.0
0.8.0
0.7.4
0.7.3
0.7.2
0.7.1
0.7.0
0.6.0
0.5.0
0.4.0
0.3.0
0.2.0
0.1.3
0.1.2
0.1.1
0.1.0
Gleam command-line argument parsing with flags and automated help text generation.
Current section
Files
Jump to
Current section
Files
src/glint/flag/constraint.gleam
import gleam/list
import gleam/result
import gleam/set
import gleam/string
import snag.{type Result}
/// Constraint type for verifying flag values
///
pub type Constraint(a) =
fn(a) -> Result(Nil)
/// one_of returns a Constraint that ensures the parsed flag value is
/// one of the allowed values.
///
pub fn one_of(allowed: List(a)) -> Constraint(a) {
let allowed_set = set.from_list(allowed)
fn(val: a) -> Result(Nil) {
case set.contains(allowed_set, val) {
True -> Ok(Nil)
False ->
snag.error(
"invalid value '"
<> string.inspect(val)
<> "', must be one of: ["
<> {
allowed
|> list.map(fn(a) { "'" <> string.inspect(a) <> "'" })
|> string.join(", ")
}
<> "]",
)
}
}
}
/// none_of returns a Constraint that ensures the parsed flag value is not one of the disallowed values.
///
pub fn none_of(disallowed: List(a)) -> Constraint(a) {
let disallowed_set = set.from_list(disallowed)
fn(val: a) -> Result(Nil) {
case set.contains(disallowed_set, val) {
False -> Ok(Nil)
True ->
snag.error(
"invalid value '"
<> string.inspect(val)
<> "', must not be one of: ["
<> {
{
disallowed
|> list.map(fn(a) { "'" <> string.inspect(a) <> "'" })
|> string.join(", ")
<> "]"
}
},
)
}
}
}
/// each is a convenience function for applying a Constraint(a) to a List(a).
/// This is useful because the default behaviour for constraints on lists is that they will apply to the list as a whole.
///
/// For example, to apply one_of to all items in a `List(Int)`:
/// ```gleam
/// [1, 2, 3, 4] |> one_of |> each
/// ```
pub fn each(constraint: Constraint(a)) -> Constraint(List(a)) {
fn(l: List(a)) -> Result(Nil) {
l
|> list.try_map(constraint)
|> result.replace(Nil)
}
}