SHOW:
|
|
- or go back to the newest paste.
1 | module VersionOne.CommandLine | |
2 | ||
3 | - | type OptionBag = { |
3 | + | module ArgParse = |
4 | - | storedCredsFile : string |
4 | + | |
5 | - | secretsFile : string |
5 | + | type FlagFuncs<'T> = Map<string, ('T -> 'T)> |
6 | - | } with |
6 | + | type ValueFuncs<'T> = Map<string, ('T -> string -> 'T)> |
7 | - | static member Default = { |
7 | + | type BareFunc<'T> = 'T -> string -> 'T |
8 | - | storedCredsFile = "stored_credentials.json" |
8 | + | |
9 | - | secretsFile = "client_secrets.json" |
9 | + | type OptionsDefinition<'T> = { |
10 | initialState : 'T | |
11 | flagFuncs : FlagFuncs<'T> | |
12 | - | let flagFuncs = |
12 | + | valueFuncs : ValueFuncs<'T> |
13 | - | Map [ |
13 | + | bareFunc : BareFunc<'T> |
14 | - | "-h", fun state -> failwith "Would display help here" |
14 | + | |
15 | - | ] |
15 | + | |
16 | let rec parseArgs' (def:OptionsDefinition<'T>) state = function | |
17 | - | let valueFuncs = |
17 | + | | flag :: tail when def.flagFuncs.ContainsKey flag -> parseArgs' def (def.flagFuncs.[flag] state) tail |
18 | - | Map [ |
18 | + | | flag :: arg :: tail when def.valueFuncs.ContainsKey flag -> parseArgs' def (def.valueFuncs.[flag] state arg) tail |
19 | - | "--creds", fun state v -> {state with storedCredsFile = v} |
19 | + | | arg :: tail -> parseArgs' def (def.bareFunc state arg) tail |
20 | - | "--secrets", fun state v -> {state with secretsFile = v} |
20 | + | | [] -> state |
21 | - | ] |
21 | + | |
22 | let fromDefinition def argv = parseArgs' def def.initialState (List.ofArray argv) | |
23 | - | let rec parseArgs' state = function |
23 | + | |
24 | - | | flag :: tail when flagFuncs.ContainsKey flag -> parseArgs' (flagFuncs.[flag] state) tail |
24 | + | |
25 | - | | flag :: v :: tail when valueFuncs.ContainsKey flag -> parseArgs' (valueFuncs.[flag] state v) tail |
25 | + | module Main = |
26 | - | | item :: tail -> failwith "Unexpected argument \"%s\" in command line" |
26 | + | |
27 | - | | [] -> state |
27 | + | type Options = { |
28 | creds : string | |
29 | - | let parseArgs = parseArgs' OptionBag.Default |
29 | + | secrets : string |
30 | outputs : string list | |
31 | } | |
32 | ||
33 | let parseOpts = ArgParse.fromDefinition { | |
34 | initialState = | |
35 | { creds = "stored_credentials.json" | |
36 | secrets = "client_secrets.json" | |
37 | outputs = [] } | |
38 | bareFunc = fun opts v -> {opts with outputs = v :: opts.outputs } | |
39 | flagFuncs = | |
40 | Map [ | |
41 | "-h", fun opts -> failwith "Would display help here" | |
42 | ] | |
43 | valueFuncs = | |
44 | Map [ | |
45 | "--creds", fun opts v -> {opts with creds = v} | |
46 | "--secrets", fun opts v -> {opts with secrets = v} | |
47 | ] | |
48 | } | |
49 | ||
50 | [<EntryPoint>] | |
51 | let main argv = | |
52 | let opts = parseOpts argv | |
53 | printfn "%A" opts | |
54 | 0 |