|
| 1 | +module GlobalOptionsTest |
| 2 | + |
| 3 | +open System.IO |
| 4 | +open FSharp.SystemCommandLine |
| 5 | +open Input |
| 6 | +open NUnit.Framework |
| 7 | +open Swensen.Unquote |
| 8 | +open Utils |
| 9 | + |
| 10 | +module Global = |
| 11 | + let enableLogging = option "--enable-logging" |> def false |
| 12 | + let logFile = option "--log-file" |> def (FileInfo @"c:\temp\default.log") |
| 13 | + |
| 14 | + type Options = { EnableLogging: bool; LogFile: FileInfo } |
| 15 | + |
| 16 | + let options: ActionInput seq = [ enableLogging; logFile ] |
| 17 | + |
| 18 | + let bind parseResult = |
| 19 | + { EnableLogging = enableLogging.GetValue parseResult |
| 20 | + LogFile = logFile.GetValue parseResult } |
| 21 | + |
| 22 | +let listCmd = |
| 23 | + let action (ctx, dir: DirectoryInfo) = |
| 24 | + let options = Global.bind ctx.ParseResult |
| 25 | + if options.EnableLogging then |
| 26 | + printfn $"Logging enabled to {options.LogFile.FullName}" |
| 27 | + |
| 28 | + if dir.Exists then |
| 29 | + dir.EnumerateFiles() |
| 30 | + |> Seq.iter (fun f -> printfn "%s" f.FullName) |
| 31 | + else |
| 32 | + printfn $"{dir.FullName} does not exist." |
| 33 | + |
| 34 | + let dir = argument "directory" |> def (DirectoryInfo @"c:\default") |
| 35 | + |
| 36 | + command "list" { |
| 37 | + description "lists contents of a directory" |
| 38 | + inputs (context, dir) |
| 39 | + setAction action |
| 40 | + addAlias "ls" |
| 41 | + } |
| 42 | + |
| 43 | +let deleteCmd = |
| 44 | + let action (ctx, dir: DirectoryInfo, recursive: bool) = |
| 45 | + let options = Global.bind ctx.ParseResult |
| 46 | + if options.EnableLogging then |
| 47 | + printfn $"Logging enabled to {options.LogFile.FullName}" |
| 48 | + |
| 49 | + if dir.Exists then |
| 50 | + if recursive then |
| 51 | + printfn $"Recursively deleting {dir.FullName}" |
| 52 | + else |
| 53 | + printfn $"Deleting {dir.FullName}" |
| 54 | + else |
| 55 | + printfn $"{dir.FullName} does not exist." |
| 56 | + |
| 57 | + let dir = argument "directory" |> def (DirectoryInfo @"c:\default") |
| 58 | + let recursive = option "--recursive" |> def false |
| 59 | + |
| 60 | + command "delete" { |
| 61 | + description "deletes a directory" |
| 62 | + inputs (context, dir, recursive) |
| 63 | + setAction action |
| 64 | + addAlias "del" |
| 65 | + } |
| 66 | + |
| 67 | +let ioCmd = |
| 68 | + command "io" { |
| 69 | + description "Contains IO related subcommands." |
| 70 | + noAction |
| 71 | + addCommands [ deleteCmd; listCmd ] |
| 72 | + } |
| 73 | + |
| 74 | +[<Test>] |
| 75 | +let ``01 - Global options with nested commands`` () = |
| 76 | + testRootCommand "io list \"c:/data/\" --enable-logging" { |
| 77 | + description "Contains IO related subcommands." |
| 78 | + noAction |
| 79 | + addGlobalOptions Global.options |
| 80 | + addCommand ioCmd |
| 81 | + } =! 0 |
0 commit comments