AbstractCommand.cs 16 KB

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