Skip to content

Commit a263f73

Browse files
authored
Merge pull request #38 from shayanhabibi/empty-lists
Safe list handling for ActionInputs
2 parents 9702fdc + 9b44a5a commit a263f73

3 files changed

Lines changed: 193 additions & 9 deletions

File tree

‎src/FSharp.SystemCommandLine/Inputs.fs‎

Lines changed: 90 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,93 @@ namespace FSharp.SystemCommandLine
33
open System
44
open System.CommandLine
55

6-
module private MaybeParser =
6+
module private MaybeParser =
7+
/// Parses an argument token value to the given type.
8+
let parseTokenValueForType (typ: Type) (tokenValue: string) =
9+
match typ with
10+
| t when t = typeof<IO.DirectoryInfo> -> IO.DirectoryInfo(tokenValue) :> obj
11+
| t when t = typeof<IO.FileInfo> -> IO.FileInfo(tokenValue)
12+
| t when t = typeof<Uri> -> Uri(tokenValue)
13+
| t -> Convert.ChangeType(tokenValue, t)
14+
715
/// Parses an argument token value.
816
/// TODO: Ideally, this should use the S.CL Arugment parser.
917
let parseTokenValue<'T> (tokenValue: string) =
10-
match typeof<'T> with
11-
| t when t = typeof<IO.DirectoryInfo> -> IO.DirectoryInfo(tokenValue) |> unbox<'T> |> Some
12-
| t when t = typeof<IO.FileInfo> -> IO.FileInfo(tokenValue) |> unbox<'T> |> Some
13-
| t when t = typeof<Uri> -> Uri(tokenValue) |> unbox<'T> |> Some
14-
| t -> Convert.ChangeType(tokenValue, t) :?> 'T |> Some
18+
parseTokenValueForType typeof<'T> tokenValue :?> 'T |> Some
19+
20+
/// Short alias used in SafeInputLists for constraints and delegate construction.
21+
type private ParseFunc<'T> = Func<Parsing.ArgumentResult, 'T>
22+
type private SafeInputLists =
23+
// bound generic `List.OfArray` method
24+
static let ofArrayInfo =
25+
typeof<list<obj>>
26+
.Assembly
27+
.GetType("Microsoft.FSharp.Collections.ListModule")
28+
.GetMethod("OfArray", System.Reflection.BindingFlags.Static ||| System.Reflection.BindingFlags.Public)
29+
// invokes `List.OfArray` with the given array using the provided type as the element type
30+
static let ofArrayForType (typ: Type) (elements: Array) =
31+
ofArrayInfo.MakeGenericMethod(typ.GetGenericArguments()[0]).Invoke(null, [| elements |])
32+
// safely retrieves the element type of a list type
33+
static let listElementType (typ: Type) =
34+
// naive tests show more predictable behaviour
35+
// with the presence of this branch
36+
match typ.GetElementType() with
37+
| null -> typ.GetGenericArguments()[0]
38+
| typ -> typ
39+
// retrieves the `List.Empty` property for the given element type generic
40+
static let makeEmptyList (typ: Type) =
41+
match typ.GetProperty("Empty", System.Reflection.BindingFlags.Static ||| System.Reflection.BindingFlags.Public) with
42+
| null -> Error $"Could not find Empty property on type %s{typ.FullName}."
43+
| prop -> prop.GetValue(null) |> Ok
44+
// determines whether provided type is a generic `list` type
45+
static let isListGeneric (typ: Type) =
46+
typ.IsGenericType
47+
&& typ.GetGenericTypeDefinition() = typedefof<list<_>>
48+
static member inline private dynamicParser<^T, ^U
49+
// static binding of Option<_> and Argument<_>
50+
// where T is the typar for U: the generic Option/Argument
51+
when ^U:(member set_DefaultValueFactory: ParseFunc<^T> -> unit)
52+
and ^U:(member set_CustomParser: ParseFunc<^T> -> unit)
53+
and ^U:(member set_Arity: ArgumentArity -> unit)>
54+
(o: ^U) =
55+
let typ = typeof<'T>
56+
// if not a list, noop
57+
if not <| isListGeneric typ then () else
58+
let elementType = listElementType typ
59+
// parses token to element type
60+
let changeType: Parsing.Token -> obj =
61+
let fn = MaybeParser.parseTokenValueForType elementType
62+
_.Value >> fn
63+
// converts array to final list type
64+
let ofArray = ofArrayForType typ
65+
let empty = makeEmptyList typ
66+
// Default Value Factory -> List.Empty
67+
ParseFunc(fun result ->
68+
match empty with
69+
| Error err ->
70+
result.AddError err
71+
Unchecked.defaultof<'T>
72+
| Ok empty -> empty |> unbox<'T>)
73+
|> o.set_DefaultValueFactory
74+
// Custom Parser -> tokens -> Array -> List.OfArray
75+
ParseFunc(fun result ->
76+
let count = result.Tokens.Count
77+
let dynamicArray = Array.CreateInstance(elementType, count)
78+
for i, token in result.Tokens |> Seq.indexed do
79+
try
80+
dynamicArray.SetValue(changeType token, i)
81+
// should this be more permissive?
82+
with :? FormatException as e -> result.AddError e.Message
83+
ofArray dynamicArray |> unbox<'T>)
84+
|> o.set_CustomParser
85+
ArgumentArity(0, 100_000)
86+
|> o.set_Arity
87+
/// Checks `'T` for a `List&lt;_>` generic type. Injects list compatible CustomParser and DefaultValueFactory
88+
/// if `true`; noop if `false`
89+
static member protect<'T>(o: Argument<'T>) = SafeInputLists.dynamicParser<'T, _> o; o
90+
/// Checks `'T` for a `List&lt;_>` generic type. Injects list compatible CustomParser and DefaultValueFactory
91+
/// if `true`; noop if `false`
92+
static member protect<'T>(o: Option<'T>) = SafeInputLists.dynamicParser<'T, _> o; o
1593

