Recently, I discovered this Github page here and was pretty floored by the idea. Simply put, the writer documents the console application’s actions in comments and this library will parse them and return a list of key-value pairs containing the options that the user has selected.
Here’s some code from their example:
#nullable enable
using System;
using DocoptNet;
const string usage = @"Naval Fate.
Usage:
naval_fate.exe ship new <name>...
naval_fate.exe ship <name> move <x> <y> [--speed=<kn>]
naval_fate.exe ship shoot <x> <y>
naval_fate.exe mine (set|remove) <x> <y> [--moored | --drifting]
naval_fate.exe (-h | --help)
naval_fate.exe --version
Options:
-h --help Show this screen.
--version Show version.
--speed=<kn> Speed in knots [default: 10].
--moored Moored (anchored) mine.
--drifting Drifting mine.
";
var arguments = new Docopt().Apply(usage, args, version: "Naval Fate 2.0", exit: true)!;
foreach (var (key, value) in arguments)
Console.WriteLine("{0} = {1}", key, value);
Notice how the comment outlines how the console application should work. This is such a cool concept! Let’s look at the first line and see what gets returned:
naval_fate.exe ship new <name>...
The following gets returned if the user enters this:
- ship is a key and the value is a boolean
- new is a key and the value is a boolean
- <name> is a key and a string list is returned (note the ‘…’, this tells Docopt that it can be a list)
I will be using this for my next console application that I need to write. Please try it out! Bye!