AbstractCommand.cs 15 KB

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