private static void ParseCommand(ITypeData type, string[] group, CliActionTree command) { if (command.SubCommands == null) { command.SubCommands = new List <CliActionTree>(); } // If group is not empty. Find command with first group name if (group.Length > 0) { var existingCommand = command.SubCommands.FirstOrDefault(c => c.Name == group[0]); if (existingCommand == null) { existingCommand = new CliActionTree(command, group[0]); command.SubCommands.Add(existingCommand); } ParseCommand(type, group.Skip(1).ToArray(), existingCommand); } else { command.SubCommands.Add(new CliActionTree(command, type.GetDisplayAttribute().Name) { Type = type, SubCommands = new List <CliActionTree>() }); command.SubCommands.Sort((x, y) => string.Compare(x.Name, y.Name)); } }
/// <summary> /// Stores an object as a result. These results will be propagated to the ResultStore after the TestStep completes. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="result">The result whose properties should be stored.</param> public void Publish <T>(T result) { if (result == null) { throw new ArgumentNullException("result"); } ITypeData runtimeType = TypeData.GetTypeData(result); if (ResultFunc == null) { lock (resultFuncLock) ResultFunc = new Dictionary <ITypeData, Func <object, ResultTable> >(); } if (!ResultFunc.ContainsKey(runtimeType)) { var Typename = runtimeType.GetDisplayAttribute().GetFullName(); var Props = runtimeType.GetMembers().Where(x => x.Readable && x.TypeDescriptor.DescendsTo(typeof(IConvertible))).ToArray(); var PropNames = Props.Select(p => p.GetDisplayAttribute().GetFullName()).ToArray(); ResultFunc[runtimeType] = (v) => { var cols = new ResultColumn[Props.Length]; for (int i = 0; i < Props.Length; i++) { cols[i] = new ResultColumn(PropNames[i], GetArray(Props[i].TypeDescriptor.AsTypeData().Type, Props[i].GetValue(v))); } return(new ResultTable(Typename, cols)); }; } var res = ResultFunc[runtimeType](result); DoStore(res); }
public static int Execute(params string[] args) { // Trigger plugin manager before anything else. if (ExecutorClient.IsRunningIsolated) { // TODO: This is not needed right now, but might be again when we fix the TODO in tap.exe //PluginManager.DirectoriesToSearch.Clear(); //PluginManager.DirectoriesToSearch.Add(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)); using (var tpmClient = new ExecutorClient()) { tpmClient.MessageServer("delete " + Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)); } } // Set TapMutex to ensure any installers know about running OpenTAP processes. ReflectionHelper.SetTapMutex(); try { // Turn off the default system behavior when CTRL+C is pressed. // When Console.TreatControlCAsInput is false, CTRL+C is treated as an interrupt instead of as input. Console.TreatControlCAsInput = false; } catch { } try { var execThread = TapThread.Current; Console.CancelKeyPress += (s, e) => { e.Cancel = true; execThread.Abort(); }; } catch { } CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; // Find the called action if (!TypeData.GetDerivedTypes <ICliAction>().Any()) { Console.WriteLine("No commands found. Please try reinstalling OpenTAP."); return(1); } try { // setup logging to be relative to the executing assembly. // at this point SessionLogs.Initialize has already been called (PluginManager.Load). // so the log is already being saved at a different location. var logpath = EngineSettings.Current.SessionLogPath.Expand(date: Process.GetCurrentProcess().StartTime); bool isPathRooted = Path.IsPathRooted(logpath); if (isPathRooted == false) { var dir = Path.GetDirectoryName(typeof(SessionLogs).Assembly.Location); if (ExecutorClient.IsRunningIsolated) { // redirect the isolated log path to the non-isolated path. dir = ExecutorClient.ExeDir; } logpath = Path.Combine(dir, logpath); } SessionLogs.Rename(logpath); } catch (Exception e) { log.Error("Path defined in Engine settings contains invalid characters: {0}", EngineSettings.Current.SessionLogPath); log.Debug(e); } ITypeData selectedCommand = null; // Find selected command var actionTree = new CliActionTree(); var selectedcmd = actionTree.GetSubCommand(args); if (selectedcmd?.Type != null && selectedcmd?.SubCommands.Any() != true) { selectedCommand = selectedcmd.Type; } void print_command(CliActionTree cmd, int level, int descriptionStart) { if (cmd.IsBrowsable) { int relativePadding = descriptionStart - (level * LevelPadding); // Calculate amount of characters to pad right before description start to ensure description alignments. Console.Write($"{"".PadRight(level * LevelPadding)}{cmd.Name.PadRight(relativePadding)}"); if (cmd.Type?.IsBrowsable() ?? false) { Console.WriteLine($"{cmd.Type.GetDisplayAttribute().Description}"); } else { Console.WriteLine(); } if (cmd.IsGroup) { foreach (var subCmd in cmd.SubCommands) { print_command(subCmd, level + 1, descriptionStart); } } } } // Print default info if (selectedCommand == null) { Console.WriteLine("OpenTAP Command Line Interface ({0})", Assembly.GetExecutingAssembly().GetSemanticVersion().ToString(4)); Console.WriteLine("Usage: tap <command> [<subcommand(s)>] [<args>]\n"); if (selectedcmd == null) { Console.WriteLine("Valid commands are:"); foreach (var cmd in actionTree.SubCommands) { print_command(cmd, 0, actionTree.GetMaxCommandTreeLength(LevelPadding) + LevelPadding); } } else { Console.Write("Valid subcommands of "); print_command(selectedcmd, 0, actionTree.GetMaxCommandTreeLength(LevelPadding) + LevelPadding); } Console.WriteLine($"\nRun \"{(OperatingSystem.Current == OperatingSystem.Windows ? "tap.exe" : "tap")} " + "<command> [<subcommand>] -h\" to get additional help for a specific command.\n"); if (args.Length == 0 || args.Any(s => s.ToLower() == "--help" || s.ToLower() == "-h")) { return(0); } else { return(-1); } } if (selectedCommand != TypeData.FromType(typeof(RunCliAction)) && UserInput.Interface == null) // RunCliAction has --non-interactive flag and custom platform interaction handling. { CliUserInputInterface.Load(); } ICliAction packageAction = null; try{ packageAction = (ICliAction)selectedCommand.CreateInstance(); }catch (TargetInvocationException e1) when(e1.InnerException is System.ComponentModel.LicenseException e) { Console.Error.WriteLine("Unable to load CLI Action '{0}'", selectedCommand.GetDisplayAttribute().GetFullName()); Console.Error.WriteLine(e.Message); return(-4); } if (packageAction == null) { Console.WriteLine("Error instantiating command {0}", selectedCommand.Name); return(-3); } try { int skip = selectedCommand.GetDisplayAttribute().Group.Length + 1; // If the selected command has a group, it takes two arguments to use the command. E.g. "package create". If not, it only takes 1 argument, E.g. "restapi". return(packageAction.Execute(args.Skip(skip).ToArray())); } catch (ExitCodeException ec) { log.Error(ec.Message); return(ec.ExitCode); } catch (ArgumentException ae) { // ArgumentException usually contains several lines. // Only print the first line as an error message. // Example message: // "Directory is not a git repository. // Parameter name: repositoryDir" var lines = ae.Message.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); log.Error(lines.First()); for (int i = 1; i < lines.Length; i++) { log.Debug(lines[i]); } return(-1); } catch (OperationCanceledException ex) { log.Error(ex.Message); return(1); } catch (Exception ex) { log.Error(ex.Message); log.Debug(ex); return(-1); } finally { Log.Flush(); } }