Engine.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using Quadarax.Foundation.Common.Console;
  6. using Quadarax.Foundation.QConsole.Attributes;
  7. using Quadarax.Foundation.QConsole.Command.Base;
  8. using Quadarax.Foundation.QConsole.Command.Defaults;
  9. using Quadarax.Foundation.QConsole.Configuration;
  10. using Quadarax.Foundation.QConsole.Context;
  11. namespace Quadarax.Foundation.QConsole
  12. {
  13. public class Engine : IDisposable
  14. {
  15. #region *** Private Fields ***
  16. private bool _isDispoising;
  17. private bool _isExitSignal;
  18. private IList<AbstractCommand> _commands = new List<AbstractCommand>();
  19. private StartupConfiguration _configuration;
  20. private IList<ISelectionEntry> _selections = new List<ISelectionEntry>();
  21. #endregion
  22. #region *** Properties ***
  23. public string[] RawArguments { get; }
  24. public StartupConfiguration Configuration => _configuration;
  25. public AbstractCommand[] Commands => _commands.ToArray();
  26. public ISelectionEntry[] Selections => _selections.ToArray();
  27. public IEngineContext Context { get; }
  28. #endregion
  29. #region *** Constructor ***
  30. public Engine(StartupConfiguration configuration, IEngineContext context, string[] args)
  31. {
  32. _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
  33. Context = context ?? throw new ArgumentNullException(nameof(context));
  34. if (args == null)
  35. args = new string[0];
  36. // Ensure if debug mode -> Enable debug mode and remove explicit argument
  37. if (args.Any(x => x.Trim().ToLower() == Constants.Console.DebugModeExplicitArg))
  38. {
  39. configuration.EnableDebugMode();
  40. var newArgs = new List<string>(args);
  41. newArgs.Remove(Constants.Console.DebugModeExplicitArg);
  42. args = newArgs.ToArray();
  43. }
  44. WriteDebugInfo($"Console '{_configuration.ConsoleName}' initialization started.");
  45. WriteDebugInfo($"Engine assembly version '{Assembly.GetExecutingAssembly().GetName().Version}'.");
  46. WriteDebugInfo($"IsInitFromXml is set to '{_configuration.IsInitFromXml}'.");
  47. ShowHeader();
  48. RawArguments = args;
  49. WriteDebugInfo($"Input {args.Length} arguments appended.");
  50. WriteDebugInfo($"Context set: {Context}");
  51. var commandClasses = GetTypesWithHelpAttribute(new CommandDefinitionAttribute());
  52. WriteDebugInfo($"Console found {commandClasses.Count()} command definitions.");
  53. var paramConstrTypes = new Type[] { typeof(Engine) };
  54. var paramConstrValues = new object[] { this };
  55. foreach (var commandClass in commandClasses)
  56. {
  57. var command = Construct<AbstractCommand>(commandClass, paramConstrTypes, paramConstrValues);
  58. _commands.Add(command);
  59. WriteDebugInfo($"Command definition '{command}' added - class '{command.GetType().FullName}', assembly '{command.GetType().Assembly.GetName().Name}'.");
  60. }
  61. WriteDebugInfo("Console initialized.");
  62. }
  63. public void Start()
  64. {
  65. WriteDebugInfo("Console starting.");
  66. var commandLineArguments = string.Join(" ", RawArguments);
  67. using (var writer = new ConsoleWriter(ConsoleColor.White))
  68. {
  69. while (!_isExitSignal)
  70. {
  71. var input = string.Empty;
  72. if (commandLineArguments.Length == 0 && Configuration.AllowInteractive)
  73. {
  74. // interactive command entry
  75. writer.Write(_configuration.CharacterLineIntroduce);
  76. input = Console.ReadLine();
  77. }
  78. else
  79. {
  80. // inline command entry
  81. input = commandLineArguments;
  82. _isExitSignal = true;
  83. }
  84. var args = input.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries);
  85. if (args.Length == 0)
  86. continue;
  87. var command = GetCommand(args[0]);
  88. if (command == null)
  89. {
  90. using (var writerError = new ConsoleWriter(ConsoleColor.Red))
  91. {
  92. writerError.WriteLine($"Unknown command '{args[0]}'.");
  93. }
  94. continue;
  95. }
  96. var result = command.Execute(input);
  97. if (result.IsSuccess)
  98. {
  99. using (var writerSucc = new ConsoleWriter(ConsoleColor.Green))
  100. {
  101. writerSucc.WriteLine("Done.");
  102. }
  103. }
  104. else
  105. {
  106. using (var writerError = new ConsoleWriter(ConsoleColor.Red))
  107. {
  108. writerError.WriteLine("Error:");
  109. var e = result.ThrownException;
  110. while (e != null)
  111. {
  112. writerError.WriteLine(e.Message);
  113. e = e.InnerException;
  114. }
  115. }
  116. }
  117. }
  118. if (!Configuration.AllowInteractive && Configuration.WaitOnKeyInNonInteractiveMode)
  119. {
  120. WriteDebugInfo("Waiting for the key by configuration settings...");
  121. using (var writerGreen = new ConsoleWriter(ConsoleColor.Magenta))
  122. {
  123. writerGreen.WriteLine("Press any key to close...");
  124. Console.ReadKey();
  125. }
  126. }
  127. }
  128. }
  129. public void Stop()
  130. {
  131. _isExitSignal = true;
  132. WriteDebugInfo("Console stopped.");
  133. }
  134. public AbstractCommand GetCommand(string commandName)
  135. {
  136. return _commands.FirstOrDefault(x => x.Name == commandName.ToUpper());
  137. }
  138. public void AppendSelection(params ISelectionEntry[] selectionEntries)
  139. {
  140. if (selectionEntries == null)
  141. throw new ArgumentNullException(nameof(selectionEntries));
  142. foreach (var entry in selectionEntries)
  143. {
  144. _selections.Add(entry);
  145. }
  146. WriteDebugInfo($"{selectionEntries.Length} was added to global selections. Total count {_selections.Count} entries.");
  147. }
  148. public void ClearSelection()
  149. {
  150. _selections.Clear();
  151. WriteDebugInfo("Global selections was cleared.");
  152. }
  153. public ISelectionEntry GetSelection(int ordinal)
  154. {
  155. if (ordinal==0)
  156. throw new ArgumentOutOfRangeException(nameof(ordinal), "Ordinal value must be greater than 0.");
  157. if (_selections.Count < ordinal)
  158. throw new ArgumentOutOfRangeException(nameof(ordinal), $"Ordinal value must be less than {_selections.Count}.");
  159. return _selections[ordinal - 1];
  160. }
  161. #endregion
  162. #region *** Public Operations ***
  163. public void Dispose()
  164. {
  165. if (_isDispoising)
  166. return;
  167. _isDispoising = true;
  168. WriteDebugInfo("Dispoising called.");
  169. OnDispoising();
  170. WriteDebugInfo("Dispoising done.");
  171. }
  172. #endregion
  173. #region *** Protected Operations ***
  174. protected virtual void OnDispoising()
  175. {
  176. }
  177. protected virtual void OnShowHeader()
  178. {
  179. var headerText = @"{0} * {1} * Copyright (c) Quadarax 2019";
  180. using (var writer = new ConsoleWriter(ConsoleColor.Green))
  181. {
  182. writer.WriteLine(string.Format(headerText, _configuration.ConsoleName, _configuration.ConsoleVersion));
  183. }
  184. }
  185. #endregion
  186. #region *** Private Operations ***
  187. private static T Construct<T>(Type instance, Type[] paramTypes, object[] paramValues)
  188. {
  189. var ci = instance.GetConstructor(
  190. BindingFlags.Instance | BindingFlags.Public,
  191. null, paramTypes, null);
  192. if (ci == null)
  193. throw new Exception($"Command class '{instance.FullName}' has not public constuctor defined or has bad constructor's format.");
  194. return (T)ci.Invoke(paramValues);
  195. }
  196. private IEnumerable<Type> GetTypesWithHelpAttribute(Attribute attribute)
  197. {
  198. WriteDebugInfo($"Loading command assemblies ...");
  199. var defaultTypes = Assembly.GetExecutingAssembly().GetTypes().Where(type => type.GetCustomAttributes(attribute.GetType(), true).Length > 0).Distinct().ToList();
  200. var customTypes = new List<Type>();
  201. if (_configuration.CommandDefinitionAssebmly != null)
  202. {
  203. foreach (var assembly in _configuration.CommandDefinitionAssebmly)
  204. {
  205. customTypes.AddRange(assembly.GetTypes().Where(type => type.GetCustomAttributes(attribute.GetType(), true).Length > 0).Distinct().ToArray());
  206. WriteDebugInfo(assembly.GetName().Name + " was scanned for commands.");
  207. }
  208. }
  209. else
  210. {
  211. WriteDebugInfo("Custom CommandDefinitionAssembly is not defined. Skip.");
  212. }
  213. WriteDebugInfo($"Command definition obtaining process found {defaultTypes.Count} default definitions and {customTypes.Count} custom definitions.");
  214. defaultTypes.AddRange(customTypes);
  215. defaultTypes = defaultTypes.Distinct().ToList();
  216. foreach (var disabledCommand in _configuration.DisabledCommands)
  217. {
  218. var disabled = defaultTypes.FirstOrDefault(x => x.Name == disabledCommand);
  219. if (disabled==null)
  220. continue;
  221. defaultTypes.Remove(disabled);
  222. WriteDebugInfo($"Commnad class '{disabled.Name}', fullname '{disabled.FullName}', assembly '{disabled.Assembly.GetName().Name}' was skipped by configuration.");
  223. }
  224. return defaultTypes.ToArray();
  225. }
  226. private void WriteDebugInfo(string text)
  227. {
  228. using (var debug = new DebugConsoleWriter())
  229. {
  230. debug.WriteDebugLine(text);
  231. }
  232. }
  233. private void ShowHeader()
  234. {
  235. OnShowHeader();
  236. }
  237. #endregion
  238. }
  239. }