AbstractCommand.cs 15 KB

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