Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use with F#? #941

Closed
sgaliamov opened this issue Jun 21, 2020 · 2 comments
Closed

How to use with F#? #941

sgaliamov opened this issue Jun 21, 2020 · 2 comments

Comments

@sgaliamov
Copy link

Hi, I'm trying to use it in F#:

module Program

open System.CommandLine
open System.CommandLine.Invocation;
open System

let [<EntryPoint>] main args =
    let root = new RootCommand()
    let option = new Option<string>("--test")
    root.AddOption option
    root.Handler <- CommandHandler.Create<string>(fun (test: string) -> Console.WriteLine test)
    root.Invoke args

Handler is invoked, but test argument is null. What I'm doing wrong?

@twaalewijn
Copy link

I don't think you've done anything wrong in the code example you've posted.

It seems to work just fine for me when copy pasted into a new F# console project targeting netcoreapp3.1 and using version 2.0.0-beta1.20303.1 of System.CommandLine from NuGet.

What doesn't work for me is using the name of another function directly as a handler e.g.:

let handler(test: string) =
    Console.WriteLine test

[<EntryPoint>]
let main args =
    let root = new RootCommand()
    let option = new Option<string>("--test")
    root.AddOption option
    // Compiles just fine but test is null when the handler function gets called.
    root.Handler <- CommandHandler.Create(handler)
    root.Invoke args

I'm assuming this is somehow caused by the implicit cast/conversion from string -> unit to Action<string>.

You can get around this by either passing test as you've done in the example:

let handler(test: string) =
    Console.WriteLine test

[<EntryPoint>]
let main args =
    let root = new RootCommand()
    let option = new Option<string>("--test")
    root.AddOption option
    root.Handler <- CommandHandler.Create(fun (test) -> handler test)
    root.Invoke args

Or defining a type to store your option values in.
Something like this for example:

type Opt(test) =
    member val Test: string = test

let handler(opt: Opt) =
    Console.WriteLine opt.Test

[<EntryPoint>]
let main args =
    let root = new RootCommand()
    let option = new Option<string>("--test")
    root.AddOption option
    root.Handler <- CommandHandler.Create(handler)
    root.Invoke args

@sgaliamov
Copy link
Author

@twaalewijn thank you.
i updated the sdk and now it works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants