1 /** 2 * Copyright: Copyright (c) 2010-2011 Jacob Carlborg. All rights reserved. 3 * Authors: Jacob Carlborg 4 * Version: Initial created: Nov 8, 2010 5 * License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0) 6 */ 7 module dvm.dvm.CommandManager; 8 9 import std.algorithm : sort; 10 import std.array : array; 11 import std.format : format; 12 import std.range : join, repeat; 13 import std.conv : to; 14 15 import dvm.commands.Command; 16 import dvm.dvm.Options; 17 18 class CommandManager 19 { 20 private static CommandManager instance_; 21 private Command[string] commands; 22 23 private this () {} 24 25 static CommandManager instance () 26 { 27 if (instance_) 28 return instance_; 29 30 return instance_ = new typeof(this); 31 } 32 33 void register (string command) 34 { 35 commands[command] = null; 36 } 37 38 Command opIndex (string command) 39 { 40 if (auto c = command in commands) 41 if (*c) 42 return *c; 43 44 auto c = createCommand(command); 45 commands[command] = c; 46 47 return c; 48 } 49 50 string[] names () 51 { 52 return commands.keys.sort.array; 53 } 54 55 string summary () 56 { 57 string result; 58 59 auto len = lenghtOfLongestCommand; 60 auto options = Options.instance; 61 62 foreach (name, _ ; commands) 63 { 64 auto command = this[name]; 65 result ~= format("%s%s%s%s%s\n", 66 options.indentation, 67 command.name, 68 " ".repeat(len - command.name.length).join, 69 options.indentation.repeat(options.numberOfIndentations).join, 70 command.summary); 71 } 72 73 return result; 74 } 75 76 private Command createCommand (string command) 77 { 78 return cast(Command) ClassInfo.find(command).create; 79 } 80 81 private size_t lenghtOfLongestCommand () 82 { 83 size_t len; 84 85 foreach (name, _ ; commands) 86 { 87 auto command = this[name]; 88 89 if (command.name.length > len) 90 len = command.name.length; 91 } 92 93 return len; 94 } 95 }