Skip to content

Commit 67031ec

Browse files
authored
Merge pull request #37 from shayanhabibi/choices
feat: 4 function helpers for accepting a known set of values bound to a typed value
2 parents b76396b + 385705a commit 67031ec

4 files changed

Lines changed: 192 additions & 1 deletion

File tree

‎README.md‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,8 @@ The new `Input` module contains functions for the underlying System.CommandLine
213213
* `validateDirectoryExists` ensures that the `DirectoryInfo` exists
214214
* `addValidator` allows you to add a validator to the underlying `Option` or `Argument`
215215
* `acceptOnlyFromAmong` validates the allowed values for an `Option` or `Argument`
216+
* `mapFromAmong` validates allowed values against `string * 'T` tuples, providing the typed value
217+
* `mapFromAmongWith` validates allowed values against `string * 'T` tuples using a given `StringComparer`
216218
* `customParser` allows you to parse the input tokens using a custom parser function.
217219
* `tryParse` allows you to parse the input tokens using a custom parser `Result<'T, string>` function.
218220
* `arity` sets the arity of an `Option` or `Argument`
@@ -782,6 +784,42 @@ Notes about invocation:
782784

783785
</details>
784786

787+
<details>
788+
<summary><b>Mapping to a bound set of typed values</b></summary>
789+
790+
Use `Input.mapFromAmong` to map string inputs to typed values:
791+
792+
```F#
793+
open FSharp.SystemCommandLine
794+
type Configuration =
795+
| Debug
796+
| Release
797+
798+
let config =
799+
Input.option<Configuration>
800+
|> Input.mapFromAmong [
801+
"r", Release; "release", Release
802+
"R", Release; "Release", Release
803+
"d", Debug; "debug", Debug
804+
"D", Debug; "Debug", Debug
805+
]
806+
// is required unless you provide a default
807+
808+
// use `Input.mapFromAmongWith` to pass a custom string comparer!
809+
810+
let config =
811+
Input.option<Configuration>
812+
|> Input.mapFromAmongWith StringComparer.OrdinalIgnoreCase [
813+
"r", Release; "release", Release
814+
"d", Debug; "debug", Debug
815+
]
816+
```
817+
818+
Notes about overriding properties:
819+
* `Input.tryParse` will overwrite the configuration from `.mapFromAmong` if it is used downstream.
820+
821+
</details>
822+
785823
---
786824

787825
## Configuration

‎src/FSharp.SystemCommandLine/Inputs.fs‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,6 @@ module Input =
172172
input
173173
|> editOption (fun o -> o.Required <- true)
174174

175-
/// Marks an argument as required.
176175
/// When set to true, this option will be applied to its immediate parent command or commands and recursively to their subcommands.
177176
let recursive (input: ActionInput<'T>) =
178177
input
@@ -308,6 +307,32 @@ module Input =
308307
argResult.AddError(err)
309308
Unchecked.defaultof<'T>
310309
)
310+
311+
312+
/// <summary>
313+
/// Maps an input whose legal values are a known set bound to a typed value using the given <c>StringComparer</c>.
314+
/// <remarks>Caution: avoid overriding downstream with <c>Input.tryParse</c>.</remarks>
315+
/// </summary>
316+
let mapFromAmongWith (comparer: StringComparer) (choices: seq<string * 'T>) (input: ActionInput<'T>) =
317+
let keys = choices |> Seq.map fst
318+
let legal = keys |> String.concat ", "
319+
let lookup token = choices |> Seq.tryFind (fun (key, _) -> comparer.Equals(key, token)) |> Option.map snd
320+
editOption (fun opt -> for key in keys do opt.CompletionSources.Add key) input
321+
|> editArgument (fun arg -> for key in keys do arg.CompletionSources.Add key)
322+
// parser closes over lookup -> nothing downstream can reach in/modify or would break.
323+
|> tryParse (fun argResult ->
324+
match argResult.Tokens |> Seq.tryLast with
325+
| None -> Error $"'%s{argResult.Argument.Name}' needs one of: %s{legal}"
326+
| Some token ->
327+
match lookup token.Value with
328+
| Some value -> Ok value
329+
| None -> Error $"'%s{token.Value}' is not a valid choice from: %s{legal}"
330+
)
331+
332+
/// <summary>Maps an input whose legal values are a known set bound to a typed value.</summary>
333+
/// <remarks>Caution: avoid overriding downstream with <c>Input.tryParse</c>.</remarks>
334+
let mapFromAmong (choices: seq<string * 'T>) (input: ActionInput<'T>) =
335+
mapFromAmongWith StringComparer.Ordinal choices input
311336

