Skip to content

Commit

Permalink
add optional_opt
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanmiville committed Dec 30, 2024
1 parent 9b6f2f5 commit ffbe612
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 3 deletions.
2 changes: 1 addition & 1 deletion gleam.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name = "clad"
version = "1.0.1"
version = "1.1.0"

# Fill out these fields if you intend to generate HTML documentation or publish
# your project to the Hex package manager.
Expand Down
28 changes: 26 additions & 2 deletions src/clad.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -213,10 +213,34 @@ pub fn flag(
short_name: String,
next: fn(Bool) -> Decoder(final),
) -> Decoder(final) {
use value <- optional_field(long_name, decode.bool)
optional_opt(long_name, short_name, False, decode.bool, next)
}

/// Decode a command line option by either a long name or short name.
/// The given default value is returned if the option does not exist.
/// ```gleam
/// let decoder = {
/// use name <- clad.optional_opt("name", "n", "Lucy", decode.string)
/// decode.success(name)
/// }
///
/// let result = clad.decode(["--name", "Joe"], decoder)
/// assert result == Ok("Joe")
///
/// let result = clad.decode([], decoder)
/// assert result == Ok("Lucy")
/// ```
pub fn optional_opt(
long_name: String,
short_name: String,
default: t,
field_decoder: Decoder(t),
next: fn(t) -> Decoder(final),
) -> Decoder(final) {
use value <- optional_field(long_name, field_decoder)
case value {
Some(v) -> next(v)
None -> decode.optional_field(short_name, False, decode.bool, next)
None -> decode.optional_field(short_name, default, field_decoder, next)
}
}

Expand Down
16 changes: 16 additions & 0 deletions test/clad_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -210,3 +210,19 @@ pub fn list_test() {
clad.decode([], decoder)
|> should.be_error
}

pub fn optional_opt_test() {
let decoder = {
use name <- clad.optional_opt("name", "n", "Lucy", decode.string)
decode.success(name)
}

clad.decode(["--name", "Joe"], decoder)
|> should.equal(Ok("Joe"))

clad.decode(["-n", "Joe"], decoder)
|> should.equal(Ok("Joe"))

clad.decode([], decoder)
|> should.equal(Ok("Lucy"))
}

0 comments on commit ffbe612

Please sign in to comment.