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.array : array;
10 
11 import tango.text.convert.Format;
12 
13 import mambo.core._;
14 import mambo.util.Singleton;
15 
16 import dvm.commands.Command;
17 import dvm.dvm.Options;
18 
19 class CommandManager
20 {
21     mixin Singleton;
22 
23     private Command[string] commands;
24 
25     void register (string command)
26     {
27         commands[command] = null;
28     }
29 
30     Command opIndex (string command)
31     {
32         if (auto c = command in commands)
33             if (*c)
34                 return *c;
35 
36         auto c = createCommand(command);
37         commands[command] = c;
38 
39         return c;
40     }
41 
42     string[] names ()
43     {
44         return commands.keys.sort.array;
45     }
46 
47     string summary ()
48     {
49         string result;
50 
51         auto len = lenghtOfLongestCommand;
52         auto options = Options.instance;
53 
54         foreach (name, _ ; commands)
55         {
56             auto command = this[name];
57             result ~= Format("{}{}{}{}{}\n",
58                         options.indentation,
59                         command.name,
60                         " ".repeat(len - command.name.length),
61                         options.indentation.repeat(options.numberOfIndentations),
62                         command.summary);
63         }
64 
65         return result;
66     }
67 
68     private Command createCommand (string command)
69     {
70         return cast(Command) ClassInfo.find(command).create;
71     }
72 
73     private size_t lenghtOfLongestCommand ()
74     {
75         size_t len;
76 
77         foreach (name, _ ; commands)
78         {
79             auto command = this[name];
80 
81             if (command.name.length > len)
82                 len = command.name.length;
83         }
84 
85         return len;
86     }
87 }