using System; using System.Collections.Generic; using System.Collections.Specialized; using ln.build.commands; using ln.type; namespace ln.build.pipeline { public class StageCommandContainer { public StageCommandContainer Parent { get; } public string Name { get; } public string FullName => Parent?.FullName != null ? string.Format("{0} {1}", Parent.FullName, Name) : Name; Dictionary> commands = new Dictionary>(); Dictionary children = new Dictionary(); public StageCommandContainer(StageCommandContainer parent, string name) { Parent = parent; Name = name; } public void AddCommand(Action commandAction, string commandPath) => AddCommand(commandAction, commandPath.Split()); public void AddCommand(Action commandAction, params string[] commandPath) { if (commandPath.Length == 0) throw new ArgumentException(nameof(commandPath)); if (commandPath.Length > 1) { if (!children.TryGetValue(commandPath[0], out StageCommandContainer childContainer)) { childContainer = new StageCommandContainer(this, commandPath[0]); children.Add(commandPath[0], childContainer); } childContainer.AddCommand(commandAction, commandPath.Slice(1)); } else { commands.Add(commandPath[0], commandAction); } } public void Run(Stage stage, params string[] arguments) { if (commands.TryGetValue(arguments[0], out Action commandAction)) commandAction(stage, arguments.Slice(1)); else if (children.TryGetValue(arguments[0], out StageCommandContainer childContainer)) childContainer.Run(stage, arguments.Slice(1)); else throw new ArgumentException(String.Format("command not found: {0}", arguments[0])); } } }