Skip to content

Instantly share code, notes, and snippets.

@jbeeko
Last active June 16, 2020 04:47
Show Gist options
  • Save jbeeko/b2d5b8b989b81eaa3c81e2a884f42fde to your computer and use it in GitHub Desktop.
Save jbeeko/b2d5b8b989b81eaa3c81e2a884f42fde to your computer and use it in GitHub Desktop.
A mini command-line program using F# 5.0 scripting
#! /usr/bin/env dotnet fsi --exec --langversion:preview
#r "nuget: Argu"
#r "nuget: FParsec"
// #I needed because of https://github.com/dotnet/fsharp/issues/9217
// Should be fixed for final release
#I "/Users/joergbeekmann/.nuget/packages/fparsec/1.1.1/lib/netstandard2.0"
open Argu
open FParsec
// Setup athe Argu commandline parser
type Type =
| Ints
| Floats
type CliArguments =
| Type of Type
| Usage
| LogLevel of int
with
interface IArgParserTemplate with
member s.Usage =
match s with
| Type _ -> "Specify a type of data to parse."
| LogLevel -> "Specify the log level."
| Usage -> "Show help information."
let clParser = ArgumentParser.Create<CliArguments>(programName = "Parser.fsx")
// Setup a Parsec parser printing the results of parseing a number
let runP p str =
match run p str with
| Success(result, _, _) -> printfn "Success: %A" result
| Failure(errorMsg, _, _) -> printfn "Failure: %s" errorMsg
let parseNum dataType st =
match dataType with
| Some Floats -> runP pfloat st
| Some Ints -> runP pint32 st
| _ -> runP pfloat st
// Parse command line and run processing loop
let clArgs = clParser.Parse fsi.CommandLineArgs.[1..] // without script name
match clArgs.TryGetResult Usage with
| Some _ -> printfn "%s" (clParser.PrintUsage())
| _ ->
let numType = clArgs.TryGetResult Type
let logLevel = clArgs.TryGetResult LogLevel
match logLevel with
| Some s when s > 0 -> printfn "parsing %A" numType
| _ -> ()
// Loop till quit
Seq.initInfinite (fun index -> printfn ">"; stdin.ReadLine())
|> Seq.find (fun input ->
match input with
| "quit" | "q" -> true
| st -> st |> parseNum numType; false
) |> ignore
printfn "bye"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment