Skip to content

Commit 725e662

Browse files
JordanMarrclaude
andcommitted
Tidy list input handling after #38
- Report any element conversion failure as a parse error (overflow, unsupported types like Guid), with a message naming the token and type - Remove unreachable GetElementType and missing-Empty branches - Build closed List.ofArray / List.Empty once per input - Consolidate list tests into a shared runner; cover order, overflow, FileInfo list, and unsupported element types Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent a263f73 commit 725e662

2 files changed

Lines changed: 57 additions & 122 deletions

File tree

‎src/FSharp.SystemCommandLine/Inputs.fs‎

Lines changed: 15 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -20,27 +20,13 @@ module private MaybeParser =
2020
/// Short alias used in SafeInputLists for constraints and delegate construction.
2121
type private ParseFunc<'T> = Func<Parsing.ArgumentResult, 'T>
2222
type private SafeInputLists =
23-
// bound generic `List.OfArray` method
23+
static let publicStatic = Reflection.BindingFlags.Static ||| Reflection.BindingFlags.Public
24+
// open generic `List.ofArray` method
2425
static let ofArrayInfo =
2526
typeof<list<obj>>
2627
.Assembly
2728
.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
29+
.GetMethod("OfArray", publicStatic)
4430
// determines whether provided type is a generic `list` type
4531
static let isListGeneric (typ: Type) =
4632
typ.IsGenericType
@@ -55,32 +41,22 @@ type private SafeInputLists =
5541
let typ = typeof<'T>
5642
// if not a list, noop
5743
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
44+
let elementType = typ.GetGenericArguments()[0]
45+
// closed `List.ofArray<elementType>` and `List<elementType>.Empty`, built once per input
46+
let ofArray = ofArrayInfo.MakeGenericMethod(elementType)
47+
let empty = typ.GetProperty("Empty", publicStatic).GetValue(null) |> unbox<'T>
6648
// 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>)
49+
ParseFunc(fun _ -> empty)
7350
|> o.set_DefaultValueFactory
74-
// Custom Parser -> tokens -> Array -> List.OfArray
51+
// Custom Parser -> tokens -> Array -> List.ofArray
7552
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
53+
let dynamicArray = Array.CreateInstance(elementType, result.Tokens.Count)
54+
result.Tokens |> Seq.iteri (fun i token ->
7955
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>)
56+
dynamicArray.SetValue(MaybeParser.parseTokenValueForType elementType token.Value, i)
57+
with _ ->
58+
result.AddError $"Cannot parse '%s{token.Value}' as %s{elementType.Name}.")
59+
ofArray.Invoke(null, [| dynamicArray |]) |> unbox<'T>)
8460
|> o.set_CustomParser
8561
ArgumentArity(0, 100_000)
8662
|> o.set_Arity

‎src/Tests/ListOptionTest.fs‎

Lines changed: 42 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -1,102 +1,61 @@
11
module ListOptionTest
22

3-
43
open NUnit.Framework
54
open Swensen.Unquote
65
open FSharp.SystemCommandLine
76
open Utils
87
open Input
98

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 ->
9+
/// Runs `command` against a root command with the single list `input`.
10+
/// Returns `Some values` if the action ran, or `None` if parsing failed.
11+
let run (input: ActionInput<'T list>) (command: string) =
12+
let mutable received = None
13+
let exitCode =
1914
testRootCommand command {
2015
description "Test"
2116
inputs input
22-
setAction (function
23-
| values when comp values -> called(); 0
24-
| _ -> 1
25-
)
17+
setAction (fun values -> received <- Some values; 0)
2618
}
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-
19+
match received with
20+
| Some _ -> exitCode =! 0
21+
| None -> exitCode <>! 0
22+
received
23+
3724
[<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
25+
let ``01 - string list option`` () =
26+
let input = option<string list> "-p"
27+
run input "" =! Some []
28+
run input "-p a" =! Some [ "a" ]
29+
run input "-p a -p b -p c" =! Some [ "a"; "b"; "c" ]
5830

31+
[<Test>]
32+
let ``02 - int list option`` () =
33+
let input = option<int list> "-p"
34+
run input "" =! Some []
35+
run input "-p 3 -p 1 -p 2" =! Some [ 3; 1; 2 ]
36+
run input "-p a" =! None
37+
run input "-p 99999999999" =! None
5938

6039
[<Test>]
61-
let ``03 - No input to string list argument should be empty list``() =
40+
let ``03 - string list argument`` () =
6241
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-
42+
run input "" =! Some []
43+
run input "a b" =! Some [ "a"; "b" ]
44+
8245
[<Test>]
83-
let ``04 - No input to int list argument should be empty list``() =
46+
let ``04 - int list argument`` () =
8447
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
48+
run input "" =! Some []
49+
run input "3 4" =! Some [ 3; 4 ]
50+
run input "a" =! None
51+
52+
[<Test>]
53+
let ``05 - FileInfo list option`` () =
54+
let input = option<System.IO.FileInfo list> "-f"
55+
let names = run input "-f a.txt -f b.txt" |> Option.map (List.map _.Name)
56+
names =! Some [ "a.txt"; "b.txt" ]
57+
58+
[<Test>]
59+
let ``06 - Guid list option reports unsupported type as a parse error`` () =
60+
let input = option<System.Guid list> "-g"
61+
run input "-g 7f3c2a10-0000-0000-0000-000000000000" =! None

0 commit comments

Comments
 (0)