Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 61 additions & 6 deletions src/FSharp.SystemCommandLine/Inputs.fs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,57 @@ module private MaybeParser =
| t when t = typeof<Uri> -> Uri(tokenValue) |> unbox<'T> |> Some
| t -> Convert.ChangeType(tokenValue, t) :?> 'T |> Some

type private SafeInputLists =
static member private dynamicParser<'T>(): Parsing.ArgumentResult -> Array =
fun result ->
let typ = typeof<'T>
let count = result.Tokens.Count
let elementType =
// if list is empty, then element type will return null
if typ.GetElementType() = null
// use the generic arg passed to the generic type definition
then typ.GetGenericArguments()[0]
// otherwise, we use the element type
else typ.GetElementType()

let dynamicArray = Array.CreateInstance(elementType, count)
for i, token in result.Tokens |> Seq.indexed do
dynamicArray.SetValue(Convert.ChangeType(token.Value, elementType), i)
dynamicArray

static member protect<'T>(o: Argument<'T>) =
match typeof<'T> with
| typ when typ.IsGenericType && typ.GetGenericTypeDefinition() = typedefof<list<_>> ->
o.Arity <- ArgumentArity (0, 100_000)
o.CustomParser <- (SafeInputLists.dynamicParser<'T>() >> fun dynamicArray ->
let modl = typeof<list<obj>>.Assembly.GetType("Microsoft.FSharp.Collections.ListModule")
let meth = modl.GetMethod("OfArray", System.Reflection.BindingFlags.Static ||| System.Reflection.BindingFlags.Public)
meth.MakeGenericMethod(typeof<'T>.GetGenericArguments()[0]).Invoke(null, [| dynamicArray |] ) |> unbox
)
o.DefaultValueFactory <- (fun _ ->
let emptyProperty = typ.GetProperty("Empty", System.Reflection.BindingFlags.Static ||| System.Reflection.BindingFlags.Public)
if emptyProperty <> null then emptyProperty.GetValue(null) |> unbox
else failwithf $"Could not find Empty property on type %s{typ.FullName}."
)
o
| _ -> o
static member protect<'T>(o: Option<'T>) =
match typeof<'T> with
| typ when typ.IsGenericType && typ.GetGenericTypeDefinition() = typedefof<list<_>> ->
o.Arity <- ArgumentArity (0, 100_000)
o.CustomParser <- (SafeInputLists.dynamicParser<'T>() >> fun dynamicArray ->
let modl = typeof<list<obj>>.Assembly.GetType("Microsoft.FSharp.Collections.ListModule")
let meth = modl.GetMethod("OfArray", System.Reflection.BindingFlags.Static ||| System.Reflection.BindingFlags.Public)
meth.MakeGenericMethod(typeof<'T>.GetGenericArguments()[0]).Invoke(null, [| dynamicArray |] ) |> unbox
)
o.DefaultValueFactory <- (fun _ ->
let emptyProperty = typ.GetProperty("Empty", System.Reflection.BindingFlags.Static ||| System.Reflection.BindingFlags.Public)
if emptyProperty <> null then emptyProperty.GetValue(null) |> unbox
else failwithf $"Could not find Empty property on type %s{typ.FullName}."
)
o
| _ -> o

/// A custom action context that contains the `ParseResult` and a cancellation token.
type ActionContext =
{
Expand Down Expand Up @@ -89,7 +140,7 @@ type Arity =
| _ -> ArgumentArity (argumentArity.MinimumNumberOfValues, argumentArity.MaximumNumberOfValues)


module Input =
module Input =

/// Injects an `ActionContext` into the action which contains the `ParseResult` and a cancellation token.
let context =
Expand All @@ -99,9 +150,6 @@ module Input =
let inject<'T> (value: 'T) =
ActionInput<'T>(Injection (box value))

/// Creates a named option. Example: `option "--file-name"`
let option<'T> (name: string) =
Option<'T>(name) |> ActionInput.OfOption

/// Edits the underlying System.CommandLine.Option<'T>.
let editOption (edit: Option<'T> -> unit) (input: ActionInput<'T>) =
Expand Down Expand Up @@ -178,6 +226,12 @@ module Input =
input
|> editOption (fun o -> o.Recursive <- true)

/// Creates a named option. Example: `option "--file-name"`
let option<'T> (name: string) =
Option<'T>(name)
|> SafeInputLists.protect<'T>
|> ActionInput.OfOption<'T>

/// Creates a named option of type `Option<'T option>` that defaults to `None`.
let optionMaybe<'T> (name: string) =
let o = Option<'T option>(name, aliases = [||])
Expand Down Expand Up @@ -217,8 +271,9 @@ module Input =

/// Creates a named argument. Example: `argument "file-name"`
let argument<'T> (name: string) =
let a = Argument<'T>(name)
ActionInput.OfArgument<'T> a
Argument<'T>(name)
|> SafeInputLists.protect<'T>
|> ActionInput.OfArgument<'T>

/// Creates a named argument of type `Argument<'T option>` that defaults to `None`.
let argumentMaybe<'T> (name: string) =
Expand Down
35 changes: 35 additions & 0 deletions src/Tests/ListOptionTest.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
module ListOptionTest


open NUnit.Framework
open Swensen.Unquote
open FSharp.SystemCommandLine
open Utils
open Input

let mutable handlerCalled = false
let called() = handlerCalled <- true
[<SetUp>]
let setup () = handlerCalled <- false

[<Test>]
let ``01 - No input to list option should be empty list``() =
let input = option<string list> "-p" |> arity Arity.ZeroOrMore
let commandRunner (shouldSucceed: bool): string -> (string list -> bool) -> unit = fun command comp ->
testRootCommand command {
description "Test"
inputs input
setAction (function
| values when comp values -> called(); 0
| _ -> 1
)
}
|> if shouldSucceed then (=!) 0 else (<>!) 0
handlerCalled =! shouldSucceed
handlerCalled <- false
let shouldSucceed = commandRunner true
let shouldFail = commandRunner false

shouldSucceed "" List.isEmpty
shouldSucceed "-p a" (List.isEmpty >> not)
shouldFail "-p a" List.isEmpty
1 change: 1 addition & 0 deletions src/Tests/Tests.fsproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
<Compile Include="SimpleAsyncTest.fs" />
<Compile Include="SimpleAppTest.fs" />
<Compile Include="InputBuilderTest.fs" />
<Compile Include="ListOptionTest.fs" />
<Compile Include="Program.fs" />
</ItemGroup>

Expand Down
Loading