AbstractCommand.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. {
  119. argument.Value.Set(parsed.Item2);
  120. argument.Hit();
  121. }
  122. }
  123. else
  124. {
  125. //Ordinal
  126. WriteDebugInfo("Detects argument as ordinal.");
  127. argument = GetArgument(index);
  128. if (argument == null)
  129. throw new Exception(
  130. $"Invalid ordinal argument '{arg}' at position {index} for this command.");
  131. argument.Value.Set(arg);
  132. argument.Hit();
  133. WriteDebugInfo($"Ordinal argument '{argument.Code}' is set to value '{argument.Value.AsString()}'.");
  134. }
  135. }
  136. }
  137. private Tuple<string, string> ParseNamedArgument(string argument)
  138. {
  139. try
  140. {
  141. var argParts = argument.Split(new[] {Engine.Configuration.CharacterNamedArgumentValueSeparator}, StringSplitOptions.RemoveEmptyEntries);
  142. WriteDebugInfo($"Splitting arg-parts '{argument}' to parts (count={argParts.Length}): {string.Join(",",argParts)}");
  143. var argName = argParts[0].Replace(Engine.Configuration.CharacterNamedArgumentSeparator,string.Empty);
  144. 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;
  145. WriteDebugInfo($"Named argument '{argument}' parsed as name='{argName}'; value='{argValue}'.");
  146. return new Tuple<string, string>(argName, argValue);
  147. }
  148. catch (Exception e)
  149. {
  150. WriteDebugInfo($"Error during parsing named argument '{argument}'.");
  151. throw new Exception($"Argument '{argument}' parsing error.", e);
  152. }
  153. }
  154. private string[] Split(string input, string valueBracket, string[] separators)
  155. {
  156. var result = new List<string>();
  157. var trimedInput = input.Trim();
  158. if (string.IsNullOrEmpty(trimedInput))
  159. return result.ToArray();
  160. var cValueBracked = valueBracket.ToCharArray().First();
  161. var cSeparators = separators.Select(x => x.ToCharArray().First());
  162. var nIndexStart = 0;
  163. var nIndexEnd = 0;
  164. var isInsideBracked = false;
  165. int offset = 0;
  166. for (offset = 0; offset < trimedInput.Length; offset++)
  167. {
  168. var current = trimedInput[offset];
  169. // current | isInside | Result
  170. // 1 1 0
  171. // 1 0 1
  172. // 0 1 1
  173. // 0 0 0
  174. isInsideBracked = current == cValueBracked ^ isInsideBracked;
  175. if (isInsideBracked)
  176. continue;
  177. if (cSeparators.Contains(current))
  178. {
  179. nIndexEnd = offset;
  180. result.Add(trimedInput.Substring(nIndexStart,nIndexEnd - nIndexStart));
  181. nIndexStart = nIndexEnd;
  182. isInsideBracked = false;
  183. }
  184. }
  185. if (offset>nIndexStart)
  186. result.Add(trimedInput.Substring(nIndexStart,offset - nIndexStart));
  187. return result.Where(x => !string.IsNullOrEmpty(x.Trim())).Select(x=>x.Trim()).ToArray();
  188. }
  189. private IEnumerable<AbstractArgument> SetupArguments()
  190. {
  191. return OnSetupArguments();
  192. }
  193. protected void WriteDebugInfo(string text)
  194. {
  195. using (var debug = new DebugConsoleWriter())
  196. {
  197. debug.WriteDebugLine(text);
  198. }
  199. }
  200. protected void WriteInfo(string text)
  201. {
  202. using (var writer = new ConsoleWriter(ConsoleColor.Green))
  203. WriteLine(writer,WriteTextSeverity.Info, text);
  204. }
  205. protected void WriteCaption(string text)
  206. {
  207. using (var writer = new ConsoleWriter(ConsoleColor.White))
  208. WriteLine(writer,WriteTextSeverity.Caption, text);
  209. }
  210. protected void WriteWarning(string text)
  211. {
  212. using (var writer = new ConsoleWriter(ConsoleColor.Yellow))
  213. WriteLine(writer,WriteTextSeverity.Warning, text);
  214. }
  215. protected void WriteError(string text)
  216. {
  217. using (var writer = new ConsoleWriter(ConsoleColor.Red))
  218. WriteLine(writer, WriteTextSeverity.Error, text);
  219. }
  220. protected void WriteError(Exception e)
  221. {
  222. if (e is AggregateException aggr)
  223. {
  224. foreach (var ex in aggr.InnerExceptions)
  225. DumpException(ex, "- ");
  226. }
  227. else
  228. DumpException(e, string.Empty);
  229. }
  230. private void DumpException(Exception e, string prefix)
  231. {
  232. while (e != null)
  233. {
  234. WriteError(prefix + e.Message);
  235. e = e.InnerException;
  236. }
  237. }
  238. protected virtual void WriteLine(ConsoleWriter writer, WriteTextSeverity severity, string text)
  239. {
  240. writer.WriteLine(text);
  241. }
  242. private void ShowContextStatus(ConsoleWriter writer)
  243. {
  244. using (var writerBlue = new ConsoleWriter(ConsoleColor.Blue))
  245. {
  246. using (var writerYellow = new ConsoleWriter(ConsoleColor.Magenta))
  247. {
  248. writer.WriteLine("Engine context:");
  249. writerBlue.Write(_engine.Context.ToString()).Write(" : ");
  250. writerYellow.WriteLine(_engine.Context.Status);
  251. writer.WriteLine("Command context:");
  252. writerBlue.Write(_context.ToString()).Write(" : ");
  253. writerYellow.WriteLine(_context.Status);
  254. }
  255. }
  256. }
  257. #endregion
  258. #region *** Protected virtuals ***
  259. protected virtual void OnCommandInit()
  260. {
  261. WriteDebugInfo("Command called OnCommandInit.");
  262. }
  263. protected virtual IEnumerable<AbstractArgument> OnSetupArguments()
  264. {
  265. return new AbstractArgument[0];
  266. //{
  267. // new FlagArgument(Constants.Arguments.General.DebugMode.Code, Constants.Arguments.General.DebugMode.Description, Constants.Arguments.General.DebugMode.Hint, true),
  268. //};
  269. }
  270. protected abstract Result OnExecute();
  271. protected virtual void OnValidateArguments()
  272. {
  273. var ex = new List<Exception>();
  274. foreach (var arg in _arguments.Where(x=>x.Value.IsMandatory).Select(x=>x.Value))
  275. {
  276. if (!arg.Value.HasValue)
  277. ex.Add(new Exception($"Argument '{arg.Code}' is mandatory!"));
  278. }
  279. if (ex.Count > 0)
  280. throw new AggregateException(ex);
  281. }
  282. protected virtual void OnInitialize()
  283. {
  284. }
  285. protected virtual void BeginExecute()
  286. {
  287. }
  288. protected virtual Result EndExecute(Result incommingResult)
  289. {
  290. return incommingResult;
  291. }
  292. #endregion
  293. #region *** Protected operations ***
  294. protected AbstractArgument GetArgument(string code)
  295. {
  296. if (!_arguments.ContainsKey(code))
  297. throw new Exception($"Argument '{code}' is not defined.");
  298. return _arguments[code];
  299. }
  300. protected AbstractArgument GetArgument(int ordinalPosition)
  301. {
  302. return _arguments.Values.Where(x => x.IsPositional()).Skip(ordinalPosition).FirstOrDefault();
  303. }
  304. protected TValue GetArgumentValueOrDefault<TValue>(string code, TValue defalutValue)
  305. {
  306. if (!ContainsArgument(code)) return defalutValue;
  307. return (TValue) GetArgumentValueOrDefault<TValue>(code);
  308. }
  309. protected TValue GetArgumentValueOrDefault<TValue>(string code)
  310. {
  311. if (!ContainsArgument(code)) throw new ArgumentOutOfRangeException(code, $"Argument '{code}' not defined.");
  312. var arg = GetArgument(code);
  313. var value = arg.Value.Get() ?? arg.DefaultValue.Get();
  314. if (typeof(TValue).IsEnum)
  315. return (TValue)Enum.Parse(typeof(TValue), value?.ToString(),true);
  316. return (TValue) value;
  317. }
  318. protected bool WasArgumentSpecified(string code)
  319. {
  320. if (!ContainsArgument(code)) throw new ArgumentOutOfRangeException(code, $"Argument '{code}' not defined.");
  321. var arg = GetArgument(code);
  322. return arg.Value.HasValue && arg.WasUsed;
  323. }
  324. protected void ValidateArgumentValueEnum(string argumentName, Type enumType)
  325. {
  326. var argVal = GetArgumentValueOrDefault<string>(argumentName);
  327. if (!Enum.GetNames(enumType).Select(x => x.ToLower()).Contains(argVal.ToLower()))
  328. throw new ArgumentOutOfRangeException(
  329. $"Argument '{argumentName}' value must be set as following: {string.Join(",", Enum.GetNames(enumType))}");
  330. }
  331. protected void ValidateArgumentValueEnum<TEnum>(string argumentName) where TEnum : Enum
  332. {
  333. ValidateArgumentValueEnum(argumentName, typeof(TEnum));
  334. }
  335. protected bool ContainsArgument(string code)
  336. {
  337. return _arguments.ContainsKey(code);
  338. }
  339. protected TContext GetContext<TContext>() where TContext : class, ICommandContext
  340. {
  341. return (TContext)_context;
  342. }
  343. #endregion
  344. }
  345. }