1694
/// A custom action context that contains the `ParseResult` and a cancellation token.
1795
type ActionContext =
@@ -101,7 +179,9 @@ module Input =
101179

102180
/// Creates a named option. Example: `option "--file-name"`
103181
let option<'T> (name: string) =
104-
Option<'T>(name) |> ActionInput.OfOption
182+
Option<'T>(name)
183+
|> SafeInputLists.protect
184+
|> ActionInput.OfOption
105185

106186
/// Edits the underlying System.CommandLine.Option<'T>.
107187
let editOption (edit: Option<'T> -> unit) (input: ActionInput<'T>) =
@@ -216,8 +296,9 @@ module Input =
216296

217297
/// Creates a named argument. Example: `argument "file-name"`
218298
let argument<'T> (name: string) =
219-
let a = Argument<'T>(name)
220-
ActionInput.OfArgument<'T> a
299+
Argument<'T>(name)
300+
|> SafeInputLists.protect
301+
|> ActionInput.OfArgument<'T>
221302

222303
/// Creates a named argument of type `Argument<'T option>` that defaults to `None`.
223304
let argumentMaybe<'T> (name: string) =

‎src/Tests/ListOptionTest.fs‎

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
module ListOptionTest
2+
3+
4+
open NUnit.Framework
5+
open Swensen.Unquote
6+
open FSharp.SystemCommandLine
7+
open Utils
8+
open Input
9+
10+
let mutable handlerCalled = false
11+
let called() = handlerCalled <- true
12+
[<SetUp>]
13+
let setup () = handlerCalled <- false
14+
15+
[<Test>]
16+
let ``01 - No input to string list option should be empty list``() =
17+
let input = option<string list> "-p"
18+
let commandRunner (shouldSucceed: bool): string -> (string list -> bool) -> unit = fun command comp ->
19+
testRootCommand command {
20+
description "Test"
21+
inputs input
22+
setAction (function
23+
| values when comp values -> called(); 0
24+
| _ -> 1
25+
)
26+
}
27+
|> if shouldSucceed then (=!) 0 else (<>!) 0
28+
handlerCalled =! shouldSucceed
29+
handlerCalled <- false
30+
let shouldSucceed = commandRunner true
31+
let shouldFail = commandRunner false
32+
33+
shouldSucceed "" List.isEmpty
34+
shouldSucceed "-p a" (List.isEmpty >> not)
35+
shouldFail "-p a" List.isEmpty
36+
37+
[<Test>]
38+
let ``02 - No input to int list option should be empty list``() =
39+
let input = option<int list> "-p"
40+
let commandRunner (shouldSucceed: bool): string -> (int list -> bool) -> unit = fun command comp ->
41+
testRootCommand command {
42+
description "Test"
43+
inputs input
44+
setAction (function
45+
| values when comp values -> called(); 0
46+
| _ -> 1
47+
)
48+
}
49+
|> if shouldSucceed then (=!) 0 else (<>!) 0
50+
handlerCalled =! shouldSucceed
51+
handlerCalled <- false
52+
let shouldSucceed = commandRunner true
53+
let shouldFail = commandRunner false
54+
55+
shouldSucceed "" List.isEmpty
56+
shouldSucceed "-p 3" (List.isEmpty >> not)
57+
shouldFail "-p a" List.isEmpty
58+
59+
60+
[<Test>]
61+
let ``03 - No input to string list argument should be empty list``() =
62+
let input = argument<string list> "p"
63+
let commandRunner (shouldSucceed: bool): string -> (string list -> bool) -> unit = fun command comp ->
64+
testRootCommand command {
65+
description "Test"
66+
inputs input
67+
setAction (function
68+
| values when comp values -> called(); 0
69+
| _ -> 1
70+
)
71+
}
72+
|> if shouldSucceed then (=!) 0 else (<>!) 0
73+
handlerCalled =! shouldSucceed
74+
handlerCalled <- false
75+
let shouldSucceed = commandRunner true
76+
let shouldFail = commandRunner false
77+
78+
shouldSucceed "" List.isEmpty
79+
shouldSucceed "a" (List.isEmpty >> not)
80+
shouldFail "a" List.isEmpty
81+
82+
[<Test>]
83+
let ``04 - No input to int list argument should be empty list``() =
84+
let input = argument<int list> "p"
85+
let commandRunner (shouldSucceed: bool): string -> (int list -> bool) -> unit = fun command comp ->
86+
testRootCommand command {
87+
description "Test"
88+
inputs input
89+
setAction (function
90+
| values when comp values -> called(); 0
91+
| _ -> 1
92+
)
93+
}
94+
|> if shouldSucceed then (=!) 0 else (<>!) 0
95+
handlerCalled =! shouldSucceed
96+
handlerCalled <- false
97+
let shouldSucceed = commandRunner true
98+
let shouldFail = commandRunner false
99+
100+
shouldSucceed "" List.isEmpty
101+
shouldSucceed "3" (List.isEmpty >> not)
102+
shouldFail "a" List.isEmpty

‎src/Tests/Tests.fsproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
<Compile Include="SimpleAppTest.fs" />
1919
<Compile Include="InputBuilderTest.fs" />
2020
<Compile Include="MapFromAmongTest.fs" />
21+
<Compile Include="ListOptionTest.fs" />
2122
<Compile Include="Program.fs" />
2223
</ItemGroup>
2324

0 commit comments

Comments
 (0)