312337
/// Sets the arity of an option or argument.
313338
let arity (arity: Arity) (input: ActionInput<'T>) =

‎src/Tests/MapFromAmongTest.fs‎

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
module MapFromAmongTest
2+
3+
4+
open System
5+
open NUnit.Framework
6+
open Swensen.Unquote
7+
open FSharp.SystemCommandLine
8+
open Utils
9+
open Input
10+
11+
let mutable actionCalled = false
12+
let callAction() = actionCalled <- true
13+
[<SetUp>]
14+
let setup () = actionCalled <- false
15+
16+
type DUType =
17+
| A
18+
| B
19+
20+
let duChoices = [
21+
"a", A
22+
B.ToString() (* "B" *), B
23+
]
24+
25+
[<Test>]
26+
let ``01 - mapFromAmong requires input``() =
27+
let input =
28+
option<DUType> "--du" |> mapFromAmong duChoices
29+
testRootCommand "--du" {
30+
description "Test"
31+
inputs input
32+
setAction (ignore >> callAction)
33+
} <>! 0
34+
actionCalled <>! true
35+
36+
[<Test>]
37+
let ``02 - mapFromAmong returns correct typed DU value``() =
38+
let input = option<DUType> "--du" |> mapFromAmong duChoices
39+
let compareAgainst (shouldSucceed: bool): string -> DUType -> unit = fun cmd v ->
40+
testRootCommand cmd {
41+
description "Test"
42+
inputs input
43+
setAction (fun o ->
44+
if shouldSucceed
45+
then o =! v |> callAction; 0
46+
else o <>! v; 1
47+
)
48+
}
49+
|> if shouldSucceed then (=!) 0 else (<>!) 0
50+
actionCalled =! shouldSucceed
51+
actionCalled <- false
52+
let shouldSucceed = compareAgainst true
53+
let shouldFail = compareAgainst false
54+
// valid casing
55+
shouldSucceed "--du a" A
56+
shouldSucceed "--du B" B
57+
// invalid casing
58+
shouldFail "--du A" A
59+
shouldFail "--du b" B
60+
// invalid input
61+
shouldFail "--du c" A
62+
shouldFail "--du c" B
63+
// invalid map
64+
shouldFail "--du a" B
65+
shouldFail "--du B" A
66+
67+
68+
[<Test>]
69+
let ``03 - mapFromAmongWith returns correct typed DU - case insensitive``() =
70+
let input = option<DUType> "--du" |> mapFromAmongWith StringComparer.OrdinalIgnoreCase duChoices
71+
let compareAgainst (shouldSucceed: bool): string -> DUType -> unit = fun cmd v ->
72+
testRootCommand cmd {
73+
description "Test"
74+
inputs input
75+
setAction (fun o ->
76+
if shouldSucceed
77+
then o =! v |> callAction; 0
78+
else o <>! v; 1
79+
)
80+
}
81+
|> if shouldSucceed then (=!) 0 else (<>!) 0
82+
actionCalled =! shouldSucceed
83+
actionCalled <- false
84+
let shouldSucceed = compareAgainst true
85+
let shouldFail = compareAgainst false
86+
shouldSucceed "--du a" A
87+
shouldSucceed "--du A" A
88+
shouldSucceed "--du b" B
89+
shouldSucceed "--du B" B
90+
// invalid input
91+
shouldFail "--du c" A
92+
shouldFail "--du c" B
93+
// invalid map
94+
shouldFail "--du a" B
95+
shouldFail "--du B" A
96+
97+
[<Test>]
98+
let ``04 - mapFromAmong followed by different tryParse will override``() =
99+
let input = option<DUType> "--du" |> mapFromAmong duChoices |> tryParse (fun _ -> Ok A)
100+
let compareAgainst (shouldSucceed: bool): string -> DUType -> unit = fun cmd v ->
101+
testRootCommand cmd {
102+
description "Test"
103+
inputs input
104+
setAction (fun o ->
105+
if shouldSucceed
106+
then o =! v |> callAction; 0
107+
else o <>! v; 1
108+
)
109+
}
110+
|> if shouldSucceed then (=!) 0 else (<>!) 0
111+
actionCalled =! shouldSucceed
112+
actionCalled <- false
113+
let shouldSucceed = compareAgainst true
114+
let shouldFail = compareAgainst false
115+
shouldSucceed "--du a" A
116+
shouldSucceed "--du A" A
117+
shouldSucceed "--du b" A
118+
shouldSucceed "--du B" A
119+
shouldFail "--du a" B
120+
shouldFail "--du A" B
121+
shouldFail "--du b" B
122+
shouldFail "--du B" B
123+
// invalid input still processes
124+
// completions will still show correctly
125+
// undefined behaviour
126+
shouldSucceed "--du c" A
127+
shouldFail "--du c" B

‎src/Tests/Tests.fsproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
<Compile Include="SimpleAsyncTest.fs" />
1818
<Compile Include="SimpleAppTest.fs" />
1919
<Compile Include="InputBuilderTest.fs" />
20+
<Compile Include="MapFromAmongTest.fs" />
2021
<Compile Include="Program.fs" />
2122
</ItemGroup>
2223

0 commit comments

Comments
 (0)