CommandConsole.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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.Xml;
  29. using System.Collections.Generic;
  30. using System.Diagnostics;
  31. using System.Reflection;
  32. using System.Text;
  33. using System.Text.RegularExpressions;
  34. using System.Threading;
  35. using log4net;
  36. using OpenSim.Framework;
  37. namespace OpenSim.Framework.Console
  38. {
  39. public class Commands : ICommands
  40. {
  41. /// <summary>
  42. /// Encapsulates a command that can be invoked from the console
  43. /// </summary>
  44. private class CommandInfo
  45. {
  46. /// <value>
  47. /// The module from which this command comes
  48. /// </value>
  49. public string module;
  50. /// <value>
  51. /// Whether the module is shared
  52. /// </value>
  53. public bool shared;
  54. /// <value>
  55. /// Very short BNF description
  56. /// </value>
  57. public string help_text;
  58. /// <value>
  59. /// Longer one line help text
  60. /// </value>
  61. public string long_help;
  62. /// <value>
  63. /// Full descriptive help for this command
  64. /// </value>
  65. public string descriptive_help;
  66. /// <value>
  67. /// The method to invoke for this command
  68. /// </value>
  69. public List<CommandDelegate> fn;
  70. }
  71. /// <value>
  72. /// Commands organized by keyword in a tree
  73. /// </value>
  74. private Dictionary<string, object> tree =
  75. new Dictionary<string, object>();
  76. /// <summary>
  77. /// Get help for the given help string
  78. /// </summary>
  79. /// <param name="helpParts">Parsed parts of the help string. If empty then general help is returned.</param>
  80. /// <returns></returns>
  81. public List<string> GetHelp(string[] cmd)
  82. {
  83. List<string> help = new List<string>();
  84. List<string> helpParts = new List<string>(cmd);
  85. // Remove initial help keyword
  86. helpParts.RemoveAt(0);
  87. // General help
  88. if (helpParts.Count == 0)
  89. {
  90. help.AddRange(CollectHelp(tree));
  91. help.Sort();
  92. }
  93. else
  94. {
  95. help.AddRange(CollectHelp(helpParts));
  96. }
  97. return help;
  98. }
  99. /// <summary>
  100. /// See if we can find the requested command in order to display longer help
  101. /// </summary>
  102. /// <param name="helpParts"></param>
  103. /// <returns></returns>
  104. private List<string> CollectHelp(List<string> helpParts)
  105. {
  106. string originalHelpRequest = string.Join(" ", helpParts.ToArray());
  107. List<string> help = new List<string>();
  108. Dictionary<string, object> dict = tree;
  109. while (helpParts.Count > 0)
  110. {
  111. string helpPart = helpParts[0];
  112. if (!dict.ContainsKey(helpPart))
  113. break;
  114. //m_log.Debug("Found {0}", helpParts[0]);
  115. if (dict[helpPart] is Dictionary<string, Object>)
  116. dict = (Dictionary<string, object>)dict[helpPart];
  117. helpParts.RemoveAt(0);
  118. }
  119. // There was a command for the given help string
  120. if (dict.ContainsKey(String.Empty))
  121. {
  122. CommandInfo commandInfo = (CommandInfo)dict[String.Empty];
  123. help.Add(commandInfo.help_text);
  124. help.Add(commandInfo.long_help);
  125. string descriptiveHelp = commandInfo.descriptive_help;
  126. // If we do have some descriptive help then insert a spacing line before and after for readability.
  127. if (descriptiveHelp != string.Empty)
  128. help.Add(string.Empty);
  129. help.Add(commandInfo.descriptive_help);
  130. if (descriptiveHelp != string.Empty)
  131. help.Add(string.Empty);
  132. }
  133. else
  134. {
  135. help.Add(string.Format("No help is available for {0}", originalHelpRequest));
  136. }
  137. return help;
  138. }
  139. private List<string> CollectHelp(Dictionary<string, object> dict)
  140. {
  141. List<string> result = new List<string>();
  142. foreach (KeyValuePair<string, object> kvp in dict)
  143. {
  144. if (kvp.Value is Dictionary<string, Object>)
  145. {
  146. result.AddRange(CollectHelp((Dictionary<string, Object>)kvp.Value));
  147. }
  148. else
  149. {
  150. if (((CommandInfo)kvp.Value).long_help != String.Empty)
  151. result.Add(((CommandInfo)kvp.Value).help_text+" - "+
  152. ((CommandInfo)kvp.Value).long_help);
  153. }
  154. }
  155. return result;
  156. }
  157. /// <summary>
  158. /// Add a command to those which can be invoked from the console.
  159. /// </summary>
  160. /// <param name="module"></param>
  161. /// <param name="command"></param>
  162. /// <param name="help"></param>
  163. /// <param name="longhelp"></param>
  164. /// <param name="fn"></param>
  165. public void AddCommand(string module, bool shared, string command,
  166. string help, string longhelp, CommandDelegate fn)
  167. {
  168. AddCommand(module, shared, command, help, longhelp, String.Empty, fn);
  169. }
  170. /// <summary>
  171. /// Add a command to those which can be invoked from the console.
  172. /// </summary>
  173. /// <param name="module"></param>
  174. /// <param name="command"></param>
  175. /// <param name="help"></param>
  176. /// <param name="longhelp"></param>
  177. /// <param name="descriptivehelp"></param>
  178. /// <param name="fn"></param>
  179. public void AddCommand(string module, bool shared, string command,
  180. string help, string longhelp, string descriptivehelp,
  181. CommandDelegate fn)
  182. {
  183. string[] parts = Parser.Parse(command);
  184. Dictionary<string, Object> current = tree;
  185. foreach (string s in parts)
  186. {
  187. if (current.ContainsKey(s))
  188. {
  189. if (current[s] is Dictionary<string, Object>)
  190. {
  191. current = (Dictionary<string, Object>)current[s];
  192. }
  193. else
  194. return;
  195. }
  196. else
  197. {
  198. current[s] = new Dictionary<string, Object>();
  199. current = (Dictionary<string, Object>)current[s];
  200. }
  201. }
  202. CommandInfo info;
  203. if (current.ContainsKey(String.Empty))
  204. {
  205. info = (CommandInfo)current[String.Empty];
  206. if (!info.shared && !info.fn.Contains(fn))
  207. info.fn.Add(fn);
  208. return;
  209. }
  210. info = new CommandInfo();
  211. info.module = module;
  212. info.shared = shared;
  213. info.help_text = help;
  214. info.long_help = longhelp;
  215. info.descriptive_help = descriptivehelp;
  216. info.fn = new List<CommandDelegate>();
  217. info.fn.Add(fn);
  218. current[String.Empty] = info;
  219. }
  220. public string[] FindNextOption(string[] cmd, bool term)
  221. {
  222. Dictionary<string, object> current = tree;
  223. int remaining = cmd.Length;
  224. foreach (string s in cmd)
  225. {
  226. remaining--;
  227. List<string> found = new List<string>();
  228. foreach (string opt in current.Keys)
  229. {
  230. if (remaining > 0 && opt == s)
  231. {
  232. found.Clear();
  233. found.Add(opt);
  234. break;
  235. }
  236. if (opt.StartsWith(s))
  237. {
  238. found.Add(opt);
  239. }
  240. }
  241. if (found.Count == 1 && (remaining != 0 || term))
  242. {
  243. current = (Dictionary<string, object>)current[found[0]];
  244. }
  245. else if (found.Count > 0)
  246. {
  247. return found.ToArray();
  248. }
  249. else
  250. {
  251. break;
  252. // return new string[] {"<cr>"};
  253. }
  254. }
  255. if (current.Count > 1)
  256. {
  257. List<string> choices = new List<string>();
  258. bool addcr = false;
  259. foreach (string s in current.Keys)
  260. {
  261. if (s == String.Empty)
  262. {
  263. CommandInfo ci = (CommandInfo)current[String.Empty];
  264. if (ci.fn.Count != 0)
  265. addcr = true;
  266. }
  267. else
  268. choices.Add(s);
  269. }
  270. if (addcr)
  271. choices.Add("<cr>");
  272. return choices.ToArray();
  273. }
  274. if (current.ContainsKey(String.Empty))
  275. return new string[] { "Command help: "+((CommandInfo)current[String.Empty]).help_text};
  276. return new string[] { new List<string>(current.Keys)[0] };
  277. }
  278. public string[] Resolve(string[] cmd)
  279. {
  280. string[] result = cmd;
  281. int index = -1;
  282. Dictionary<string, object> current = tree;
  283. foreach (string s in cmd)
  284. {
  285. index++;
  286. List<string> found = new List<string>();
  287. foreach (string opt in current.Keys)
  288. {
  289. if (opt == s)
  290. {
  291. found.Clear();
  292. found.Add(opt);
  293. break;
  294. }
  295. if (opt.StartsWith(s))
  296. {
  297. found.Add(opt);
  298. }
  299. }
  300. if (found.Count == 1)
  301. {
  302. result[index] = found[0];
  303. current = (Dictionary<string, object>)current[found[0]];
  304. }
  305. else if (found.Count > 0)
  306. {
  307. return new string[0];
  308. }
  309. else
  310. {
  311. break;
  312. }
  313. }
  314. if (current.ContainsKey(String.Empty))
  315. {
  316. CommandInfo ci = (CommandInfo)current[String.Empty];
  317. if (ci.fn.Count == 0)
  318. return new string[0];
  319. foreach (CommandDelegate fn in ci.fn)
  320. {
  321. if (fn != null)
  322. fn(ci.module, result);
  323. else
  324. return new string[0];
  325. }
  326. return result;
  327. }
  328. return new string[0];
  329. }
  330. public XmlElement GetXml(XmlDocument doc)
  331. {
  332. CommandInfo help = (CommandInfo)((Dictionary<string, object>)tree["help"])[String.Empty];
  333. ((Dictionary<string, object>)tree["help"]).Remove(string.Empty);
  334. if (((Dictionary<string, object>)tree["help"]).Count == 0)
  335. tree.Remove("help");
  336. CommandInfo quit = (CommandInfo)((Dictionary<string, object>)tree["quit"])[String.Empty];
  337. ((Dictionary<string, object>)tree["quit"]).Remove(string.Empty);
  338. if (((Dictionary<string, object>)tree["quit"]).Count == 0)
  339. tree.Remove("quit");
  340. XmlElement root = doc.CreateElement("", "HelpTree", "");
  341. ProcessTreeLevel(tree, root, doc);
  342. if (!tree.ContainsKey("help"))
  343. tree["help"] = (object) new Dictionary<string, object>();
  344. ((Dictionary<string, object>)tree["help"])[String.Empty] = help;
  345. if (!tree.ContainsKey("quit"))
  346. tree["quit"] = (object) new Dictionary<string, object>();
  347. ((Dictionary<string, object>)tree["quit"])[String.Empty] = quit;
  348. return root;
  349. }
  350. private void ProcessTreeLevel(Dictionary<string, object> level, XmlElement xml, XmlDocument doc)
  351. {
  352. foreach (KeyValuePair<string, object> kvp in level)
  353. {
  354. if (kvp.Value is Dictionary<string, Object>)
  355. {
  356. XmlElement next = doc.CreateElement("", "Level", "");
  357. next.SetAttribute("Name", kvp.Key);
  358. xml.AppendChild(next);
  359. ProcessTreeLevel((Dictionary<string, object>)kvp.Value, next, doc);
  360. }
  361. else
  362. {
  363. CommandInfo c = (CommandInfo)kvp.Value;
  364. XmlElement cmd = doc.CreateElement("", "Command", "");
  365. XmlElement e;
  366. e = doc.CreateElement("", "Module", "");
  367. cmd.AppendChild(e);
  368. e.AppendChild(doc.CreateTextNode(c.module));
  369. e = doc.CreateElement("", "Shared", "");
  370. cmd.AppendChild(e);
  371. e.AppendChild(doc.CreateTextNode(c.shared.ToString()));
  372. e = doc.CreateElement("", "HelpText", "");
  373. cmd.AppendChild(e);
  374. e.AppendChild(doc.CreateTextNode(c.help_text));
  375. e = doc.CreateElement("", "LongHelp", "");
  376. cmd.AppendChild(e);
  377. e.AppendChild(doc.CreateTextNode(c.long_help));
  378. e = doc.CreateElement("", "Description", "");
  379. cmd.AppendChild(e);
  380. e.AppendChild(doc.CreateTextNode(c.descriptive_help));
  381. xml.AppendChild(cmd);
  382. }
  383. }
  384. }
  385. public void FromXml(XmlElement root, CommandDelegate fn)
  386. {
  387. CommandInfo help = (CommandInfo)((Dictionary<string, object>)tree["help"])[String.Empty];
  388. ((Dictionary<string, object>)tree["help"]).Remove(string.Empty);
  389. if (((Dictionary<string, object>)tree["help"]).Count == 0)
  390. tree.Remove("help");
  391. CommandInfo quit = (CommandInfo)((Dictionary<string, object>)tree["quit"])[String.Empty];
  392. ((Dictionary<string, object>)tree["quit"]).Remove(string.Empty);
  393. if (((Dictionary<string, object>)tree["quit"]).Count == 0)
  394. tree.Remove("quit");
  395. tree.Clear();
  396. ReadTreeLevel(tree, root, fn);
  397. if (!tree.ContainsKey("help"))
  398. tree["help"] = (object) new Dictionary<string, object>();
  399. ((Dictionary<string, object>)tree["help"])[String.Empty] = help;
  400. if (!tree.ContainsKey("quit"))
  401. tree["quit"] = (object) new Dictionary<string, object>();
  402. ((Dictionary<string, object>)tree["quit"])[String.Empty] = quit;
  403. }
  404. private void ReadTreeLevel(Dictionary<string, object> level, XmlNode node, CommandDelegate fn)
  405. {
  406. Dictionary<string, object> next;
  407. string name;
  408. XmlNodeList nodeL = node.ChildNodes;
  409. XmlNodeList cmdL;
  410. CommandInfo c;
  411. foreach (XmlNode part in nodeL)
  412. {
  413. switch (part.Name)
  414. {
  415. case "Level":
  416. name = ((XmlElement)part).GetAttribute("Name");
  417. next = new Dictionary<string, object>();
  418. level[name] = next;
  419. ReadTreeLevel(next, part, fn);
  420. break;
  421. case "Command":
  422. cmdL = part.ChildNodes;
  423. c = new CommandInfo();
  424. foreach (XmlNode cmdPart in cmdL)
  425. {
  426. switch (cmdPart.Name)
  427. {
  428. case "Module":
  429. c.module = cmdPart.InnerText;
  430. break;
  431. case "Shared":
  432. c.shared = Convert.ToBoolean(cmdPart.InnerText);
  433. break;
  434. case "HelpText":
  435. c.help_text = cmdPart.InnerText;
  436. break;
  437. case "LongHelp":
  438. c.long_help = cmdPart.InnerText;
  439. break;
  440. case "Description":
  441. c.descriptive_help = cmdPart.InnerText;
  442. break;
  443. }
  444. }
  445. c.fn = new List<CommandDelegate>();
  446. c.fn.Add(fn);
  447. level[String.Empty] = c;
  448. break;
  449. }
  450. }
  451. }
  452. }
  453. public class Parser
  454. {
  455. // If an unquoted portion ends with an element matching this regex
  456. // and the next element contains a space, then we have stripped
  457. // embedded quotes that should not have been stripped
  458. private static Regex optionRegex = new Regex("^--[a-zA-Z0-9-]+=$");
  459. public static string[] Parse(string text)
  460. {
  461. List<string> result = new List<string>();
  462. int index;
  463. string[] unquoted = text.Split(new char[] {'"'});
  464. for (index = 0 ; index < unquoted.Length ; index++)
  465. {
  466. if (index % 2 == 0)
  467. {
  468. string[] words = unquoted[index].Split(new char[] {' '});
  469. bool option = false;
  470. foreach (string w in words)
  471. {
  472. if (w != String.Empty)
  473. {
  474. if (optionRegex.Match(w) == Match.Empty)
  475. option = false;
  476. else
  477. option = true;
  478. result.Add(w);
  479. }
  480. }
  481. // The last item matched the regex, put the quotes back
  482. if (option)
  483. {
  484. // If the line ended with it, don't do anything
  485. if (index < (unquoted.Length - 1))
  486. {
  487. // Get and remove the option name
  488. string optionText = result[result.Count - 1];
  489. result.RemoveAt(result.Count - 1);
  490. // Add the quoted value back
  491. optionText += "\"" + unquoted[index + 1] + "\"";
  492. // Push the result into our return array
  493. result.Add(optionText);
  494. // Skip the already used value
  495. index++;
  496. }
  497. }
  498. }
  499. else
  500. {
  501. result.Add(unquoted[index]);
  502. }
  503. }
  504. return result.ToArray();
  505. }
  506. }
  507. /// <summary>
  508. /// A console that processes commands internally
  509. /// </summary>
  510. public class CommandConsole : ConsoleBase, ICommandConsole
  511. {
  512. // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  513. public ICommands Commands { get; private set; }
  514. public CommandConsole(string defaultPrompt) : base(defaultPrompt)
  515. {
  516. Commands = new Commands();
  517. Commands.AddCommand("console", false, "help", "help [<command>]",
  518. "Get general command list or more detailed help on a specific command", Help);
  519. }
  520. private void Help(string module, string[] cmd)
  521. {
  522. List<string> help = Commands.GetHelp(cmd);
  523. foreach (string s in help)
  524. Output(s);
  525. }
  526. /// <summary>
  527. /// Display a command prompt on the console and wait for user input
  528. /// </summary>
  529. public void Prompt()
  530. {
  531. string line = ReadLine(m_defaultPrompt + "# ", true, true);
  532. if (line != String.Empty)
  533. Output("Invalid command");
  534. }
  535. public void RunCommand(string cmd)
  536. {
  537. string[] parts = Parser.Parse(cmd);
  538. Commands.Resolve(parts);
  539. }
  540. public override string ReadLine(string p, bool isCommand, bool e)
  541. {
  542. System.Console.Write("{0}", p);
  543. string cmdinput = System.Console.ReadLine();
  544. if (isCommand)
  545. {
  546. string[] cmd = Commands.Resolve(Parser.Parse(cmdinput));
  547. if (cmd.Length != 0)
  548. {
  549. int i;
  550. for (i=0 ; i < cmd.Length ; i++)
  551. {
  552. if (cmd[i].Contains(" "))
  553. cmd[i] = "\"" + cmd[i] + "\"";
  554. }
  555. return String.Empty;
  556. }
  557. }
  558. return cmdinput;
  559. }
  560. }
  561. }