AbstractCommand.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Quadarax.Foundation.Core.Console;
  6. using Quadarax.Foundation.Core.QConsole.Argument;
  7. using Quadarax.Foundation.Core.QConsole.Context;
  8. using Quadarax.Foundation.Core.QConsole.Extensions;
  9. using Quadarax.Foundation.Core.Value;
  10. namespace Quadarax.Foundation.Core.QConsole.Command.Base
  11. {
  12. public abstract class AbstractCommand
  13. {
  14. #region *** Enumerations ***
  15. public enum WriteTextSeverity
  16. {
  17. Info,
  18. Caption,
  19. Warning,
  20. Error,
  21. }
  22. #endregion
  23. #region *** Private Fields ***
  24. private Engine _engine;
  25. private IDictionary<string, AbstractArgument> _arguments;
  26. protected ICommandContext _context;
  27. #endregion
  28. #region *** Properties ***
  29. public abstract string Name { get; }
  30. public abstract string Description { get; }
  31. public virtual string Notes { get; set; }
  32. public virtual string Examples { get; set; }
  33. public virtual string CustomUsage { get; set; }
  34. public AbstractArgument[] Arguments => _arguments.Values.ToArray();
  35. protected Engine Engine => _engine;
  36. #endregion
  37. #region *** Constructor ***
  38. public AbstractCommand(Engine engine)
  39. {
  40. _engine = engine ?? throw new ArgumentNullException(nameof(engine));
  41. _arguments = new Dictionary<string, AbstractArgument>();
  42. _context = _engine.Context.CreateCommandContext();
  43. WriteDebugInfo($"Context for command '{Name}' created: {_context}");
  44. var args = SetupArguments();
  45. foreach (var arg in args)
  46. _arguments.Add(arg.Code, arg);
  47. Init();
  48. WriteDebugInfo($"Command '{Name}' has {_arguments.Count} arguments. Initialized.");
  49. }
  50. #endregion
  51. #region *** Public operations ***
  52. public Result Execute(string input)
  53. {
  54. ConsoleWriter writer = null;
  55. try
  56. {
  57. writer = new ConsoleWriter(ConsoleColor.Green);
  58. foreach (var arg in Arguments)
  59. arg.SetValueAsDefault();
  60. ParseInput(input);
  61. OnInitialize();
  62. if (_engine.Configuration.ShowStatusOnEveryCommand)
  63. ShowContextStatus(writer);
  64. OnValidateArguments();
  65. BeginExecute();
  66. var result = OnExecute();
  67. result = EndExecute(result);
  68. return result;
  69. }
  70. catch (Exception e)
  71. {
  72. return new Result(e);
  73. }
  74. finally
  75. {
  76. writer?.Dispose();
  77. }
  78. }
  79. public override string ToString()
  80. {
  81. return "Command: " + Name;
  82. }
  83. #endregion
  84. #region *** Private operations ***
  85. private void Init()
  86. {
  87. OnCommandInit();
  88. }
  89. private void ParseInput(string input)
  90. {
  91. //var args = input.Split(new[] {Engine.Configuration.CharacterNamedArgumentSeparator}, StringSplitOptions.RemoveEmptyEntries);
  92. var args = Split(input, Engine.Configuration.CharacterTextValueBraceSeparator, new[]
  93. {
  94. Engine.Configuration.CharacterNamedArgumentSeparator,
  95. Engine.Configuration.CharacterOrdinalArgumentSeparator
  96. });
  97. for (int i = 1; i < args.Length; i++)
  98. {
  99. var arg = args[i];
  100. var index = i - 1;
  101. WriteDebugInfo($"Parsing argument [index={index}] by value string '{arg}' in progress..");
  102. AbstractArgument argument = null;
  103. if (arg.StartsWith(Engine.Configuration.CharacterNamedArgumentSeparator))
  104. {
  105. //Named
  106. WriteDebugInfo("Detects argument as named.");
  107. var parsed = ParseNamedArgument(arg);
  108. if (!ContainsArgument(parsed.Item1))
  109. throw new Exception(
  110. $"Invalid argument '{Engine.Configuration.CharacterNamedArgumentSeparator}{parsed.Item1}' for this command.");
  111. argument = GetArgument(parsed.Item1);
  112. if (argument.IsPositional())
  113. if (!((OrdinalArgument)argument).IsCodeAllowed)
  114. throw new Exception($"Usage of ordinal argument '{argument.Code}' as named argument is not allowed!");
  115. if (argument.IsFlag())
  116. ((FlagArgument)argument).Set();
  117. else
  118. argument.Value.Set(parsed.Item2);
  119. }
  120. else
  121. {
  122. //Ordinal
  123. WriteDebugInfo("Detects argument as ordinal.");
  124. argument = GetArgument(index);
  125. if (argument == null)
  126. throw new Exception(
  127. $"Invalid ordinal argument '{arg}' at position {index} for this command.");
  128. argument.Value.Set(arg);
  129. WriteDebugInfo($"Ordinal argument '{argument.Code}' is set to value '{argument.Value.AsString()}'.");
  130. }
  131. }
  132. }
  133. private Tuple<string, string> ParseNamedArgument(string argument)
  134. {
  135. try
  136. {
  137. var argParts = argument.Split(new[] {Engine.Configuration.CharacterNamedArgumentValueSeparator}, StringSplitOptions.RemoveEmptyEntries);
  138. WriteDebugInfo($"Splitting arg-parts '{argument}' to parts (count={argParts.Length}): {string.Join(",",argParts)}");
  139. var argName = argParts[0].Replace(Engine.Configuration.CharacterNamedArgumentSeparator,string.Empty);
  140. var argValue = argParts.Length > 1 ? string.Join(Engine.Configuration.CharacterNamedArgumentValueSeparator,argParts.Skip(1).Take(argParts.Length - 1)).Replace(_engine.Configuration.CharacterTextValueBraceSeparator,string.Empty) : string.Empty;
  141. WriteDebugInfo($"Named argument '{argument}' parsed as name='{argName}'; value='{argValue}'.");
  142. return new Tuple<string, string>(argName, argValue);
  143. }
  144. catch (Exception e)
  145. {
  146. WriteDebugInfo($"Error during parsing named argument '{argument}'.");
  147. throw new Exception($"Argument '{argument}' parsing error.", e);
  148. }
  149. }
  150. private string[] Split(string input, string valueBracket, string[] separators)
  151. {
  152. var result = new List<string>();
  153. var trimedInput = input.Trim();
  154. if (string.IsNullOrEmpty(trimedInput))
  155. return result.ToArray();
  156. var cValueBracked = valueBracket.ToCharArray().First();
  157. var cSeparators = separators.Select(x => x.ToCharArray().First());
  158. var nIndexStart = 0;
  159. var nIndexEnd = 0;
  160. var isInsideBracked = false;
  161. int offset = 0;
  162. for (offset = 0; offset < trimedInput.Length; offset++)
  163. {
  164. var current = trimedInput[offset];
  165. // current | isInside | Result
  166. // 1 1 0
  167. // 1 0 1
  168. // 0 1 1
  169. // 0 0 0
  170. isInsideBracked = current == cValueBracked ^ isInsideBracked;
  171. if (isInsideBracked)
  172. continue;
  173. if (cSeparators.Contains(current))
  174. {
  175. nIndexEnd = offset;
  176. result.Add(trimedInput.Substring(nIndexStart,nIndexEnd - nIndexStart));
  177. nIndexStart = nIndexEnd;
  178. isInsideBracked = false;
  179. }
  180. }
  181. if (offset>nIndexStart)
  182. result.Add(trimedInput.Substring(nIndexStart,offset - nIndexStart));
  183. return result.Where(x => !string.IsNullOrEmpty(x.Trim())).Select(x=>x.Trim()).ToArray();
  184. }
  185. private IEnumerable<AbstractArgument> SetupArguments()
  186. {
  187. return OnSetupArguments();
  188. }
  189. protected void WriteDebugInfo(string text)
  190. {
  191. using (var debug = new DebugConsoleWriter())
  192. {
  193. debug.WriteDebugLine(text);
  194. }
  195. }
  196. protected void WriteInfo(string text)
  197. {
  198. using (var writer = new ConsoleWriter(ConsoleColor.Green))
  199. WriteLine(writer,WriteTextSeverity.Info, text);
  200. }
  201. protected void WriteCaption(string text)
  202. {
  203. using (var writer = new ConsoleWriter(ConsoleColor.White))
  204. WriteLine(writer,WriteTextSeverity.Caption, text);
  205. }
  206. protected void WriteWarning(string text)
  207. {
  208. using (var writer = new ConsoleWriter(ConsoleColor.Yellow))
  209. WriteLine(writer,WriteTextSeverity.Warning, text);
  210. }
  211. protected void WriteError(string text)
  212. {
  213. using (var writer = new ConsoleWriter(ConsoleColor.Red))
  214. WriteLine(writer, WriteTextSeverity.Error, text);
  215. }
  216. protected void WriteError(Exception e)
  217. {
  218. if (e is AggregateException aggr)
  219. {
  220. foreach (var ex in aggr.InnerExceptions)
  221. DumpException(ex, "- ");
  222. }
  223. else
  224. DumpException(e, string.Empty);
  225. }
  226. private void DumpException(Exception e, string prefix)
  227. {
  228. while (e != null)
  229. {
  230. WriteError(prefix + e.Message);
  231. e = e.InnerException;
  232. }
  233. }
  234. protected virtual void WriteLine(ConsoleWriter writer, WriteTextSeverity severity, string text)
  235. {
  236. writer.WriteLine(text);
  237. }
  238. private void ShowContextStatus(ConsoleWriter writer)
  239. {
  240. using (var writerBlue = new ConsoleWriter(ConsoleColor.Blue))
  241. {
  242. using (var writerYellow = new ConsoleWriter(ConsoleColor.Magenta))
  243. {
  244. writer.WriteLine("Engine context:");
  245. writerBlue.Write(_engine.Context.ToString()).Write(" : ");
  246. writerYellow.WriteLine(_engine.Context.Status);
  247. writer.WriteLine("Command context:");
  248. writerBlue.Write(_context.ToString()).Write(" : ");
  249. writerYellow.WriteLine(_context.Status);
  250. }
  251. }
  252. }
  253. #endregion
  254. #region *** Protected virtuals ***
  255. protected virtual void OnCommandInit()
  256. {
  257. WriteDebugInfo("Command called OnCommandInit.");
  258. }
  259. protected virtual IEnumerable<AbstractArgument> OnSetupArguments()
  260. {
  261. return new AbstractArgument[0];
  262. //{
  263. // new FlagArgument(Constants.Arguments.General.DebugMode.Code, Constants.Arguments.General.DebugMode.Description, Constants.Arguments.General.DebugMode.Hint, true),
  264. //};
  265. }
  266. protected abstract Result OnExecute();
  267. protected virtual void OnValidateArguments()
  268. {
  269. var ex = new List<Exception>();
  270. foreach (var arg in _arguments.Where(x=>x.Value.IsMandatory).Select(x=>x.Value))
  271. {
  272. if (!arg.Value.HasValue)
  273. ex.Add(new Exception($"Argument '{arg.Code}' is mandatory!"));
  274. }
  275. if (ex.Count > 0)
  276. throw new AggregateException(ex);
  277. }
  278. protected virtual void OnInitialize()
  279. {
  280. }
  281. protected virtual void BeginExecute()
  282. {
  283. }
  284. protected virtual Result EndExecute(Result incommingResult)
  285. {
  286. return incommingResult;
  287. }
  288. #endregion
  289. #region *** Protected operations ***
  290. protected AbstractArgument GetArgument(string code)
  291. {
  292. if (!_arguments.ContainsKey(code))
  293. throw new Exception($"Argument '{code}' is not defined.");
  294. return _arguments[code];
  295. }
  296. protected AbstractArgument GetArgument(int ordinalPosition)
  297. {
  298. return _arguments.Values.Where(x => x.IsPositional()).Skip(ordinalPosition).FirstOrDefault();
  299. }
  300. protected TValue GetArgumentValueOrDefault<TValue>(string code, TValue defalutValue)
  301. {
  302. if (!ContainsArgument(code)) return defalutValue;
  303. var arg = GetArgument(code);
  304. var value = arg.Value.Get() ?? arg.DefaultValue.Get();
  305. return (TValue) value;
  306. }
  307. protected TValue GetArgumentValueOrDefault<TValue>(string code)
  308. {
  309. if (!ContainsArgument(code)) throw new ArgumentOutOfRangeException(code, $"Argument '{code}' not defined.");
  310. var arg = GetArgument(code);
  311. var value = arg.Value.Get() ?? arg.DefaultValue.Get();
  312. return (TValue) value;
  313. }
  314. protected bool WasArgumentSpecified(string code)
  315. {
  316. if (!ContainsArgument(code)) throw new ArgumentOutOfRangeException(code, $"Argument '{code}' not defined.");
  317. var arg = GetArgument(code);
  318. return arg.Value.HasValue;
  319. }
  320. protected bool ContainsArgument(string code)
  321. {
  322. return _arguments.ContainsKey(code);
  323. }
  324. protected TContext GetContext<TContext>() where TContext : class, ICommandContext
  325. {
  326. return (TContext)_context;
  327. }
  328. #endregion
  329. }
  330. }