1 module sily.getopt; 2 3 import std.getopt: Option; 4 import std.algorithm: max; 5 import std.stdio: writefln; 6 7 /** 8 * Prints passed **Option**s and text in aligned manner on stdout, i.e: 9 * ``` 10 * A simple cli tool 11 * 12 * Usage: 13 * scli [options] [script] \ 14 * scli run [script] 15 * 16 * Options: 17 * -h, --help This help information. \ 18 * -c, --check Check syntax without running. \ 19 * --quiet Run silently (no output). 20 * Commands: 21 * run Runs script. \ 22 * compile Compiles script. 23 * ``` 24 * Params: 25 * text = Text to be printed at the beginning of the help output 26 * usage = Usage string 27 * com = Commands 28 * opt = The **Option** extracted from the **getopt** parameter 29 */ 30 void printGetopt(string text, string usage, Commands[] com, Option[] opt) { 31 size_t maxLen = 0; 32 33 foreach (it; opt) { 34 int sep = it.optShort == "" ? 0 : 2; 35 maxLen = max(maxLen, it.optShort.length + it.optLong.length + sep); 36 } 37 38 foreach (it; com) { 39 maxLen = max(maxLen, it.name.length); 40 } 41 42 if (text != "") { 43 writefln(text); 44 } 45 46 if (usage != "") { 47 if (text != "") writefln(""); 48 writefln("Usage:"); 49 writefln(" " ~ usage); 50 } 51 52 if (com.length != 0) { 53 if (text != "" || usage != "") writefln(""); 54 writefln("Options:"); 55 } 56 57 foreach (it; opt) { 58 // writefln("%*s %*s%s%s", 59 // shortLen, it.optShort, 60 // longLen, it.optLong, 61 // it.required ? " Required: " : " ", it.help); 62 string opts = it.optShort ~ (it.optShort == "" ? "" : ", ") ~ it.optLong; 63 writefln(" %-*s %s", maxLen, opts, it.help); 64 } 65 66 if (com.length != 0) { 67 if (text != "" || usage != "" || com.length != 0) writefln(""); 68 writefln("Commands:"); 69 } 70 71 foreach (it; com) { 72 writefln(" %-*s %s", maxLen, it.name, it.help); 73 } 74 } 75 76 struct Commands { 77 string name; 78 string help; 79 }