CommandConsole.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Diagnostics;
  30. using System.Reflection;
  31. using System.Text;
  32. using System.Threading;
  33. using log4net;
  34. namespace OpenSim.Framework.Console
  35. {
  36. public delegate void CommandDelegate(string module, string[] cmd);
  37. public class Commands
  38. {
  39. /// <summary>
  40. /// Encapsulates a command that can be invoked from the console
  41. /// </summary>
  42. private class CommandInfo
  43. {
  44. /// <value>
  45. /// The module from which this command comes
  46. /// </value>
  47. public string module;
  48. /// <value>
  49. /// Whether the module is shared
  50. /// </value>
  51. public bool shared;
  52. /// <value>
  53. /// Very short BNF description
  54. /// </value>
  55. public string help_text;
  56. /// <value>
  57. /// Longer one line help text
  58. /// </value>
  59. public string long_help;
  60. /// <value>
  61. /// Full descriptive help for this command
  62. /// </value>
  63. public string descriptive_help;
  64. /// <value>
  65. /// The method to invoke for this command
  66. /// </value>
  67. public List<CommandDelegate> fn;
  68. }
  69. /// <value>
  70. /// Commands organized by keyword in a tree
  71. /// </value>
  72. private Dictionary<string, object> tree =
  73. new Dictionary<string, object>();
  74. /// <summary>
  75. /// Get help for the given help string
  76. /// </summary>
  77. /// <param name="helpParts">Parsed parts of the help string. If empty then general help is returned.</param>
  78. /// <returns></returns>
  79. public List<string> GetHelp(string[] cmd)
  80. {
  81. List<string> help = new List<string>();
  82. List<string> helpParts = new List<string>(cmd);
  83. // Remove initial help keyword
  84. helpParts.RemoveAt(0);
  85. // General help
  86. if (helpParts.Count == 0)
  87. {
  88. help.AddRange(CollectHelp(tree));
  89. help.Sort();
  90. }
  91. else
  92. {
  93. help.AddRange(CollectHelp(helpParts));
  94. }
  95. return help;
  96. }
  97. /// <summary>
  98. /// See if we can find the requested command in order to display longer help
  99. /// </summary>
  100. /// <param name="helpParts"></param>
  101. /// <returns></returns>
  102. private List<string> CollectHelp(List<string> helpParts)
  103. {
  104. string originalHelpRequest = string.Join(" ", helpParts.ToArray());
  105. List<string> help = new List<string>();
  106. Dictionary<string, object> dict = tree;
  107. while (helpParts.Count > 0)
  108. {
  109. string helpPart = helpParts[0];
  110. if (!dict.ContainsKey(helpPart))
  111. break;
  112. //m_log.Debug("Found {0}", helpParts[0]);
  113. if (dict[helpPart] is Dictionary<string, Object>)
  114. dict = (Dictionary<string, object>)dict[helpPart];
  115. helpParts.RemoveAt(0);
  116. }
  117. // There was a command for the given help string
  118. if (dict.ContainsKey(String.Empty))
  119. {
  120. CommandInfo commandInfo = (CommandInfo)dict[String.Empty];
  121. help.Add(commandInfo.help_text);
  122. help.Add(commandInfo.long_help);
  123. help.Add(commandInfo.descriptive_help);
  124. }
  125. else
  126. {
  127. help.Add(string.Format("No help is available for {0}", originalHelpRequest));
  128. }
  129. return help;
  130. }
  131. private List<string> CollectHelp(Dictionary<string, object> dict)
  132. {
  133. List<string> result = new List<string>();
  134. foreach (KeyValuePair<string, object> kvp in dict)
  135. {
  136. if (kvp.Value is Dictionary<string, Object>)
  137. {
  138. result.AddRange(CollectHelp((Dictionary<string, Object>)kvp.Value));
  139. }
  140. else
  141. {
  142. if (((CommandInfo)kvp.Value).long_help != String.Empty)
  143. result.Add(((CommandInfo)kvp.Value).help_text+" - "+
  144. ((CommandInfo)kvp.Value).long_help);
  145. }
  146. }
  147. return result;
  148. }
  149. /// <summary>
  150. /// Add a command to those which can be invoked from the console.
  151. /// </summary>
  152. /// <param name="module"></param>
  153. /// <param name="command"></param>
  154. /// <param name="help"></param>
  155. /// <param name="longhelp"></param>
  156. /// <param name="fn"></param>
  157. public void AddCommand(string module, bool shared, string command,
  158. string help, string longhelp, CommandDelegate fn)
  159. {
  160. AddCommand(module, shared, command, help, longhelp,
  161. String.Empty, fn);
  162. }
  163. /// <summary>
  164. /// Add a command to those which can be invoked from the console.
  165. /// </summary>
  166. /// <param name="module"></param>
  167. /// <param name="command"></param>
  168. /// <param name="help"></param>
  169. /// <param name="longhelp"></param>
  170. /// <param name="descriptivehelp"></param>
  171. /// <param name="fn"></param>
  172. public void AddCommand(string module, bool shared, string command,
  173. string help, string longhelp, string descriptivehelp,
  174. CommandDelegate fn)
  175. {
  176. string[] parts = Parser.Parse(command);
  177. Dictionary<string, Object> current = tree;
  178. foreach (string s in parts)
  179. {
  180. if (current.ContainsKey(s))
  181. {
  182. if (current[s] is Dictionary<string, Object>)
  183. {
  184. current = (Dictionary<string, Object>)current[s];
  185. }
  186. else
  187. return;
  188. }
  189. else
  190. {
  191. current[s] = new Dictionary<string, Object>();
  192. current = (Dictionary<string, Object>)current[s];
  193. }
  194. }
  195. CommandInfo info;
  196. if (current.ContainsKey(String.Empty))
  197. {
  198. info = (CommandInfo)current[String.Empty];
  199. if (!info.shared && !info.fn.Contains(fn))
  200. info.fn.Add(fn);
  201. return;
  202. }
  203. info = new CommandInfo();
  204. info.module = module;
  205. info.shared = shared;
  206. info.help_text = help;
  207. info.long_help = longhelp;
  208. info.descriptive_help = descriptivehelp;
  209. info.fn = new List<CommandDelegate>();
  210. info.fn.Add(fn);
  211. current[String.Empty] = info;
  212. }
  213. public string[] FindNextOption(string[] cmd, bool term)
  214. {
  215. Dictionary<string, object> current = tree;
  216. int remaining = cmd.Length;
  217. foreach (string s in cmd)
  218. {
  219. remaining--;
  220. List<string> found = new List<string>();
  221. foreach (string opt in current.Keys)
  222. {
  223. if (remaining > 0 && opt == s)
  224. {
  225. found.Clear();
  226. found.Add(opt);
  227. break;
  228. }
  229. if (opt.StartsWith(s))
  230. {
  231. found.Add(opt);
  232. }
  233. }
  234. if (found.Count == 1 && (remaining != 0 || term))
  235. {
  236. current = (Dictionary<string, object>)current[found[0]];
  237. }
  238. else if (found.Count > 0)
  239. {
  240. return found.ToArray();
  241. }
  242. else
  243. {
  244. break;
  245. // return new string[] {"<cr>"};
  246. }
  247. }
  248. if (current.Count > 1)
  249. {
  250. List<string> choices = new List<string>();
  251. bool addcr = false;
  252. foreach (string s in current.Keys)
  253. {
  254. if (s == String.Empty)
  255. {
  256. CommandInfo ci = (CommandInfo)current[String.Empty];
  257. if (ci.fn.Count != 0)
  258. addcr = true;
  259. }
  260. else
  261. choices.Add(s);
  262. }
  263. if (addcr)
  264. choices.Add("<cr>");
  265. return choices.ToArray();
  266. }
  267. if (current.ContainsKey(String.Empty))
  268. return new string[] { "Command help: "+((CommandInfo)current[String.Empty]).help_text};
  269. return new string[] { new List<string>(current.Keys)[0] };
  270. }
  271. public string[] Resolve(string[] cmd)
  272. {
  273. string[] result = cmd;
  274. int index = -1;
  275. Dictionary<string, object> current = tree;
  276. foreach (string s in cmd)
  277. {
  278. index++;
  279. List<string> found = new List<string>();
  280. foreach (string opt in current.Keys)
  281. {
  282. if (opt == s)
  283. {
  284. found.Clear();
  285. found.Add(opt);
  286. break;
  287. }
  288. if (opt.StartsWith(s))
  289. {
  290. found.Add(opt);
  291. }
  292. }
  293. if (found.Count == 1)
  294. {
  295. result[index] = found[0];
  296. current = (Dictionary<string, object>)current[found[0]];
  297. }
  298. else if (found.Count > 0)
  299. {
  300. return new string[0];
  301. }
  302. else
  303. {
  304. break;
  305. }
  306. }
  307. if (current.ContainsKey(String.Empty))
  308. {
  309. CommandInfo ci = (CommandInfo)current[String.Empty];
  310. if (ci.fn.Count == 0)
  311. return new string[0];
  312. foreach (CommandDelegate fn in ci.fn)
  313. {
  314. if (fn != null)
  315. fn(ci.module, result);
  316. else
  317. return new string[0];
  318. }
  319. return result;
  320. }
  321. return new string[0];
  322. }
  323. }
  324. public class Parser
  325. {
  326. public static string[] Parse(string text)
  327. {
  328. List<string> result = new List<string>();
  329. int index;
  330. string[] unquoted = text.Split(new char[] {'"'});
  331. for (index = 0 ; index < unquoted.Length ; index++)
  332. {
  333. if (index % 2 == 0)
  334. {
  335. string[] words = unquoted[index].Split(new char[] {' '});
  336. foreach (string w in words)
  337. {
  338. if (w != String.Empty)
  339. result.Add(w);
  340. }
  341. }
  342. else
  343. {
  344. result.Add(unquoted[index]);
  345. }
  346. }
  347. return result.ToArray();
  348. }
  349. }
  350. // A console that processes commands internally
  351. //
  352. public class CommandConsole : ConsoleBase
  353. {
  354. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  355. public Commands Commands = new Commands();
  356. public CommandConsole(string defaultPrompt) : base(defaultPrompt)
  357. {
  358. Commands.AddCommand("console", false, "help", "help [<command>]",
  359. "Get general command list or more detailed help on a specific command", Help);
  360. }
  361. private void Help(string module, string[] cmd)
  362. {
  363. List<string> help = Commands.GetHelp(cmd);
  364. foreach (string s in help)
  365. Output(s);
  366. }
  367. public void Prompt()
  368. {
  369. string line = ReadLine(m_defaultPrompt, true, true);
  370. if (line != String.Empty)
  371. {
  372. m_log.Info("[CONSOLE] Invalid command");
  373. }
  374. }
  375. public void RunCommand(string cmd)
  376. {
  377. string[] parts = Parser.Parse(cmd);
  378. Commands.Resolve(parts);
  379. }
  380. public override string ReadLine(string p, bool isCommand, bool e)
  381. {
  382. System.Console.Write("{0}", prompt);
  383. string cmdinput = System.Console.ReadLine();
  384. if (isCommand)
  385. {
  386. string[] cmd = Commands.Resolve(Parser.Parse(cmdinput));
  387. if (cmd.Length != 0)
  388. {
  389. int i;
  390. for (i=0 ; i < cmd.Length ; i++)
  391. {
  392. if (cmd[i].Contains(" "))
  393. cmd[i] = "\"" + cmd[i] + "\"";
  394. }
  395. return String.Empty;
  396. }
  397. }
  398. return cmdinput;
  399. }
  400. }
  401. }