Inheritance: MonoBehaviour
 protected override IConsole CreateConsole(ScriptEngine engine, CommandLine commandLine, ConsoleOptions options)
 {
     var pyoptions = (PythonConsoleOptions) options;
     return pyoptions.BasicConsole
                ? new BasicConsole(options.ColorfulConsole)
                : new SuperConsole(commandLine, options.ColorfulConsole);
 }
Example #2
0
        public static CommandLine Parse(string commandLine)
        {
            if (String.IsNullOrEmpty(commandLine)) return null;

            var args = commandLine.Split(' ')
                                  .Select(x => x.Trim())
                                  .Where(x => !String.IsNullOrEmpty(x))
                                  .ToList();

            if (args.Count == 0) return null;

            if (args[0] == "-")
                throw new InvalidOperationException("Char '-' must be followed by command or option name.");

            var cmdLine = new CommandLine(args[0].Substring(1));

            for (var i = 1; i < args.Count; i++)
            {
                var arg = args[i];

                if (arg.StartsWith("-"))
                {
                    cmdLine.Options = CommandOptionCollection.Parse(args.Skip(i).ToList());
                    break;
                }
                else
                {
                    cmdLine.Parameters.Add(arg);
                }
            }

            return cmdLine;
        }
        public void Then_arguments_should_be_set_if_provided()
        {
            var commandLine = new CommandLine("exe value1 \"value2\"");

            Assert.AreEqual("value1", commandLine.Option1);
            Assert.AreEqual("value2", commandLine.Option2);
        }
Example #4
0
        /// <summary>
        /// Parses the command-line.
        /// </summary>
        /// <param name="args">Arguments from command-line.</param>
        /// <param name="commandLine">Command line object created from command-line arguments</param>
        /// <returns>True if command-line is parsed, false if a failure was occurred.</returns>
        public static bool TryParseArguments(string[] args, out CommandLine commandLine)
        {
            bool success = true;

            commandLine = new CommandLine();

            for (int i = 0; i < args.Length; ++i)
            {
                if ('-' == args[i][0] || '/' == args[i][0])
                {
                    string arg = args[i].Substring(1).ToLowerInvariant();
                    if ("?" == arg || "help" == arg)
                    {
                        return false;
                    }
                    else if ("o" == arg || "out" == arg)
                    {
                        ++i;
                        if (args.Length == i)
                        {
                            Console.Error.WriteLine(String.Format("Missing file specification for '-out' option."));
                            success = false;
                        }
                        else
                        {
                            string outputPath = Path.GetFullPath(args[i]);
                            commandLine.OutputFolder = outputPath;
                        }
                    }
                }
                else
                {
                    string[] file = args[i].Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                    string sourcePath = Path.GetFullPath(file[0]);
                    if (!System.IO.File.Exists(sourcePath))
                    {
                        Console.Error.WriteLine(String.Format("Source file '{0}' could not be found.", sourcePath));
                        success = false;
                    }
                    else
                    {
                        commandLine.Files.Add(sourcePath);
                    }
                }
            }

            if (0 == commandLine.Files.Count)
            {
                Console.Error.WriteLine(String.Format("No inputs specified. Specify at least one file."));
                success = false;
            }

            if (String.IsNullOrEmpty(commandLine.OutputFolder))
            {
                Console.Error.WriteLine(String.Format("Ouput folder was not specified. Specify an output folder using the '-out' switch."));
                success = false;
            }

            return success;
        }
Example #5
0
File: Program.cs Project: cubean/CG
 static void Main(string[] args)
 {
     Console.Title = "Irony Console Sample";
       Console.WriteLine("Irony Console Sample.");
       Console.WriteLine("");
       Console.WriteLine("Select a grammar to load:");
       Console.WriteLine("  1. Expression Evaluator");
       Console.WriteLine("  2. mini-Python");
       Console.WriteLine("  Or press any other key to exit.");
       Console.WriteLine("");
       Console.Write("?");
       var choice = Console.ReadLine();
       Grammar grammar;
       switch (choice) {
     case "1":
       grammar = new ExpressionEvaluatorGrammar();
       break;
     case "2":
       grammar = new MiniPython.MiniPythonGrammar();
       break;
     default:
       return;
       }
       Console.Clear();
       var commandLine = new CommandLine(grammar);
       commandLine.Run();
 }
        public void Then_options_should_be_set_if_provided()
        {
            var commandLine = new CommandLine("exe -opt1 -opt4 -opt2");

            Assert.IsTrue(commandLine.Option1);
            Assert.IsTrue(commandLine.Option2);
        }
		public CommandExecutorContext(ICommandExecutor executor, CommandLine commandLine, CommandTreeNode commandNode, object parameter) : base(executor, null, commandNode, parameter)
		{
			if(commandLine == null)
				throw new ArgumentNullException("commandLine");

			_commandLine = commandLine;
		}
 public void Handle(CommandLine commandLine)
 {
     if (_context.CurrentClient == null) {
         WriteError("You should define the current client first using 'connect %index'.");
     }
     HandleInternal(commandLine, _context.CurrentClient.RemoteClient);
 }
        public void Then_options_should_be_set_if_provided()
        {
            var commandLine = new CommandLine("exe -opt1:value1 -opt4 -opt2:\"value2\"");

            Assert.AreEqual("value1", commandLine.Option1);
            Assert.AreEqual("value2", commandLine.Option2);
        }
 public void DefaultProvider_invalidCommandLine_Throws()
 {
     var provider = Provider.Default;
     var commandLine = new CommandLine {[CommandLineParam.user] = Value.From("user")};
     var connectionString = new ConnectionString();
     var result = ConnectionStringBuilder.GetConnectionString(provider, commandLine, connectionString);
 }
 public PythonCompletionData(string text, string stub, CommandLine commandLine, bool isInstance)
 {
     this.Text = text;
     this.Stub = stub;
     this.commandLine = commandLine;
     this.IsInstance = isInstance;
 }
Example #12
0
		/// <summary>
		/// This is the entry point into the DLL.  It parses the command line and
		/// delegates the work out to each program.
		/// </summary>
		/// <param name="commandLine">The commandline that invoked the program.  Usually
		/// this corresponds to System.Environment.CommandLine</param>
		/// <returns></returns>
		public static void DllMain(string commandLine)
		{
			CommandLine = new CommandLine();
			Parser parser = new Parser(commandLine, CommandLine);			
			parser.Parse();

			if(CommandLine.Help)
			{
				Console.WriteLine("This program is used to import blog data from other blogging programs.");
				Console.WriteLine("  Note that this program will modify your content directory so back it up.");
				Console.WriteLine("  Also, the program will require an internet connection in some instances, ");
				Console.WriteLine("  like importing comments from an external server.");
				Console.WriteLine( parser.GetHelpText() );
			}
			else
			{
				switch(CommandLine.Source)
				{
					case BlogSourceType.Radio:
						if(CommandLine.SourceDirectory !=  null && CommandLine.SourceDirectory.Length > 0
							&& CommandLine.ContentDirectory != null && CommandLine.ContentDirectory.Length > 0)
						{
							Console.WriteLine("Importing entries from Radio...");
							DasBlog.Import.Radio.EntryImporter.Import(
								CommandLine.SourceDirectory,
								CommandLine.ContentDirectory);
						}
						else
						{
							Console.WriteLine("Entries from Radio not imported because either source directory or content directory were not specified.");
						}
						
						if(CommandLine.UserID != null && CommandLine.UserID.Length > 0 
							&& CommandLine.ContentDirectory != null && CommandLine.ContentDirectory.Length > 0)

						{
							if(CommandLine.CommentServer != null && CommandLine.CommentServer.Length > 0)
							{
								Console.WriteLine("Defaulting to comment server {0}.  You may need to check your radio source.  radiocomments2, etc",DasBlog.Import.Radio.CommentImporter.DefaultCommentServer);
							}

							Console.WriteLine("BETA: Importing comments from Radio...");
							DasBlog.Import.Radio.CommentImporter.Import(
								CommandLine.UserID, CommandLine.ContentDirectory, CommandLine.CommentServer );
						}
						else
						{
							Console.WriteLine("Comments from Radio not imported because comment server, userid or content directory were not specified.");
						}


						break;
					case BlogSourceType.none:
						goto default;
					default:
						throw new ApplicationException(
							string.Format("The source option was not specified or else was invalid."));
				}
			}
		}
 public void DefaultProvider_EmptyCommandLine_Throws()
 {
     var provider = Provider.Default;
     var commandLine = new CommandLine();
     var connectionString = new ConnectionString();
     var result = ConnectionStringBuilder.GetConnectionString(provider, commandLine, connectionString);
 }
 public void WithEmptyOption__GetOption__ReturnEmptyString()
 {
     string[] arguments = { "/" };
     var commandLine = new CommandLine(arguments);
     var option = commandLine.Option("");
     Assert.IsEmpty(option);
 }
        public void Then_options_should_be_set_if_provided()
        {
            var commandLine = new CommandLine("exe -opt1:two -opt4 -opt2:\"bbb\"");

            Assert.AreEqual(Enum1.two, commandLine.Option1);
            Assert.AreEqual(Enum2.bbb, commandLine.Option2);
        }
 public void WithValidOption__GetOptionWithNameInCaps__ReturnOption()
 {
     string[] arguments = { "/keyfile:file" };
     var commandLine = new CommandLine(arguments);
     var option = commandLine.Option("KEYFILE");
     Assert.AreEqual("file", option);
 }
 public void WithValidOption__GetOtherOption__ReturnNull()
 {
     string[] arguments = { "/keyfile:file" };
     var commandLine = new CommandLine(arguments);
     var option = commandLine.Option("union");
     Assert.IsNull(option);
 }
 public void WithInvalidOptionPrefix__GetOption__ReturnNull()
 {
     string[] arguments = { "&ver" };
     var commandLine = new CommandLine(arguments);
     var option = commandLine.Option("ver");
     Assert.IsNull(option);
 }
 public void WithValidOptionPrefix__GetOption__ReturnNull()
 {
     string[] arguments = { "--keyfile:file", "--log" };
     var commandLine = new CommandLine(arguments);
     var option = commandLine.Option("keyfile");
     Assert.AreEqual("file", option);
 }
Example #20
0
        public static CommandLine Load(ICollection<string> args)
        {
            var assembly = Assembly.GetExecutingAssembly();
            var info = FileVersionInfo.GetVersionInfo(assembly.Location).ProductVersion;
            Console.WriteLine(Resources.Splash, info);
            if (null == args)
            {
                return new CommandLine();
            }

            var result = new CommandLine(args);
            if (!result.Help)
            {
                Console.WriteLine(string.Empty);
                Console.WriteLine(Resources.Usage);
                Console.WriteLine(string.Empty);
                Console.WriteLine(Resources.UsageDetails);
                Console.WriteLine(string.Empty);
                Console.WriteLine(Resources.Parameters);
                Console.WriteLine(string.Empty);
                Console.WriteLine(Resources.ParametersHelp);
                Console.WriteLine(Resources.ParametersInfo);
                Console.WriteLine(string.Empty);
                Console.WriteLine(Resources.HelpLink);
            }

            return result;
        }
 public void WithEmptyOption__GetOption__ReturnNull()
 {
     string[] arguments = { "" };
     var commandLine = new CommandLine(arguments);
     string option = commandLine.Option("");
     Assert.IsNull(option);
 }
        public void Then_options_should_be_set_if_provided()
        {
            var commandLine = new CommandLine("exe -opt1:12 -opt4 -opt2:\"13\"");

            Assert.AreEqual(12, commandLine.Option1);
            Assert.AreEqual(13, commandLine.Option2);
        }
Example #23
0
		/// <remarks>
		/// After the engine is created the standard output is replaced with our custom Stream class so we
		/// can redirect the stdout to the text editor window.
		/// This can be done in this method since the Runtime object will have been created before this method
		/// is called.
		/// </remarks>
		protected override IConsole CreateConsole(ScriptEngine engine, CommandLine commandLine, ConsoleOptions options)
		{
			ScriptingConsoleOutputStream stream = pythonConsole.CreateOutputStream();
			SetOutput(stream);
			pythonConsole.CommandLine = commandLine;
			return pythonConsole;
		}
Example #24
0
 static void Main(string[] args)
 {
     var commandLine = new CommandLine(args);
     if (commandLine.Help)
     {
         commandLine.ShowHelp(Console.Out);
         Environment.ExitCode = 1;
         return;
     }
     if (commandLine.HasErrors)
     {
         commandLine.ShowErrors(Console.Error);
         Environment.ExitCode = 1;
         return;
     }
     try
     {
         if (SolutionFile.IsSolutionFileName(commandLine.ProjectFile))
         {
             ProcessSolutionFile(commandLine);
         }
         else
         {
             ProcessProjectFile(commandLine);
         }
         Log.Info("Done");
     }
     catch (Exception ex)
     {
         Log.Error("Unexpected exception: " + ex.Message);
         Environment.ExitCode = 1;
     }
 }
        public void Execute(Session session, CommandLine line)
        {
            session.WriteLine("usage:");
            session.WriteLine("  <command> [patameters ...]");
            session.WriteLine();

            session.WriteLine("commands:");

            var mapper = session.GetCommandMapper(line);
            if (mapper == null)
            {
                foreach (var m in session.Engine.MapperManager.GetCommandMappers())
                {
                    this.HelpFor(m, session, line);
                }
            }
            else
            {
                this.HelpFor(mapper, session, line);
                var parameterFormater = session.Engine.GetCommandMember(z => z.ParametersFormater);
                var ParameterParser = session.Engine.GetCommandMember(z => z.CommandParameterParser);
                session.WriteLine();
                session.WriteLine("parameters:");
                foreach (var formatedString in parameterFormater.Format(mapper, mapper.ExecutorBuilder.Mappers, ParameterParser))
                {
                    session.WriteLine("  " + formatedString);
                }
            }
        }
        private void Execute(CommandMapper mapper, CommandLine command)
        {
            var obj = mapper.CommandClassBuilder.Build();
            var executor = mapper.ExecutorBuilder.CreateExecutor(obj);
            foreach (var kvp in command.Parameters)
            {
                var r = executor.SetParameter(kvp.Key, kvp.Value, this.Engine.MapperManager.GetAgent());
                if (r.HasError)
                {
                    this.WriteLine(r);
                    return;
                }
            }
            var missing = executor.GetMissingParameters().ToArray();
            if (missing.Length != 0)
            {
                this.Engine.GetCommandMember(z => z.MissingParametersFormater)
                    .Format(this.Engine.GetCommandMember(z => z.Output), mapper, missing,
                        this.Engine.GetCommandMember(z => z.CommandParameterParser));
                this.Help(command);
                return;
            }

            executor.Execute(this, command);
        }
Example #27
0
 public IUpdateProcess CreateProcess(CommandLine cmdline)
 {
     Version ver;
     var version = cmdline["version"];
     if(string.IsNullOrEmpty(version))
     {
         ver = new Version(0, 0, 0, 0);
     }
     else
     {
         if(!Version.TryParse(version, out ver))
         {
             ver = new Version(0, 0, 0, 0);
         }
     }
     var git = cmdline["git"];
     if(string.IsNullOrEmpty(git))
     {
         git = DetectGitExePath();
         if(string.IsNullOrEmpty(git)) return null;
     }
     var url = cmdline["url"];
     if(string.IsNullOrEmpty(url)) return null;
     var target = cmdline["target"];
     if(string.IsNullOrEmpty(target)) return null;
     bool skipVersionCheck = cmdline.IsDefined("skipversioncheck");
     return new UpdateFromGitRepositoryProcess(ver, git, url, target, skipVersionCheck);
 }
Example #28
0
 public void AutoLoadWithQuotes()
 {
     CommandLine commandLine = new CommandLine();
     Parser parser = new Parser("DummyProgram.exe /SourceDir:\"c:\\Program Files\"", commandLine);
     parser.Parse();
     Assert.AreEqual("c:\\Program Files", commandLine.SourceDirectory, "The source parameter is not correct.");
 }
Example #29
0
        static int Main( string[] args )
        {
            CommandLine     commandLine = new CommandLine();
            int             returnVal = 0;

            try
            {
                commandLine.Parse( args );

                if( commandLine.Mode == SyncAppMode.RunEngine )
                {
                    RunSyncEngine( commandLine );
                }
                else if( commandLine.Mode == SyncAppMode.CreateConfigTemplate )
                {
                    CreateConfigTemplateFile( commandLine );
                }
            }
            catch( Exception e )
            {
                Console.Error.WriteLine( "Error: {0}", e.ToString() );
                returnVal = -1;
            }

            if( commandLine.PauseOnExit )
            {
                Console.WriteLine();
                Console.WriteLine( "Press any key to exit..." );
                Console.ReadKey( true );
            }

            return returnVal;
        }
Example #30
0
 public static void RunCommand(string[] inputArgs, CommandStatusWriter consoleOut)
 {
     using (CommandLine cmd = new CommandLine(consoleOut))
     {
         cmd.Run(inputArgs);
     }
 }
Example #31
0
        /// <summary>
        /// This is the program entrypoint.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        public static void Main(string[] args)
        {
            string          platform;
            KubeSetupHelper helper;

            commandLine = new CommandLine(args);

            var command = commandLine.Arguments.FirstOrDefault();

            if (command != null)
            {
                command = command.ToLowerInvariant();
            }

            if (commandLine.Arguments.Length == 0 || commandLine.HasHelpOption || command == "help")
            {
                Console.WriteLine(usage);
                Program.Exit(0);
            }

            try
            {
                Program.RepoRootFolder = Environment.GetEnvironmentVariable("NF_ROOT");

                if (string.IsNullOrEmpty(Program.RepoRootFolder) || !Directory.Exists(Program.RepoRootFolder))
                {
                    Console.Error.WriteLine("*** ERROR: NF_ROOT environment variable does not reference the local neonKUBE repostory.");
                    Program.Exit(1);
                }

                Program.DefaultKubernetesVersion = File.ReadAllText(Path.Combine(Program.RepoRootFolder, "kube-version.txt")).Trim();

                // Handle the commands.

                switch (command)
                {
                case "clean":

                    var buildFolder = Path.Combine(Program.RepoRootFolder, "Build");

                    if (Directory.Exists(buildFolder))
                    {
                        NeonHelper.DeleteFolderContents(buildFolder);
                    }

                    if (commandLine.HasOption("--all"))
                    {
                        var buildCacheFolder = Path.Combine(Program.RepoRootFolder, "Build-cache");

                        if (Directory.Exists(buildCacheFolder))
                        {
                            NeonHelper.DeleteFolderContents(buildCacheFolder);
                        }
                    }

                    var cadenceResourcesPath = Path.Combine(Program.RepoRootFolder, "Lib", "Neon.Cadence", "Resources");

                    if (Directory.Exists(cadenceResourcesPath))
                    {
                        NeonHelper.DeleteFolder(cadenceResourcesPath);
                    }

                    foreach (var folder in Directory.EnumerateDirectories(Program.RepoRootFolder, "bin", SearchOption.AllDirectories))
                    {
                        if (Directory.Exists(folder))
                        {
                            NeonHelper.DeleteFolder(folder);
                        }
                    }

                    foreach (var folder in Directory.EnumerateDirectories(Program.RepoRootFolder, "obj", SearchOption.AllDirectories))
                    {
                        if (Directory.Exists(folder))
                        {
                            NeonHelper.DeleteFolder(folder);
                        }
                    }

                    break;

                case "installer":

                    platform = commandLine.Arguments.ElementAtOrDefault(1);

                    if (string.IsNullOrEmpty(platform))
                    {
                        Console.Error.WriteLine("*** ERROR: PLATFORM argument is required.");
                        Program.Exit(1);
                    }

                    helper = new KubeSetupHelper(platform, commandLine,
                                                 outputAction: text => Console.Write(text),
                                                 errorAction: text => Console.Write(text));

                    EnsureOption("--kube-version", Program.DefaultKubernetesVersion);

                    switch (helper.Platform)
                    {
                    case KubeClientPlatform.Windows:

                        new WinInstallBuilder(helper).Run();
                        break;

                    case KubeClientPlatform.Osx:

                        throw new NotImplementedException();
                    }
                    break;

                case "clear":

                    platform = commandLine.Arguments.ElementAtOrDefault(1);

                    if (string.IsNullOrEmpty(platform))
                    {
                        Console.Error.WriteLine("*** ERROR: PLATFORM argument is required.");
                        Program.Exit(1);
                    }

                    helper = new KubeSetupHelper(platform, commandLine,
                                                 outputAction: text => Console.Write(text),
                                                 errorAction: text => Console.Write(text));

                    helper.Clear();
                    break;

                case "download":

                    platform = commandLine.Arguments.ElementAtOrDefault(1);

                    if (string.IsNullOrEmpty(platform))
                    {
                        Console.Error.WriteLine("*** ERROR: PLATFORM argument is required.");
                        Program.Exit(1);
                    }

                    helper = new KubeSetupHelper(platform, commandLine,
                                                 outputAction: text => Console.Write(text),
                                                 errorAction: text => Console.Write(text));

                    EnsureOption("--kube-version", Program.DefaultKubernetesVersion);
                    helper.Download();
                    break;

                case "copy":

                {
                    var sourcePath = commandLine.Arguments.ElementAtOrDefault(1);
                    var targetPath = commandLine.Arguments.ElementAtOrDefault(2);

                    if (sourcePath == null)
                    {
                        Console.Error.WriteLine("*** ERROR: SOURCE argument is required.");
                        Program.Exit(1);
                    }

                    if (targetPath == null)
                    {
                        Console.Error.WriteLine("*** ERROR: TARGET argument is required.");
                        Program.Exit(1);
                    }

                    if (!File.Exists(sourcePath))
                    {
                        Console.Error.WriteLine($"*** ERROR: SOURCE file [{sourcePath}] does not exist.");
                        Program.Exit(1);
                    }

                    Directory.CreateDirectory(Path.GetDirectoryName(targetPath));

                    if (File.Exists(targetPath) && File.GetLastWriteTimeUtc(targetPath) > File.GetLastWriteTimeUtc(sourcePath))
                    {
                        Console.WriteLine($"File [{targetPath}] is up to date.");
                        Program.Exit(0);
                    }

                    Console.WriteLine($"COPY: [{sourcePath}] --> [{targetPath}].");
                    File.Copy(sourcePath, targetPath);
                }
                break;

                case "gzip":

                    Gzip(commandLine);
                    break;

                case "build-version":

                    BuildVersion(commandLine);
                    break;

                case "pack-version":

                    PackVersion(commandLine);
                    break;

                case "shfb":

                    Shfb(commandLine);
                    break;

                default:

                    Console.Error.WriteLine($"*** ERROR: Unexpected command [{command}].");
                    Program.Exit(1);
                    break;
                }

                Program.Exit(0);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine($"*** ERROR: {e.GetType().FullName}: {e.Message}");
                Program.Exit(1);
            }
        }
Example #32
0
        static int Main(string[] args)
        {
            var nodeIndex        = CommandLine.GetInt32("multinode.index");
            var nodeRole         = CommandLine.GetProperty("multinode.role");
            var assemblyFileName = CommandLine.GetProperty("multinode.test-assembly");
            var typeName         = CommandLine.GetProperty("multinode.test-class");
            var testName         = CommandLine.GetProperty("multinode.test-method");
            var displayName      = testName;

            var listenAddress  = IPAddress.Parse(CommandLine.GetProperty("multinode.listen-address"));
            var listenPort     = CommandLine.GetInt32("multinode.listen-port");
            var listenEndpoint = new IPEndPoint(listenAddress, listenPort);

            var system    = ActorSystem.Create("NoteTestRunner-" + nodeIndex);
            var tcpClient = _logger = system.ActorOf <RunnerTcpClient>();

            system.Tcp().Tell(new Tcp.Connect(listenEndpoint), tcpClient);

#if CORECLR
            // In NetCore, if the assembly file hasn't been touched,
            // XunitFrontController would fail loading external assemblies and its dependencies.
            AssemblyLoadContext.Default.Resolving += (assemblyLoadContext, assemblyName) => DefaultOnResolving(assemblyLoadContext, assemblyName, assemblyFileName);
            var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyFileName);
            DependencyContext.Load(assembly)
            .CompileLibraries
            .Where(dep => dep.Name.ToLower()
                   .Contains(assembly.FullName.Split(new[] { ',' })[0].ToLower()))
            .Select(dependency => AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(dependency.Name)));
#endif

            Thread.Sleep(TimeSpan.FromSeconds(10));
            using (var controller = new XunitFrontController(AppDomainSupport.IfAvailable, assemblyFileName))
            {
                /* need to pass in just the assembly name to Discovery, not the full path
                 * i.e. "Akka.Cluster.Tests.MultiNode.dll"
                 * not "bin/Release/Akka.Cluster.Tests.MultiNode.dll" - this will cause
                 * the Discovery class to actually not find any individual specs to run
                 */
                var assemblyName = Path.GetFileName(assemblyFileName);
                Console.WriteLine("Running specs for {0} [{1}]", assemblyName, assemblyFileName);
                using (var discovery = new Discovery(assemblyName, typeName))
                {
                    using (var sink = new Sink(nodeIndex, nodeRole, tcpClient))
                    {
                        try
                        {
                            controller.Find(true, discovery, TestFrameworkOptions.ForDiscovery());
                            discovery.Finished.WaitOne();
                            controller.RunTests(discovery.TestCases, sink, TestFrameworkOptions.ForExecution());
                        }
                        catch (AggregateException ex)
                        {
                            var specFail = new SpecFail(nodeIndex, nodeRole, displayName);
                            specFail.FailureExceptionTypes.Add(ex.GetType().ToString());
                            specFail.FailureMessages.Add(ex.Message);
                            specFail.FailureStackTraces.Add(ex.StackTrace);
                            foreach (var innerEx in ex.Flatten().InnerExceptions)
                            {
                                specFail.FailureExceptionTypes.Add(innerEx.GetType().ToString());
                                specFail.FailureMessages.Add(innerEx.Message);
                                specFail.FailureStackTraces.Add(innerEx.StackTrace);
                            }
                            _logger.Tell(specFail.ToString());
                            Console.WriteLine(specFail);

                            //make sure message is send over the wire
                            FlushLogMessages();
                            Environment.Exit(1); //signal failure
                            return(1);
                        }
                        catch (Exception ex)
                        {
                            var specFail = new SpecFail(nodeIndex, nodeRole, displayName);
                            specFail.FailureExceptionTypes.Add(ex.GetType().ToString());
                            specFail.FailureMessages.Add(ex.Message);
                            specFail.FailureStackTraces.Add(ex.StackTrace);
                            var innerEx = ex.InnerException;
                            while (innerEx != null)
                            {
                                specFail.FailureExceptionTypes.Add(innerEx.GetType().ToString());
                                specFail.FailureMessages.Add(innerEx.Message);
                                specFail.FailureStackTraces.Add(innerEx.StackTrace);
                                innerEx = innerEx.InnerException;
                            }
                            _logger.Tell(specFail.ToString());
                            Console.WriteLine(specFail);

                            //make sure message is send over the wire
                            FlushLogMessages();
                            Environment.Exit(1); //signal failure
                            return(1);
                        }

                        var timedOut = false;
                        if (!sink.Finished.WaitOne(MaxProcessWaitTimeout)) //timed out
                        {
                            var line = string.Format("Timed out while waiting for test to complete after {0} ms",
                                                     MaxProcessWaitTimeout);
                            _logger.Tell(line);
                            Console.WriteLine(line);
                            timedOut = true;
                        }

                        FlushLogMessages();
                        system.Terminate().Wait();

                        Environment.Exit(sink.Passed && !timedOut ? 0 : 1);
                        return(sink.Passed ? 0 : 1);
                    }
                }
            }
        }
Example #33
0
 /// <inheritdoc/>
 public override void Run(CommandLine commandLine)
 {
     Help();
 }
Example #34
0
        /// <summary>
        /// The program entry point.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        public static async Task <int> Main(params string[] args)
        {
            string usage = $@"
{Program.Name} [v{Program.Version}]
{Neon.Build.Copyright}

USAGE:

    gh-tool COMMAND [ARG...]

COMMANDS:

    gh-tool action run delete REPO [WORKFLOW-NAME] [--max-age-days=AGE]
";

            try
            {
                ICommand command;

                CommandLine = new CommandLine(args);

                var validOptions = new HashSet <string>();

                validOptions.Add("--help");

                if (CommandLine.Arguments.Length == 0)
                {
                    Console.WriteLine(usage);
                    Program.Exit(0);
                }

                // Scan for enabled commands in the current assembly.

                var commands = new List <ICommand>();

                foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
                {
                    if (!type.Implements <ICommand>())
                    {
                        continue;
                    }

                    var commandAttribute = type.GetCustomAttribute <CommandAttribute>();

                    if (commandAttribute == null || commandAttribute.Disabled)
                    {
                        continue;
                    }

                    commands.Add((ICommand)Activator.CreateInstance(type));
                }

                // Short-circuit the help command.

                if (CommandLine.Arguments[0] == "help")
                {
                    if (CommandLine.Arguments.Length == 1)
                    {
                        Console.WriteLine(usage);
                        Program.Exit(0);
                    }

                    CommandLine = CommandLine.Shift(1);
                    command     = GetCommand(CommandLine, commands);

                    if (command == null)
                    {
                        Console.Error.WriteLine($"*** ERROR: Unexpected [{CommandLine.Arguments[0]}] command.");
                        Program.Exit(1);
                    }

                    command.Help();
                    Program.Exit(0);
                }

                // Lookup the command.

                command = GetCommand(CommandLine, commands);

                if (command == null)
                {
                    Console.Error.WriteLine($"*** ERROR: Unexpected [{CommandLine.Arguments[0]}] command.");
                    Program.Exit(1);
                }

                // Ensure that there are no unexpected command line options.

                if (command.CheckOptions)
                {
                    foreach (var optionName in command.ExtendedOptions)
                    {
                        validOptions.Add(optionName);
                    }

                    foreach (var option in CommandLine.Options)
                    {
                        if (!validOptions.Contains(option.Key))
                        {
                            var commandWords = string.Empty;

                            foreach (var word in command.Words)
                            {
                                if (commandWords.Length > 0)
                                {
                                    commandWords += " ";
                                }

                                commandWords += word;
                            }

                            Console.Error.WriteLine($"*** ERROR: [{commandWords}] command does not support [{option.Key}].");
                            Program.Exit(1);
                        }
                    }
                }

                // Run the command.

                if (command.SplitItem != null)
                {
                    // We don't shift the command line for pass-thru commands
                    // because we don't want to change the order of any options.

                    await command.RunAsync(CommandLine);
                }
                else
                {
                    await command.RunAsync(CommandLine.Shift(command.Words.Length));
                }
            }
            catch (ProgramExitException e)
            {
                return(e.ExitCode);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine($"*** ERROR: {NeonHelper.ExceptionError(e)}");
                Console.Error.WriteLine(e.StackTrace);
                Console.Error.WriteLine(string.Empty);
                return(1);
            }

            return(0);
        }
Example #35
0
        public static void RunTests(Options o)
        {
            
            var nullMessage = new Xunit.NullMessageSink();
            var discoveryOptions = TestFrameworkOptions.ForDiscovery();
            using (var c = new XunitFrontController(AppDomainSupport.Denied, o.Assembly, null, false))
            {
                var tv = new TestDiscoverySink();
                var excludeTestCaseSet = new TestDiscoverySink();
                c.Find(true, tv, discoveryOptions);
                tv.Finished.WaitOne();
                foreach (var tc in tv.TestCases)
                {
                    var method = tc.TestMethod.Method;
                    var attributes = method.GetCustomAttributes(typeof(FactAttribute));
                    foreach (ReflectionAttributeInfo at in attributes)
                    {
                        var result = at.GetNamedArgument<string>("Skip");
                        if (result != null)
                        {
                            Console.WriteLine("SKIPPY! {0} because {1}", method, result);
                        }

                        if (o.TestType != TestType.All)
                        {
                            if (!at.ToString().EndsWith(o.TestType.ToString()))
                            {
                                excludeTestCaseSet.TestCases.Add(tc);
                            }
                        }
                    }
                }

                foreach (var tc in excludeTestCaseSet.TestCases)
                {
                    tv.TestCases.Remove(tc);
                }

                Console.WriteLine("TEST COUNT: {0}", tv.TestCases.Count);
                //core execution Sink

                int testCaseCount = tv.TestCases.Count;
                Stream file = new FileStream(".\\result.xml", FileMode.Create);
                int totalResult = 0;
                int totalErrors = 0;
                int totalFailed = 0;
                int totalSkipped = 0;
                for (int i = 0; i < testCaseCount; i++)
                {
                    IExecutionSink resultsSink;
                    ConcurrentDictionary<string, ExecutionSummary> completionMessages = new ConcurrentDictionary<string, ExecutionSummary>();
                    IMessageSinkWithTypes reporterMessageHandler;
                    var reporters = GetAvailableRunnerReporters();
                    var commandLine = CommandLine.Parse(reporters, @"CoreXunit.dll");
                    IRunnerLogger logger = new ConsoleRunnerLogger(!commandLine.NoColor);
                    reporterMessageHandler = MessageSinkWithTypesAdapter.Wrap(commandLine.Reporter.CreateMessageHandler(logger));
                    var xmlElement = new XElement("TestResult");
                    resultsSink = new XmlAggregateSink(reporterMessageHandler, completionMessages, xmlElement, () => true);
                    var message = new Xunit.NullMessageSink();
                    var executionOptions = TestFrameworkOptions.ForExecution();
                    c.RunTests(tv.TestCases.Take<Xunit.Abstractions.ITestCase>(1), resultsSink, executionOptions);
                    resultsSink.Finished.WaitOne(o.TimeOut);
                    tv.TestCases.RemoveAt(0);
                    totalResult++;
                    totalErrors = totalErrors + resultsSink.ExecutionSummary.Errors;
                    totalFailed = totalFailed + resultsSink.ExecutionSummary.Failed;
                    totalSkipped = totalSkipped + resultsSink.ExecutionSummary.Skipped;
                    xmlElement.Save(file);
                    file.Flush();
                }
                file.Dispose();

                Console.WriteLine("Total tests: " + totalResult);
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.WriteLine("Error tests: " + totalErrors);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Failed tests: " + totalFailed);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("Skipped tests: " + totalSkipped);
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Passed tests: " + (totalResult - totalErrors - totalFailed - totalSkipped));
                Console.ResetColor();
            }
        }
Example #36
0
 public static bool Parse(string commandText)
 {
     return(CommandLine.Parse <Command>(commandText, InitializeCommandLineParser)
            .All(option => option.Execute()));
 }
Example #37
0
        static void Main(params string[] args)
        {
            System.Threading.Thread.CurrentThread.Name = "Manager";
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Parse Command Line options
            CommandLineOptions mpArgs = new CommandLineOptions();

            try
            {
                CommandLine.Parse(args, mpArgs);
            }
            catch (ArgumentException)
            {
                mpArgs.DisplayOptions();
                return;
            }

            using (new ServiceScope(true)) //This is the first servicescope
            {
                ApplicationCore.RegisterCoreServices();

                IPathManager pathManager = ServiceScope.Get <IPathManager>();
                // Check if user wants to override the default Application Data location.
                if (mpArgs.IsOption(CommandLineOptions.Option.Data))
                {
                    pathManager.ReplacePath("DATA", (string)mpArgs.GetOption(CommandLineOptions.Option.Data));
                }

                //Check whether the user wants to log method names in the logger
                //This adds an extra 10 to 40 milliseconds to the log call, depending on the length of the stack trace
                bool     logMethods = mpArgs.IsOption(CommandLineOptions.Option.LogMethods);
                LogLevel level      = LogLevel.All;
                if (mpArgs.IsOption(CommandLineOptions.Option.LogLevel))
                {
                    level = (LogLevel)mpArgs.GetOption(CommandLineOptions.Option.LogLevel);
                }
                ILogger logger = ServiceScope.Get <ILogger>();
                logger.Level          = level;
                logger.LogMethodNames = logMethods;

                logger.Debug("Manager: Registering Strings Manager");
                ServiceScope.Add <ILocalisation>(new StringManager());

#if !DEBUG
                // Not in Debug mode (ie Release) then catch all Exceptions
                // In Debug mode these will be left unhandled.
                try
                {
#endif
                // Start the system
                logger.Debug("ApplicationLauncher: Starting MediaPortal manager");

                IPluginManager pluginManager = ServiceScope.Get <IPluginManager>();
                pluginManager.Initialize();
                pluginManager.Startup(true);
                Application.Run(new MainWindow());
                pluginManager.Shutdown();

#if !DEBUG
            }
            catch (Exception ex)
            {
                CrashLogger crash = new CrashLogger(pathManager.GetPath("<LOG>"));
                crash.CreateLog(ex);
                //Form frm =
                //  new YesNoDialogScreen("MediaPortal 2", "Unrecoverable Error",
                //                        "MediaPortal has encountered an unrecoverable error\r\nDetails have been logged\r\n\r\nRestart?",
                //                        BaseScreen.Image.bug);
                //restart = frm.ShowDialog() == DialogResult.Yes;
            }
#endif
            }
        }
Example #38
0
 private static void WriteWarning(string message)
 {
     CommandLine.WriteLineColor(ConsoleColor.Yellow, Strings.WarningMessage(message));
 }
Example #39
0
 private static void WriteVerbose(string message)
 {
     CommandLine.WriteLineColor(ConsoleColor.DarkGray, message);
 }
Example #40
0
        public static async Task Run()
        {
            // Disable Grpc logging
            GrpcEnvironment.DisableLogging();

            // Locals
            var client = default(SimpleClient);

            try
            {
                // Get examples config
                var config = Utilities.GetConfig();

                // Create a Native .Net BigTable Client
                client = new SimpleClient(config);

                // Connect to the Googles
                await client.Connect();

                // Get a list of table names
                var tableNames = client.GetTableNames().Result;

                // Ensure pricing table exists
                if (!tableNames.Value.Contains(Constants.PricingTable))
                {
                    // Inform user
                    CommandLine.InformUser("Setup", "Missing example table.  Please run the Examples.Bootstrap project.");

                    // Hard stop
                    return;
                }

                // Show the user
                DisplayTables(tableNames);

                // Wait for keypress
                CommandLine.WaitForUserAndThen("scan for rows");

                // Scan for data
                var rows = client.Scan(Constants.PricingTable, Constants.ScanKeyStart, Constants.ScanKeyEnd).Result;

                // Show the user
                DisplayRows(rows);

                // Wait for keypress
                CommandLine.WaitForUserAndThen("seek for row");

                // Seek for data
                var row = client.Seek(Constants.PricingTable, Constants.SeekKey).Result;

                // Show the user
                DisplayRows(row);
            }
            catch (Exception exception)
            {
                CommandLine.InformUser("Oops", "Example didn't work out as planned");
                CommandLine.RenderException(exception);
            }
            finally
            {
                // Pretty
                Console.WriteLine();

                // Dispose
                if (client != default(SimpleClient))
                {
                    client.Dispose();
                }

                // All done
                CommandLine.WaitForUserAndThen("exit");
            }
        }
Example #41
0
 public void OnNext(BigRow value)
 {
     //Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
     CommandLine.DisplayRows(new[] { value });
 }
Example #42
0
 private static void WriteError(string message)
 {
     CommandLine.WriteLineColor(ConsoleColor.Red, Strings.ErrorMessage(message));
 }
Example #43
0
        private static int Main()
        {
            if (CommandLine.ContainParameter("breakintodebugger"))
            {
#if NETFRAMEWORK
                if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                {
                    System.Windows.Forms.MessageBox.Show("Debugger requested. Please attach a debugger and press OK");
                }
                else
#endif
                {
                    Console.WriteLine("Debugger requested. Please attach a debugger and press ENTER to continue");
                    while (Console.ReadKey(true).Key != ConsoleKey.Enter)
                    {
                        Console.WriteLine("Press ENTER to continue");
                    }
                }
                Debugger.Break();
            }
            // This GC gives a little bit better results than the other ones. "LowLatency" is giving really bad results(twice slower than the other ones).
            System.Runtime.GCSettings.LatencyMode = System.Runtime.GCLatencyMode.SustainedLowLatency;

            AppDomain currentDomain = AppDomain.CurrentDomain;
            currentDomain.UnhandledException += AppDomain_UnhandledException;

            Mutex    oneInstanceMutex = null;
            Argument parameters       = new Argument();
            ExitCode exitCode         = ExitCode.Success;

            try
            {
                DebugEnable = CommandLine.ContainParameter("verbose") || CommandLine.ContainParameter("debug") || CommandLine.ContainParameter("diagnostics");

                var     sharpmakeAssembly    = Assembly.GetExecutingAssembly();
                Version version              = sharpmakeAssembly.GetName().Version;
                string  versionString        = string.Join(".", version.Major, version.Minor, version.Build);
                string  informationalVersion = sharpmakeAssembly.GetCustomAttribute <AssemblyInformationalVersionAttribute>()?.InformationalVersion;
                if (version.Revision != 0 || (informationalVersion != null && informationalVersion.IndexOf("+Branch.") == -1))
                {
                    versionString += " (non-official)";
                    if (DebugEnable && informationalVersion != null)
                    {
                        versionString += " " + informationalVersion;
                    }
                }

                LogWriteLine($"sharpmake {versionString}");
                LogWriteLine("  arguments: {0}", CommandLine.GetProgramCommandLine());
                LogWriteLine("  directory: {0}", Directory.GetCurrentDirectory());
                LogWriteLine("  platform: {0} - {1}", Util.GetExecutingPlatform().ToString(), RuntimeInformation.OSDescription);
                LogWriteLine("  compiled with framework: {0}", Util.FrameworkDisplayName());
                LogWriteLine("  running on framework: {0}", RuntimeInformation.FrameworkDescription);
                LogWriteLine(string.Empty);

                // display help if wanted and quit
                if ((CommandLine.GetProgramCommandLine().Length == 0) || CommandLine.ContainParameter("help"))
                {
                    LogWriteLine(CommandLine.GetCommandLineHelp(typeof(Argument), false));
                    return(CommandLine.ContainParameter("help") ? (int)ExitCode.Success : (int)ExitCode.Error);
                }

                AppDomain.CurrentDomain.AssemblyLoad += AppDomain_AssemblyLoad;

                // Log warnings and errors from builder
                Assembler.EventOutputError   += ErrorWrite;
                Assembler.EventOutputWarning += WarningWrite;

                CommandLine.ExecuteOnObject(parameters);

                if (parameters.Exit)
                {
                    return((int)ExitCode.Success);
                }

                const string  sharpmakeSymbolPrefix = "_SHARPMAKE";
                List <string> invalidSymbols        = parameters.Defines.Where(define => define.StartsWith(sharpmakeSymbolPrefix)).ToList();
                if (invalidSymbols.Any())
                {
                    string invalidSymbolsString = string.Join(", ", invalidSymbols);
                    throw new Error($"Only Sharpmake process can define symbols starting with {sharpmakeSymbolPrefix}. Invalid symbols defined: {invalidSymbolsString}");
                }

                parameters.Defines.Add(sharpmakeSymbolPrefix); // A generic sharpmake define to allow scripts to exclude part of code if not used with sharpmake
                parameters.Defines.Add($"{sharpmakeSymbolPrefix}_{version.Major}_{version.Minor}_X");
                parameters.Defines.Add($"{sharpmakeSymbolPrefix}_{version.Major}_{version.Minor}_{version.Build}");

                parameters.Validate();

                // CommonPlatforms.dll is always loaded by default because those are shipped with
                // the Sharpmake package.
                PlatformRegistry.RegisterExtensionAssembly(typeof(Windows.Win32Platform).Assembly);

                // If any platform declares its own command line options, execute and validate
                // them as well.
                IEnumerable <Platform> platformsCmdLines = PlatformRegistry.GetAvailablePlatforms <ICommandLineInterface>();
                foreach (var platform in platformsCmdLines)
                {
                    var platformCmdLine = PlatformRegistry.Get <ICommandLineInterface>(platform);
                    CommandLine.ExecuteOnObject(platformCmdLine);
                    platformCmdLine.Validate();
                }

                bool   oneInstanceMutexCreated;
                string mutexName = string.Format("SharpmakeSingleInstanceMutex{0}", parameters.MutexSuffix); // Allow custom mutex name suffix. Useful to debug concurrently multiple sharpmake running from different branches
                oneInstanceMutex = new Mutex(true, mutexName, out oneInstanceMutexCreated);

                if (!oneInstanceMutexCreated)
                {
                    try
                    {
                        if (!oneInstanceMutex.WaitOne(0))
                        {
                            LogWriteLine("wait for another instance(s) of sharpmake to terminate...");
                            oneInstanceMutex.WaitOne();
                        }
                    }
                    catch (AbandonedMutexException)
                    {
                        // This occurs if another sharpmake is killed in the debugger
                    }
                    finally
                    {
                        LogWriteLine("waiting done.");
                    }
                }

                if (parameters.RegexMatchCacheEnabled)
                {
                    GlobalRegexMatchCache.Init(parameters.RegexMatchCacheInitialCapacity);
                }

                switch (parameters.TestOption)
                {
                case TestOptions.Regression:
                {
                    var regressionTest = new BuildContext.RegressionTest(parameters.OutputDirectory, parameters.ReferenceDirectory, parameters.RemapRoot);
                    GenerateAll(regressionTest, parameters);
                    exitCode = ExitCode.Success;

                    var regressions = regressionTest.GetRegressions().ToList();
                    if (regressions.Count > 0)
                    {
                        exitCode = ExitCode.Error;
                        DebugWriteLine($"{regressions.Count} Regressions detected:");
                        List <BuildContext.RegressionTest.OutputInfo> fileChanges = regressions.Where(x => x.FileStatus == BuildContext.RegressionTest.FileStatus.Different).ToList();
                        LogFileChanges(fileChanges, parameters.RegressionDiff);

                        var fileMissing = regressions.Where(x => x.FileStatus == BuildContext.RegressionTest.FileStatus.NotGenerated).Select(x => x.ReferencePath).ToList();
                        if (fileMissing.Count > 0)
                        {
                            fileMissing.Sort();
                            DebugWriteLine($"  {fileMissing.Count} files are missing from the output:");
                            fileMissing.ForEach(x => DebugWriteLine($"    {x}"));
                        }
                    }
                }
                break;

                case TestOptions.QuickConfigure:
                {
                    exitCode = AnalyzeConfigureOrder(parameters, true);
                }
                break;

                case TestOptions.Configure:
                {
                    exitCode = AnalyzeConfigureOrder(parameters, false);
                }
                break;

                case TestOptions.None:
                default:
                {
                    if (parameters.OutputDirectory != null)
                    {
                        // output redirect mode
                        var redirectOutput = new BuildContext.RedirectOutput(parameters.OutputDirectory, parameters.RemapRoot);
                        GenerateAll(redirectOutput, parameters);
                        exitCode = ExitCode.Success;
                    }
                    else
                    {
                        var generateAll = new BuildContext.GenerateAll(parameters.DebugLog, parameters.WriteFiles);
                        GenerateAll(generateAll, parameters);
                        exitCode = ExitCode.Success;

                        Util.ExecuteFilesAutoCleanup();
                    }
                }
                break;
                }

                if (CSproj.AllCsProjSubTypesInfos.Any())
                {
                    Util.SerializeAllCsprojSubTypes(CSproj.AllCsProjSubTypesInfos);
                }

                if (parameters.RegexMatchCacheEnabled)
                {
                    int regexMatchCacheInitialCapacity = parameters.RegexMatchCacheInitialCapacity;
                    int regexMatchCacheSize            = GlobalRegexMatchCache.Count;
                    if (regexMatchCacheInitialCapacity < regexMatchCacheSize)
                    {
                        WarningWriteLine("Warning (perf): Consider increasing regex match cache initial capacity from {0} to at least {1} ( /regexMatchCacheInitialCapacity({1}) ).", regexMatchCacheInitialCapacity, regexMatchCacheSize);
                    }

                    GlobalRegexMatchCache.UnInit();
                }
            }
            catch (Error e)
            {
                // Log error message
                Exception innerException = e;
                while (innerException.InnerException != null)
                {
                    innerException = innerException.InnerException;
                }
                ErrorWriteLine(Environment.NewLine + "Error:" + Environment.NewLine + innerException.Message);

                // Then log details
                LogWriteLine(Util.GetCompleteExceptionMessage(e, "\t"));
                exitCode = ExitCode.Error;
            }
            catch (InternalError e)
            {
                ErrorWriteLine(Environment.NewLine + "Internal Error:");
                LogWriteLine(Util.GetCompleteExceptionMessage(e, "\t"));
                exitCode = ExitCode.InternalError;
            }
#if !DEBUG // Use this to catch right away if an exception throw
            catch (Exception e)
            {
                LogWriteLine(Environment.NewLine + "Exception Error:");
                LogWriteLine(Util.GetCompleteExceptionMessage(e, "\t"));
                exitCode = ExitCode.UnknownError;
            }
#endif
            finally
            {
                if (oneInstanceMutex != null)
                {
                    oneInstanceMutex.ReleaseMutex();
                    GC.KeepAlive(oneInstanceMutex);
                }

                if (parameters.Debug)
                {
                    Console.WriteLine("DEBUG Sharpmake.Application: Press any key to exit...");
                    Console.ReadKey();
                }
            }

            LogWriteLine(@"{0} errors, {1} warnings", s_errorCount, s_warningCount);
            if (s_errorCount != 0)
            {
                if (Debugger.IsAttached)
                {
                    LogWriteLine("Please look at the errors.");
                    Debugger.Break();
                }
            }

            // returning exit code and error count separately because they can result in an exit code of 0 if they are added together.
            if (s_errorCount != 0)
            {
                return(s_errorCount);
            }
            return((int)exitCode);
        }
Example #44
0
        /// <inheritdoc/>
        public override void Run(CommandLine commandLine)
        {
            if (commandLine.HasHelpOption)
            {
                Console.WriteLine(usage);
                Program.Exit(0);
            }

            var cluster    = Program.GetCluster();
            var extensions = KubeHelper.CurrentContext.Extension;

            NodeDefinition node;

            if (commandLine.Arguments.Length == 0)
            {
                node = cluster.GetReachableMaster().Metadata;
            }
            else
            {
                var name = commandLine.Arguments[0];

                node = cluster.Definition.Nodes.SingleOrDefault(n => n.Name == name);

                if (node == null)
                {
                    Console.Error.WriteLine($"*** ERROR: The node [{name}] was not found.");
                    Program.Exit(1);
                }
            }

            // The host's SSH key fingerprint looks something like the example below.
            // We need to extract extract the bitcount and MD5 hash to generate a
            // WinSCP compatible host key fingerprint.
            //
            //      2048 MD5:cb:2f:f1:68:4b:aa:b3:8a:72:4d:53:f6:9f:5f:6a:fa root@manage-0 (RSA)

            const string md5Pattern = "MD5:";
            string       fingerprint;
            int          bitCount;
            string       md5;
            int          startPos;
            int          endPos;

            endPos = extensions.SshNodeFingerprint.IndexOf(' ');

            if (!int.TryParse(extensions.SshNodeFingerprint.Substring(0, endPos), out bitCount) || bitCount <= 0)
            {
                Console.Error.WriteLine($"*** ERROR: Cannot parse host's SSH key fingerprint [{extensions.SshNodeFingerprint}].");
                Program.Exit(1);
            }

            startPos = extensions.SshNodeFingerprint.IndexOf(md5Pattern);

            if (startPos == -1)
            {
                Console.Error.WriteLine($"*** ERROR: Cannot parse host's SSH key fingerprint [{extensions.SshNodeFingerprint}].");
                Program.Exit(1);
            }

            startPos += md5Pattern.Length;

            endPos = extensions.SshNodeFingerprint.IndexOf(' ', startPos);

            if (endPos == -1)
            {
                md5 = extensions.SshNodeFingerprint.Substring(startPos).Trim();
            }
            else
            {
                md5 = extensions.SshNodeFingerprint.Substring(startPos, endPos - startPos).Trim();
            }

            fingerprint = $"ssh-rsa {bitCount} {md5}";

            // Launch WinSCP.

            if (!File.Exists(Program.WinScpPath))
            {
                Console.Error.WriteLine($"*** ERROR: WinSCP application is not installed at [{Program.WinScpPath}].");
                Program.Exit(1);
            }

            Process.Start(Program.WinScpPath, $@"scp://{extensions.SshUsername}:{extensions.SshPassword}@{node.PrivateAddress}:22 /hostkey=""{fingerprint}"" /newinstance /rawsettings Shell=""sudo%20-s"" compression=1");
        }
Example #45
0
 private void OnPageLoaded(object sender, RoutedEventArgs e)
 {
     CommandLine.Focus(FocusState.Pointer);
 }
Example #46
0
 public void OnError(Exception exception)
 {
     CommandLine.RenderException(exception);
 }
        /// <summary>
        /// Parse the command line options for this extension.
        /// </summary>
        /// <param name="type">The active harvester type.</param>
        /// <param name="args">The option arguments.</param>
        public override void ParseOptions(string type, string[] args)
        {
            if ("project" == type)
            {
                string[]     allOutputGroups  = VSProjectHarvester.GetOutputGroupNames();
                bool         suppressUniqueId = false;
                bool         generateWixVars  = false;
                GenerateType generateType     = GenerateType.Components;
                string       directoryIds     = null;
                string       projectName      = null;
                string       configuration    = null;
                string       platform         = null;
                ArrayList    outputGroups     = new ArrayList();

                for (int i = 0; i < args.Length; i++)
                {
                    if ("-configuration" == args[i])
                    {
                        configuration = args[++i];
                    }
                    else if ("-directoryid" == args[i])
                    {
                        if (!CommandLine.IsValidArg(args, ++i))
                        {
                            throw new WixException(VSErrors.InvalidDirectoryId(args[i]));
                        }

                        directoryIds = args[i];
                    }
                    else if ("-generate" == args[i])
                    {
                        if (!CommandLine.IsValidArg(args, ++i))
                        {
                            throw new WixException(VSErrors.InvalidOutputType(args[i]));
                        }

                        string genType = args[i].ToUpperInvariant();
                        switch (genType)
                        {
                        case "LAYOUT":
                            generateType = GenerateType.Layout;
                            break;

                        case "CONTAINER":
                            generateType = GenerateType.Container;
                            break;

                        case "COMPONENTS":
                            generateType = GenerateType.Components;
                            break;

                        case "PACKAGEGROUP":
                            generateType = GenerateType.PackageGroup;
                            break;

                        case "PAYLOADGROUP":
                            generateType = GenerateType.PayloadGroup;
                            break;

                        default:
                            throw new WixException(VSErrors.InvalidOutputType(genType));
                        }
                    }
                    else if ("-platform" == args[i])
                    {
                        platform = args[++i];
                    }
                    else if ("-pog" == args[i])
                    {
                        if (!CommandLine.IsValidArg(args, ++i))
                        {
                            throw new WixException(VSErrors.InvalidOutputGroup(args[i]));
                        }

                        string pogName = args[i];
                        bool   found   = false;
                        foreach (string availableOutputGroup in allOutputGroups)
                        {
                            if (String.Equals(pogName, availableOutputGroup, StringComparison.Ordinal))
                            {
                                outputGroups.Add(availableOutputGroup);
                                found = true;
                                break;
                            }
                        }

                        if (!found)
                        {
                            throw new WixException(VSErrors.InvalidOutputGroup(pogName));
                        }
                    }
                    else if (args[i].StartsWith("-pog:", StringComparison.Ordinal))
                    {
                        this.MessageHandler.Display(this, WixWarnings.DeprecatedCommandLineSwitch("pog:", "pog"));

                        string pogName = args[i].Substring(5);
                        bool   found   = false;
                        foreach (string availableOutputGroup in allOutputGroups)
                        {
                            if (String.Equals(pogName, availableOutputGroup, StringComparison.Ordinal))
                            {
                                outputGroups.Add(availableOutputGroup);
                                found = true;
                                break;
                            }
                        }

                        if (!found)
                        {
                            throw new WixException(VSErrors.InvalidOutputGroup(pogName));
                        }
                    }
                    else if ("-projectname" == args[i])
                    {
                        if (!CommandLine.IsValidArg(args, ++i))
                        {
                            throw new WixException(VSErrors.InvalidProjectName(args[i]));
                        }

                        projectName = args[i];
                    }
                    else if ("-suid" == args[i])
                    {
                        suppressUniqueId = true;
                    }
                    else if ("-wixvar" == args[i])
                    {
                        generateWixVars = true;
                    }
                }

                if (outputGroups.Count == 0)
                {
                    throw new WixException(VSErrors.NoOutputGroupSpecified());
                }

                VSProjectHarvester harvester = new VSProjectHarvester(
                    (string[])outputGroups.ToArray(typeof(string)));

                harvester.SetUniqueIdentifiers = !suppressUniqueId;
                harvester.GenerateWixVars      = generateWixVars;
                harvester.GenerateType         = generateType;
                harvester.DirectoryIds         = directoryIds;
                harvester.ProjectName          = projectName;
                harvester.Configuration        = configuration;
                harvester.Platform             = platform;

                this.Core.Harvester.Extension = harvester;
            }
        }
        public void ReadXml(XmlReader reader)
        {
            Utility.Code.Require(reader, "reader");

            string extension = reader.GetAttribute(Xml.Type);

            if (!string.IsNullOrEmpty(extension))
            {
                this.ExtensionType = new Regex(extension);
            }

            reader.ReadStartElement();

            reader.ConsumeUntilFirst(XmlReaderHelper.ElementFilter);

            string name = reader.Name;

            if ((name == Xml.DiscoveryCommandLine) || (name == Xml.DiscoveryFileMap))
            {
                this.DiscoveryMethodType = (DiscoveryMethodType)Enum.Parse(typeof(DiscoveryMethodType), name);

                bool empty = reader.IsEmptyElement;

                reader.ReadStartElement();
                if (name == Xml.DiscoveryCommandLine)
                {
                    empty = false;
                    this.DiscoveryCommandLine = CommandLine.FromString(reader.ReadString());
                }
                else if (name == Xml.DiscoveryFileMap)
                {
                    reader.ConsumeUntilFirst(XmlReaderHelper.ElementFilter);
                    while (reader.NodeType == XmlNodeType.Element)
                    {
                        string key = reader.GetAttribute(Xml.DiscoveryFileMapSource);

                        reader.MoveToElement();
                        empty = reader.IsEmptyElement;
                        reader.ReadStartElement();

                        this.DiscoveryFileMap[key] = (empty) ? string.Empty : reader.ReadString();

                        if (!empty)
                        {
                            reader.ReadEndElement();
                        }

                        reader.ConsumeUntilFirst(XmlReaderHelper.ElementFilter);
                    }
                }

                if (!empty)
                {
                    reader.ReadEndElement();
                }

                reader.ConsumeUntilFirst(XmlReaderHelper.ElementFilter);
            }

            this.ExecutionCommandLine = CommandLine.FromString(reader.ReadElementString(Xml.ExecutionCommandLine));

            reader.ReadEndElement();
        }
 public static string[] GetCommandLineArgs() => CommandLine.InternalCreateCommandLine(includeArg0: true);
Example #50
0
 private void CloseStatusButton_Click(object sender, RoutedEventArgs e)
 {
     CmdEnabledStatusPopup.IsOpen = false;
     CommandLine.Focus(FocusState.Keyboard);
 }
Example #51
0
 /// <inheritdoc/>
 public override async Task RunAsync(CommandLine commandLine)
 {
     Help();
     Program.Exit(commandLine.Arguments.Length == 0 ? 0 : 1);
     await Task.CompletedTask;
 }
Example #52
0
    static int Main()
    {
#if USE_EVENTSOURCE_REFLECTION
        // If this app does not take a dependency on a specific EventSource implementation we'll need to use the EventSource
        // type that represents the base type of the custom event source that needs to be registered. To accomplish this we
        // need to set up a separate domain that has the app base set to the location of the assembly to be registered, and
        // the config file set to the config file that might be associated with this assembly, in the case the assembly is
        // an EXE. Having the worker domain set up in this way allows for the regular assembly lookup rules to kick in and
        // perform the expected lookup the the EventSource-base assembly based on the passed in assembly.
        // In the worker domain we load in the "reflection-only" context the assembly passed in as an argument and allow its
        // dependency to be loaded as well. Once the base assembly is loaded in the reflection-only context we retrieve its
        // location and call LoadFrom() on the assembly in order to get access to the EventSource static methods we need to
        // call.
        var workerDomainFriendlyName = "eventRegister_workerDomain";
        if (AppDomain.CurrentDomain.FriendlyName != workerDomainFriendlyName)
        {
            // See code:#CommandLineDefinitions for Command line defintions
            CommandLine commandLine = new CommandLine();
            var         ads         = new AppDomainSetup();
            // ads.PrivateBinPath = Path.GetDirectoryName(Path.GetFullPath(commandLine.DllPath));
            ads.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
            // ads.ApplicationBase = Path.GetDirectoryName(Path.GetFullPath(commandLine.DllPath));
            // var configName = Path.GetFullPath(commandLine.DllPath) + ".config";
            // if (Path.GetExtension(commandLine.DllPath) == ".exe" && File.Exists(configName))
            //     ads.ConfigurationFile = configName;
            var workerDom = AppDomain.CreateDomain(workerDomainFriendlyName, null, ads, new System.Security.PermissionSet(System.Security.Permissions.PermissionState.Unrestricted));
            // make sure the worker domain is aware of the additional paths to probe when resolving the EventSource base type
            if (commandLine.ReferencePath != null)
            {
                workerDom.SetData("ReferencePath", Environment.ExpandEnvironmentVariables(commandLine.ReferencePath));
            }
            return(workerDom.ExecuteAssembly(typeof(Program).Assembly.Location));
        }
        else
#endif
        return(CommandLineUtilities.RunConsoleMainWithExceptionProcessing(delegate
        {
            // See code:#CommandLineDefinitions for Command line defintions
            CommandLine commandLine = new CommandLine();
            List <Tuple <string, string> > regDlls;
            EventSourceReflectionProxy.ManifestGenerator = commandLine.ManifestGenerator;
            switch (commandLine.Command)
            {
            // Create the XML description in the data directory "will be called
            case CommandLine.CommandType.DumpManifest:
                var manifests = CreateManifestsFromManagedDll(commandLine.DllPath, commandLine.ManifestPrefix);
                if (manifests.Count == 0)
                {
                    Console.WriteLine("Info: No event source classes " + (commandLine.ForceAll ? "" : "needing registration ") + "found in " + commandLine.DllPath);
                }
                break;

            case CommandLine.CommandType.CompileManifest:
                CompileManifest(commandLine.ManPath, System.IO.Path.ChangeExtension(commandLine.ManPath, ".dll"));
                break;

            case CommandLine.CommandType.DumpRegDlls:
                regDlls = CreateRegDllsFromManagedDll(commandLine.DllPath, commandLine.ForceAll, commandLine.ManifestPrefix);
                if (regDlls.Count == 0)
                {
                    Console.WriteLine("Info: No event source classes " + (commandLine.ForceAll ? "" : "needing registration ") + "found in " + commandLine.DllPath);
                }
                break;

            case CommandLine.CommandType.Install:
                regDlls = RegisterManagedDll(commandLine.DllPath, false, commandLine.ManifestPrefix);
                if (regDlls.Count == 0)
                {
                    Console.WriteLine("Info: No event source classes " + (commandLine.ForceAll ? "" : "needing registration ") + "found in " + commandLine.DllPath);
                }
                break;

            case CommandLine.CommandType.Uninstall:
                regDlls = RegisterManagedDll(commandLine.DllPath, true, commandLine.ManifestPrefix);
                if (regDlls.Count == 0)
                {
                    Console.WriteLine("Info: No event source classes " + (commandLine.ForceAll ? "" : "needing registration ") + "found in " + commandLine.DllPath);
                }
                break;
            }
            return 0;
        }));
    }
Example #53
0
        public static int MainInner()
        {
            TextEncoding.WritingDefault = TextEncoding.UTF8;

            var CmdLine = CommandLine.GetCmdLine();
            var argv    = CmdLine.Arguments;

            if (CmdLine.Arguments.Length != 0)
            {
                DisplayInfo();
                return(-1);
            }

            if (CmdLine.Options.Length == 0)
            {
                DisplayInfo();
                return(0);
            }

            foreach (var opt in CmdLine.Options)
            {
                var optNameLower = opt.Name.ToLower();
                if ((optNameLower == "?") || (optNameLower == "help"))
                {
                    DisplayInfo();
                    return(0);
                }
                else if (optNameLower == "load")
                {
                    var args = opt.Arguments;
                    if (args.Length == 1)
                    {
                        var CookedObjectSchemaPath = args[0];
                        InvalidateSchema();
                        osl.LoadSchema(CookedObjectSchemaPath);
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "save")
                {
                    var args = opt.Arguments;
                    if (args.Length == 1)
                    {
                        var CookedObjectSchemaPath = args[0];
                        var s  = GetObjectSchema();
                        var ts = new TreeSerializer();
                        var t  = ts.Write(s);
                        TreeFile.WriteDirect(CookedObjectSchemaPath, t);
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "loadtyperef")
                {
                    var args = opt.Arguments;
                    if (args.Length == 1)
                    {
                        var ObjectSchemaPath = args[0];
                        if (Directory.Exists(ObjectSchemaPath))
                        {
                            foreach (var f in Directory.GetFiles(ObjectSchemaPath, "*.tree", SearchOption.AllDirectories).OrderBy(s => s, StringComparer.OrdinalIgnoreCase))
                            {
                                InvalidateSchema();
                                osl.LoadTypeRef(f);
                            }
                        }
                        else
                        {
                            InvalidateSchema();
                            osl.LoadTypeRef(ObjectSchemaPath);
                        }
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "loadtype")
                {
                    var args = opt.Arguments;
                    if (args.Length == 1)
                    {
                        var ObjectSchemaPath = args[0];
                        if (Directory.Exists(ObjectSchemaPath))
                        {
                            foreach (var f in Directory.GetFiles(ObjectSchemaPath, "*.tree", SearchOption.AllDirectories).OrderBy(s => s, StringComparer.OrdinalIgnoreCase))
                            {
                                InvalidateSchema();
                                osl.LoadType(f);
                            }
                        }
                        else
                        {
                            InvalidateSchema();
                            osl.LoadType(ObjectSchemaPath);
                        }
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "import")
                {
                    var args = opt.Arguments;
                    if (args.Length == 1)
                    {
                        osl.AddImport(args[0]);
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "async")
                {
                    var args = opt.Arguments;
                    if (args.Length == 1)
                    {
                        InvalidateSchema();
                        LoadAsync(args[0]);
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "t2b")
                {
                    var args = opt.Arguments;
                    if (args.Length == 3)
                    {
                        TreeToBinary(args[0], args[1], args[2]);
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "b2t")
                {
                    var args = opt.Arguments;
                    if (args.Length == 3)
                    {
                        BinaryToTree(args[0], args[1], args[2]);
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "t2vb")
                {
                    var args = opt.Arguments;
                    if (args.Length == 1)
                    {
                        ObjectSchemaToVBCode(args[0], "", true);
                    }
                    else if (args.Length == 2)
                    {
                        ObjectSchemaToVBCode(args[0], args[1], true);
                    }
                    else if (args.Length == 3)
                    {
                        ObjectSchemaToVBCode(args[0], args[1], Boolean.Parse(args[2]));
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "t2cs")
                {
                    var args = opt.Arguments;
                    if (args.Length == 1)
                    {
                        ObjectSchemaToCSharpCode(args[0], "", true);
                    }
                    else if (args.Length == 2)
                    {
                        ObjectSchemaToCSharpCode(args[0], args[1], true);
                    }
                    else if (args.Length == 3)
                    {
                        ObjectSchemaToCSharpCode(args[0], args[1], Boolean.Parse(args[2]));
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "t2csb")
                {
                    var args = opt.Arguments;
                    if (args.Length == 1)
                    {
                        ObjectSchemaToCSharpBinaryCode(args[0], "", true);
                    }
                    else if (args.Length == 2)
                    {
                        ObjectSchemaToCSharpBinaryCode(args[0], args[1], true);
                    }
                    else if (args.Length == 3)
                    {
                        ObjectSchemaToCSharpBinaryCode(args[0], args[1], Boolean.Parse(args[2]));
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "t2csj")
                {
                    var args = opt.Arguments;
                    if (args.Length == 1)
                    {
                        ObjectSchemaToCSharpJsonCode(args[0], "");
                    }
                    else if (args.Length == 2)
                    {
                        ObjectSchemaToCSharpJsonCode(args[0], args[1]);
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "t2csc")
                {
                    var args = opt.Arguments;
                    if (args.Length == 4)
                    {
                        ObjectSchemaToCSharpCompatibleCode(args[0], args[1], args[2], args[3]);
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "t2csv")
                {
                    var args = opt.Arguments;
                    if (args.Length >= 2)
                    {
                        ObjectSchemaToCSharpVersionCode(args[0], args[1], args.Skip(2).ToList());
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "t2jv")
                {
                    var args = opt.Arguments;
                    if (args.Length == 2)
                    {
                        ObjectSchemaToJavaCode(args[0], args[1]);
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "t2jvb")
                {
                    var args = opt.Arguments;
                    if (args.Length == 2)
                    {
                        ObjectSchemaToJavaBinaryCode(args[0], args[1]);
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "t2cpp")
                {
                    var args = opt.Arguments;
                    if (args.Length == 1)
                    {
                        ObjectSchemaToCppCode(args[0], "");
                    }
                    else if (args.Length == 2)
                    {
                        ObjectSchemaToCppCode(args[0], args[1]);
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "t2cppb")
                {
                    var args = opt.Arguments;
                    if (args.Length == 1)
                    {
                        ObjectSchemaToCppBinaryCode(args[0], "", true, true);
                    }
                    else if (args.Length == 2)
                    {
                        ObjectSchemaToCppBinaryCode(args[0], args[1], true, true);
                    }
                    else if (args.Length == 4)
                    {
                        ObjectSchemaToCppBinaryCode(args[0], args[1], Boolean.Parse(args[2]), Boolean.Parse(args[3]));
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "t2cppc")
                {
                    var args = opt.Arguments;
                    if (args.Length == 4)
                    {
                        ObjectSchemaToCppCompatibleCode(args[0], args[1], args[2], args[3]);
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "t2cppv")
                {
                    var args = opt.Arguments;
                    if (args.Length >= 2)
                    {
                        ObjectSchemaToCppVersionCode(args[0], args[1], args.Skip(2).ToList());
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "t2hx")
                {
                    var args = opt.Arguments;
                    if (args.Length == 2)
                    {
                        ObjectSchemaToHaxeCode(args[0], args[1]);
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "t2hxj")
                {
                    var args = opt.Arguments;
                    if (args.Length == 2)
                    {
                        ObjectSchemaToHaxeJsonCode(args[0], args[1]);
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "t2py")
                {
                    var args = opt.Arguments;
                    if (args.Length == 1)
                    {
                        ObjectSchemaToPythonCode(args[0]);
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "t2pyb")
                {
                    var args = opt.Arguments;
                    if (args.Length == 1)
                    {
                        ObjectSchemaToPythonBinaryCode(args[0]);
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "t2xhtml")
                {
                    var args = opt.Arguments;
                    if (args.Length == 3)
                    {
                        ObjectSchemaToXhtml(args[0], args[1], args[2]);
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "gentypecmpt")
                {
                    var args = opt.Arguments;
                    if (args.Length % 2 == 1)
                    {
                        var ListOfObjectSchemaDirOrCookedObjectSchemaFileAndVersion = new List <KeyValuePair <String, String> >();
                        for (int k = 0; k < args.Length - 1; k += 2)
                        {
                            ListOfObjectSchemaDirOrCookedObjectSchemaFileAndVersion.Add(new KeyValuePair <String, String>(args[k], args[k + 1]));
                        }
                        GenerateTypeCompatibilityTreeFile(ListOfObjectSchemaDirOrCookedObjectSchemaFileAndVersion, args[args.Length - 1]);
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else if (optNameLower == "gencomcmpt")
                {
                    var args = opt.Arguments;
                    if (args.Length % 2 == 1)
                    {
                        var ListOfObjectSchemaDirOrCookedObjectSchemaFileAndVersion = new List <KeyValuePair <String, String> >();
                        for (int k = 0; k < args.Length - 1; k += 2)
                        {
                            ListOfObjectSchemaDirOrCookedObjectSchemaFileAndVersion.Add(new KeyValuePair <String, String>(args[k], args[k + 1]));
                        }
                        GenerateTypeCompatibilityTreeFile(ListOfObjectSchemaDirOrCookedObjectSchemaFileAndVersion, args[args.Length - 1], true);
                    }
                    else
                    {
                        DisplayInfo();
                        return(-1);
                    }
                }
                else
                {
                    throw new ArgumentException(opt.Name);
                }
            }
            return(0);
        }
Example #54
0
        /// <summary>
        /// MultiNodeTestRunner takes the following <see cref="args"/>:
        ///
        /// C:\> Akka.MultiNodeTestRunner.exe [assembly name] [-Dmultinode.enable-filesink=on] [-Dmultinode.output-directory={dir path}] [-Dmultinode.spec={spec name}]
        ///
        /// <list type="number">
        /// <listheader>
        ///     <term>Argument</term>
        ///     <description>The name and possible value of a given Akka.MultiNodeTestRunner.exe argument.</description>
        /// </listheader>
        /// <item>
        ///     <term>AssemblyName</term>
        ///     <description>
        ///         The full path or name of an assembly containing as least one MultiNodeSpec in the current working directory.
        ///
        ///         i.e. "Akka.Cluster.Tests.MultiNode.dll"
        ///              "C:\akka.net\src\Akka.Cluster.Tests\bin\Debug\Akka.Cluster.Tests.MultiNode.dll"
        ///     </description>
        /// </item>
        /// <item>
        ///     <term>-Dmultinode.enable-filesink</term>
        ///     <description>Having this flag set means that the contents of this test run will be saved in the
        ///                 current working directory as a .JSON file.
        ///     </description>
        /// </item>
        /// <item>
        ///     <term>-Dmultinode.multinode.output-directory</term>
        ///     <description>Setting this flag means that any persistent multi-node test runner output files
        ///                  will be written to this directory instead of the default, which is the same folder
        ///                  as the test binary.
        ///     </description>
        /// </item>
        /// <item>
        ///     <term>-Dmultinode.listen-address={ip}</term>
        ///     <description>
        ///             Determines the address that this multi-node test runner will use to listen for log messages from
        ///             individual NodeTestRunner.exe processes.
        ///
        ///             Defaults to 127.0.0.1
        ///     </description>
        /// </item>
        /// <item>
        ///     <term>-Dmultinode.listen-port={port}</term>
        ///     <description>
        ///             Determines the port number that this multi-node test runner will use to listen for log messages from
        ///             individual NodeTestRunner.exe processes.
        ///
        ///             Defaults to 6577
        ///     </description>
        /// </item>
        /// <item>
        ///     <term>-Dmultinode.spec={spec name}</term>
        ///     <description>
        ///             Setting this flag means that only tests which contains the spec name will be executed
        ///             otherwise all tests will be executed
        ///     </description>
        /// </item>
        /// </list>
        /// </summary>
        static void Main(string[] args)
        {
            OutputDirectory      = CommandLine.GetPropertyOrDefault("multinode.output-directory", string.Empty);
            FailedSpecsDirectory = CommandLine.GetPropertyOrDefault("multinode.failed-specs-directory", "FAILED_SPECS_LOGS");

            string logLevel = CommandLine.GetPropertyOrDefault("multinode.loglevel", "WARNING");

            TestRunSystem = ActorSystem.Create("TestRunnerLogging", $"akka.loglevel={logLevel}");

            var suiteName            = Path.GetFileNameWithoutExtension(Path.GetFullPath(args[0].Trim('"')));
            var teamCityFormattingOn = CommandLine.GetPropertyOrDefault("multinode.teamcity", "false");

            if (!Boolean.TryParse(teamCityFormattingOn, out TeamCityFormattingOn))
            {
                throw new ArgumentException("Invalid argument provided for -Dteamcity");
            }

            var listenAddress  = IPAddress.Parse(CommandLine.GetPropertyOrDefault("multinode.listen-address", "127.0.0.1"));
            var listenPort     = CommandLine.GetInt32OrDefault("multinode.listen-port", 6577);
            var listenEndpoint = new IPEndPoint(listenAddress, listenPort);
            var specName       = CommandLine.GetPropertyOrDefault("multinode.spec", "");
            var platform       = CommandLine.GetPropertyOrDefault("multinode.platform", "net");
            var reporter       = CommandLine.GetPropertyOrDefault("multinode.reporter", "console");

            var clearOutputDirectory = CommandLine.GetInt32OrDefault("multinode.clear-output", 0);

            if (clearOutputDirectory > 0 && Directory.Exists(OutputDirectory))
            {
                Directory.Delete(OutputDirectory, true);
            }

            Props coordinatorProps;

            switch (reporter.ToLowerInvariant())
            {
            case "trx":
                coordinatorProps = Props.Create(() => new SinkCoordinator(new[] { new TrxMessageSink(suiteName) }));
                break;

            case "teamcity":
                coordinatorProps = Props.Create(() => new SinkCoordinator(new[] { new TeamCityMessageSink(Console.WriteLine, suiteName) }));
                break;

            case "console":
                coordinatorProps = Props.Create(() => new SinkCoordinator(new[] { new ConsoleMessageSink() }));
                break;

            default:
                throw new ArgumentException($"Given reporter name '{reporter}' is not understood, valid reporters are: trx and teamcity");
            }

            SinkCoordinator = TestRunSystem.ActorOf(coordinatorProps, "sinkCoordinator");

#if CORECLR
            if (!_validNetCorePlatform.Contains(platform))
            {
                throw new Exception($"Target platform not supported: {platform}. Supported platforms are net and netcore");
            }
#else
            if (platform != "net")
            {
                throw new Exception($"Target platform not supported: {platform}. Supported platforms are net");
            }
#endif

            var tcpLogger = TestRunSystem.ActorOf(Props.Create(() => new TcpLoggingServer(SinkCoordinator)), "TcpLogger");
            TestRunSystem.Tcp().Tell(new Tcp.Bind(tcpLogger, listenEndpoint), sender: tcpLogger);

            var assemblyPath = Path.GetFullPath(args[0].Trim('"')); //unquote the string first

            EnableAllSinks(assemblyPath, platform);
            PublishRunnerMessage($"Running MultiNodeTests for {assemblyPath}");
#if CORECLR
            // In NetCore, if the assembly file hasn't been touched,
            // XunitFrontController would fail loading external assemblies and its dependencies.
            var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath);
            var asms     = assembly.GetReferencedAssemblies();
            var basePath = Path.GetDirectoryName(assemblyPath);
            foreach (var asm in asms)
            {
                try
                {
                    Assembly.Load(new AssemblyName(asm.FullName));
                }
                catch (Exception)
                {
                    var path = Path.Combine(basePath, asm.Name + ".dll");
                    try
                    {
                        AssemblyLoadContext.Default.LoadFromAssemblyPath(path);
                    }
                    catch (Exception e)
                    {
                        Console.Out.WriteLine($"Failed to load dll: {path}");
                    }
                }
            }
#endif

            using (var controller = new XunitFrontController(AppDomainSupport.IfAvailable, assemblyPath))
            {
                using (var discovery = new Discovery())
                {
                    controller.Find(false, discovery, TestFrameworkOptions.ForDiscovery());
                    discovery.Finished.WaitOne();

                    if (discovery.WasSuccessful)
                    {
                        foreach (var test in discovery.Tests.Reverse())
                        {
                            if (!string.IsNullOrEmpty(test.Value.First().SkipReason))
                            {
                                PublishRunnerMessage($"Skipping test {test.Value.First().MethodName}. Reason - {test.Value.First().SkipReason}");
                                continue;
                            }

                            if (!string.IsNullOrWhiteSpace(specName) &&
                                CultureInfo.InvariantCulture.CompareInfo.IndexOf(test.Value.First().TestName,
                                                                                 specName,
                                                                                 CompareOptions.IgnoreCase) < 0)
                            {
                                PublishRunnerMessage($"Skipping [{test.Value.First().MethodName}] (Filtering)");
                                continue;
                            }

                            var processes = new List <Process>();

                            PublishRunnerMessage($"Starting test {test.Value.First().MethodName}");
                            Console.Out.WriteLine($"Starting test {test.Value.First().MethodName}");

                            StartNewSpec(test.Value);
#if CORECLR
                            var ntrNetPath     = Path.Combine(AppContext.BaseDirectory, "Akka.NodeTestRunner.exe");
                            var ntrNetCorePath = Path.Combine(AppContext.BaseDirectory, "Akka.NodeTestRunner.dll");
                            var alternateIndex = 0;
#endif
                            var    timelineCollector = TestRunSystem.ActorOf(Props.Create(() => new TimelineLogCollectorActor()));
                            string testOutputDir     = null;
                            string runningSpecName   = null;

                            foreach (var nodeTest in test.Value)
                            {
                                //Loop through each test, work out number of nodes to run on and kick off process
                                var sbArguments = new StringBuilder()
                                                  //.Append($@"-Dmultinode.test-assembly=""{assemblyPath}"" ")
                                                  .Append($@"-Dmultinode.test-class=""{nodeTest.TypeName}"" ")
                                                  .Append($@"-Dmultinode.test-method=""{nodeTest.MethodName}"" ")
                                                  .Append($@"-Dmultinode.max-nodes={test.Value.Count} ")
                                                  .Append($@"-Dmultinode.server-host=""{"localhost"}"" ")
                                                  .Append($@"-Dmultinode.host=""{"localhost"}"" ")
                                                  .Append($@"-Dmultinode.index={nodeTest.Node - 1} ")
                                                  .Append($@"-Dmultinode.role=""{nodeTest.Role}"" ")
                                                  .Append($@"-Dmultinode.listen-address={listenAddress} ")
                                                  .Append($@"-Dmultinode.listen-port={listenPort} ");

#if CORECLR
                                string fileName = null;
                                switch (platform)
                                {
                                case "net":
                                    fileName = ntrNetPath;
                                    sbArguments.Insert(0, $@" -Dmultinode.test-assembly=""{assemblyPath}"" ");
                                    break;

                                case "netcore":
                                case "net5":
                                    fileName = "dotnet";
                                    sbArguments.Insert(0, $@" -Dmultinode.test-assembly=""{assemblyPath}"" ");
                                    sbArguments.Insert(0, ntrNetCorePath);
                                    break;
                                }
                                var process = new Process
                                {
                                    StartInfo = new ProcessStartInfo
                                    {
                                        FileName               = fileName,
                                        UseShellExecute        = false,
                                        RedirectStandardOutput = true,
                                        Arguments              = sbArguments.ToString(),
                                        WorkingDirectory       = Path.GetDirectoryName(assemblyPath)
                                    }
                                };
#else
                                sbArguments.Insert(0, $@"-Dmultinode.test-assembly=""{assemblyPath}"" ");
                                var process = new Process
                                {
                                    StartInfo = new ProcessStartInfo
                                    {
                                        FileName               = "Akka.NodeTestRunner.exe",
                                        UseShellExecute        = false,
                                        RedirectStandardOutput = true,
                                        Arguments              = sbArguments.ToString()
                                    }
                                };
#endif

                                processes.Add(process);
                                var nodeIndex = nodeTest.Node;
                                var nodeRole  = nodeTest.Role;

#if CORECLR
                                if (platform == "netcore" || platform == "net5")
                                {
                                    process.StartInfo.FileName         = "dotnet";
                                    process.StartInfo.Arguments        = ntrNetCorePath + " " + process.StartInfo.Arguments;
                                    process.StartInfo.WorkingDirectory = Path.GetDirectoryName(assemblyPath);
                                }
#endif

                                //TODO: might need to do some validation here to avoid the 260 character max path error on Windows
                                var folder = Directory.CreateDirectory(Path.Combine(OutputDirectory, nodeTest.TestName));
                                testOutputDir = testOutputDir ?? folder.FullName;
                                var logFilePath = Path.Combine(folder.FullName, $"node{nodeIndex}__{nodeRole}__{platform}.txt");
                                runningSpecName = nodeTest.TestName;
                                var nodeInfo  = new TimelineLogCollectorActor.NodeInfo(nodeIndex, nodeRole, platform, nodeTest.TestName);
                                var fileActor = TestRunSystem.ActorOf(Props.Create(() => new FileSystemAppenderActor(logFilePath)));
                                process.OutputDataReceived += (sender, eventArgs) =>
                                {
                                    if (eventArgs?.Data != null)
                                    {
                                        fileActor.Tell(eventArgs.Data);
                                        timelineCollector.Tell(new TimelineLogCollectorActor.LogMessage(nodeInfo, eventArgs.Data));
                                        if (TeamCityFormattingOn)
                                        {
                                            // teamCityTest.WriteStdOutput(eventArgs.Data); TODO: open flood gates
                                        }
                                    }
                                };
                                var closureTest = nodeTest;
                                process.Exited += (sender, eventArgs) =>
                                {
                                    if (process.ExitCode == 0)
                                    {
                                        ReportSpecPassFromExitCode(nodeIndex, nodeRole, closureTest.TestName);
                                    }
                                };

                                process.Start();
                                process.BeginOutputReadLine();
                                PublishRunnerMessage($"Started node {nodeIndex} : {nodeRole} on pid {process.Id}");
                            }

                            var specFailed = false;
                            foreach (var process in processes)
                            {
                                process.WaitForExit();
                                specFailed = specFailed || process.ExitCode > 0;
                                process.Dispose();
                            }

                            PublishRunnerMessage("Waiting 3 seconds for all messages from all processes to be collected.");
                            Thread.Sleep(TimeSpan.FromSeconds(3));

                            if (testOutputDir != null)
                            {
                                var dumpTasks = new List <Task>()
                                {
                                    // Dump aggregated timeline to file for this test
                                    timelineCollector.Ask <Done>(new TimelineLogCollectorActor.DumpToFile(Path.Combine(testOutputDir, "aggregated.txt"))),
                                    // Print aggregated timeline into the console
                                    timelineCollector.Ask <Done>(new TimelineLogCollectorActor.PrintToConsole(logLevel))
                                };

                                if (specFailed)
                                {
                                    var dumpFailureArtifactTask = timelineCollector.Ask <Done>(
                                        new TimelineLogCollectorActor.DumpToFile(Path.Combine(Path.GetFullPath(OutputDirectory), FailedSpecsDirectory, $"{runningSpecName}.txt")));
                                    dumpTasks.Add(dumpFailureArtifactTask);
                                }
                                Task.WaitAll(dumpTasks.ToArray());
                            }

                            FinishSpec(test.Value, timelineCollector);
                        }
                        Console.WriteLine("Complete");
                        PublishRunnerMessage("Waiting 5 seconds for all messages from all processes to be collected.");
                        Thread.Sleep(TimeSpan.FromSeconds(5));
                    }
                    else
                    {
                        var sb = new StringBuilder();
                        sb.AppendLine("One or more exception was thrown while discovering test cases. Test Aborted.");
                        foreach (var err in discovery.Errors)
                        {
                            for (int i = 0; i < err.ExceptionTypes.Length; ++i)
                            {
                                sb.AppendLine();
                                sb.Append($"{err.ExceptionTypes[i]}: {err.Messages[i]}");
                                sb.Append(err.StackTraces[i]);
                            }
                        }
                        PublishRunnerMessage(sb.ToString());
                        Console.Out.WriteLine(sb.ToString());
                    }
                }
            }

            AbortTcpLoggingServer(tcpLogger);
            CloseAllSinks();

            //Block until all Sinks have been terminated.
            TestRunSystem.WhenTerminated.Wait(TimeSpan.FromMinutes(1));

            if (Debugger.IsAttached)
            {
                Console.ReadLine(); //block when debugging
            }
            //Return the proper exit code
            Environment.Exit(ExitCodeContainer.ExitCode);
        }
Example #55
0
        /* Function: ParseCommandLine
         *
         * Parses the command line and applies the relevant settings in in <NaturalDocs.Engine's> modules.  If there were
         * errors they will be placed on errorList and it will return <ParseCommandLineResult.Error>.
         *
         * Supported:
         *
         *		- -i, --input, --source
         *		- -o, --output
         *		- -p, --project, --project-config --project-configuration
         *		- -w, --data, --working-data
         *		- -xi, --exclude-input, --exclude-source
         *		- -xip, --exclude-input-pattern, --exclude-source-pattern
         *		- -img, --images
         *		- -t, --tab, --tab-width, --tab-length
         *		- -do, --documented-only
         *		- -nag, --no-auto-group
         *		- -s, --style
         *		- -r, --rebuild
         *		- -ro, --rebuild-output
         *		- -q, --quiet
         *		- -v, --version
         *		- --benchmark
         *		- --worker-threads, --threads
         *		- --pause-before-exit, --pause
         *		- --pause-on-error
         *		- --dont-shrink-files
         *		- -h, --help
         *		- -?
         *
         * No Longer Supported:
         *
         *		- -cs, --char-set, --charset, --character-set, --characterset
         *		- -ho, --headers-only, --headersonly
         *		- -ag, --auto-group, --autogroup
         */
        private static ParseCommandLineResult ParseCommandLine(string[] commandLineSegments, out ProjectConfig commandLineConfig, ErrorList errorList)
        {
            int originalErrorCount = errorList.Count;

            Engine.CommandLine commandLine = new CommandLine(commandLineSegments);

            commandLine.AddAliases("--input", "-i", "--source");
            commandLine.AddAliases("--output", "-o");
            commandLine.AddAliases("--project", "-p", "--project-config", "--projectconfig", "--project-configuration", "--projectconfiguration");
            commandLine.AddAliases("--working-data", "-w", "--data", "--workingdata");
            commandLine.AddAliases("--exclude-input", "-xi", "--excludeinput", "--exclude-source", "--excludesource");
            commandLine.AddAliases("--exclude-input-pattern", "-xip", "--excludeinputpattern", "--exclude-source-pattern", "--excludesourcepattern");
            commandLine.AddAliases("--images", "-img");
            commandLine.AddAliases("--tab-width", "-t", "--tab", "--tabwidth", "--tab-length", "--tablength");
            commandLine.AddAliases("--documented-only", "-do", "--documentedonly");
            commandLine.AddAliases("--no-auto-group", "-nag", "--noautogroup");
            commandLine.AddAliases("--style", "-s");
            commandLine.AddAliases("--rebuild", "-r");
            commandLine.AddAliases("--rebuild-output", "-ro", "--rebuildoutput");
            commandLine.AddAliases("--quiet", "-q");
            commandLine.AddAliases("--version", "-v");
            commandLine.AddAliases("--pause-before-exit", "--pausebeforexit", "--pause");
            commandLine.AddAliases("--pause-on-error", "--pauseonerror");
            commandLine.AddAliases("--dont-shrink-files", "--dontshrinkfiles", "--dont-shrink-output", "--dontshrinkoutput", "--dont-shrink", "--dontshrink");
            commandLine.AddAliases("--worker-threads", "--threads");
            // no aliases for --benchmark
            commandLine.AddAliases("--help", "-h", "-?");

            // No longer supported
            commandLine.AddAliases("--charset", "-cs", "--char-set", "--character-set", "--characterset");
            commandLine.AddAliases("--headers-only", "-ho", "--headersonly");
            commandLine.AddAliases("--auto-group", "-ag", "--autogroup");

            commandLineConfig = new ProjectConfig(Source.CommandLine);

            string parameter, parameterAsEntered;
            bool   isFirst = true;

            while (commandLine.IsInBounds)
            {
                // If the first segment isn't a parameter, assume it's the project folder specified without -p.
                if (isFirst && !commandLine.IsOnParameter)
                {
                    parameter          = "--project";
                    parameterAsEntered = parameter;
                }
                else
                {
                    if (!commandLine.GetParameter(out parameter, out parameterAsEntered))
                    {
                        string bareWord;
                        commandLine.GetBareWord(out bareWord);

                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.UnrecognizedParameter(param)", bareWord)
                            );

                        commandLine.SkipToNextParameter();
                    }
                }

                isFirst = false;


                // Input folders

                if (parameter == "--input")
                {
                    Path folder;

                    if (!commandLine.GetPathValue(out folder))
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.ExpectedFolder(param)", parameterAsEntered)
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else
                    {
                        if (folder.IsRelative)
                        {
                            folder = System.Environment.CurrentDirectory + "/" + folder;
                        }

                        var target = new Engine.Config.Targets.SourceFolder(Source.CommandLine, Engine.Files.InputType.Source);

                        target.Folder = folder;
                        target.FolderPropertyLocation = Source.CommandLine;

                        commandLineConfig.InputTargets.Add(target);
                    }
                }



                // Output folders

                else if (parameter == "--output")
                {
                    string format;
                    Path   folder;

                    if (!commandLine.GetBareWordAndPathValue(out format, out folder))
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.ExpectedFormatAndFolder(param)", parameter)
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else
                    {
                        if (folder.IsRelative)
                        {
                            folder = System.Environment.CurrentDirectory + "/" + folder;
                        }

                        format = format.ToLower();

                        if (format == "html" || format == "framedhtml")
                        {
                            var target = new Engine.Config.Targets.HTMLOutputFolder(Source.CommandLine);

                            target.Folder = folder;
                            target.FolderPropertyLocation = Source.CommandLine;

                            commandLineConfig.OutputTargets.Add(target);
                        }
                        else
                        {
                            errorList.Add(
                                Locale.Get("NaturalDocs.CLI", "CommandLine.UnrecognizedOutputFormat(format)", format)
                                );

                            commandLine.SkipToNextParameter();
                        }
                    }
                }



                // Project configuration folder

                else if (parameter == "--project")
                {
                    Path folder;

                    if (!commandLine.GetPathValue(out folder))
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.ExpectedFolder(param)", parameterAsEntered)
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else
                    {
                        if (folder.IsRelative)
                        {
                            folder = System.Environment.CurrentDirectory + "/" + folder;
                        }

                        // Accept the parameter being set to Project.txt instead of the folder.
                        if (folder.NameWithoutPath.ToLower() == "project.txt")
                        {
                            folder = folder.ParentFolder;
                        }

                        if (commandLineConfig.ProjectConfigFolderPropertyLocation.IsDefined)
                        {
                            errorList.Add(
                                Locale.Get("NaturalDocs.CLI", "CommandLine.OnlyOneProjectConfigFolder")
                                );
                        }
                        else
                        {
                            commandLineConfig.ProjectConfigFolder = folder;
                            commandLineConfig.ProjectConfigFolderPropertyLocation = Source.CommandLine;
                        }
                    }
                }



                // Working data folder

                else if (parameter == "--working-data")
                {
                    Path folder;

                    if (!commandLine.GetPathValue(out folder))
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.ExpectedFolder(param)", parameterAsEntered)
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else
                    {
                        if (folder.IsRelative)
                        {
                            folder = System.Environment.CurrentDirectory + "/" + folder;
                        }

                        if (commandLineConfig.WorkingDataFolderPropertyLocation.IsDefined)
                        {
                            errorList.Add(
                                Locale.Get("NaturalDocs.CLI", "CommandLine.OnlyOneWorkingDataFolder")
                                );
                        }
                        else
                        {
                            commandLineConfig.WorkingDataFolder = folder;
                            commandLineConfig.WorkingDataFolderPropertyLocation = Source.CommandLine;
                        }
                    }
                }



                // Ignored input folders

                else if (parameter == "--exclude-input")
                {
                    Path folder;

                    if (!commandLine.GetPathValue(out folder))
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.ExpectedFolder(param)", parameterAsEntered)
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else
                    {
                        if (folder.IsRelative)
                        {
                            folder = System.Environment.CurrentDirectory + "/" + folder;
                        }

                        var target = new Engine.Config.Targets.IgnoredSourceFolder(Source.CommandLine);

                        target.Folder = folder;
                        target.FolderPropertyLocation = Source.CommandLine;

                        commandLineConfig.FilterTargets.Add(target);
                    }
                }



                // Ignored input folder patterns

                else if (parameter == "--exclude-input-pattern")
                {
                    string pattern;

                    if (!commandLine.GetBareOrQuotedWordsValue(out pattern))
                    {
                        errorList.Add(
                            Engine.Locale.Get("NaturalDocs.CLI", "CommandLine.ExpectedPattern(param)", parameterAsEntered)
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else
                    {
                        var target = new Engine.Config.Targets.IgnoredSourceFolderPattern(Source.CommandLine);

                        target.Pattern = pattern;
                        target.PatternPropertyLocation = Source.CommandLine;

                        commandLineConfig.FilterTargets.Add(target);
                    }
                }



                // Image folders

                else if (parameter == "--images")
                {
                    Path folder;

                    if (!commandLine.GetPathValue(out folder))
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.ExpectedFolder(param)", parameterAsEntered)
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else
                    {
                        if (folder.IsRelative)
                        {
                            folder = System.Environment.CurrentDirectory + "/" + folder;
                        }

                        var target = new Engine.Config.Targets.SourceFolder(Source.CommandLine, Engine.Files.InputType.Image);

                        target.Folder = folder;
                        target.FolderPropertyLocation = Source.CommandLine;

                        commandLineConfig.InputTargets.Add(target);
                    }
                }



                // Tab Width

                else if (parameter == "--tab-width")
                {
                    int tabWidth;

                    if (!commandLine.GetIntegerValue(out tabWidth))
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.ExpectedNumber(param)", parameterAsEntered)
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else if (tabWidth < 1)
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.InvalidTabWidth")
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else
                    {
                        commandLineConfig.TabWidth = tabWidth;
                        commandLineConfig.TabWidthPropertyLocation = Source.CommandLine;
                    }
                }

                // Support the -t4 form ini addition to -t 4.  Doesn't support --tablength4.
                else if (parameter.StartsWith("-t") && parameter.Length > 2 && parameter[2] >= '0' && parameter[2] <= '9')
                {
                    string tabWidthString = parameter.Substring(2);

                    int tabWidth;

                    if (!Int32.TryParse(tabWidthString, out tabWidth))
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.ExpectedNumber(param)", "-t")
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else if (tabWidth < 1)
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.InvalidTabWidth")
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else if (!commandLine.NoValue())
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.ExpectedNoValue(param)", parameterAsEntered)
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else
                    {
                        commandLineConfig.TabWidth = tabWidth;
                        commandLineConfig.TabWidthPropertyLocation = Source.CommandLine;
                    }
                }



                // Documented Only

                else if (parameter == "--documented-only")
                {
                    if (!commandLine.NoValue())
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.ExpectedNoValue(param)", parameterAsEntered)
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else
                    {
                        commandLineConfig.DocumentedOnly = true;
                        commandLineConfig.DocumentedOnlyPropertyLocation = Source.CommandLine;
                    }
                }



                // No Auto-Group

                else if (parameter == "--no-auto-group")
                {
                    if (!commandLine.NoValue())
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.ExpectedNoValue(param)", parameterAsEntered)
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else
                    {
                        commandLineConfig.AutoGroup = false;
                        commandLineConfig.AutoGroupPropertyLocation = Source.CommandLine;
                    }
                }



                // Don't Shrink Files

                else if (parameter == "--dont-shrink-files")
                {
                    if (!commandLine.NoValue())
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.ExpectedNoValue(param)", parameterAsEntered)
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else
                    {
                        commandLineConfig.ShrinkFiles = false;
                        commandLineConfig.ShrinkFilesPropertyLocation = Source.CommandLine;
                    }
                }



                // Style

                else if (parameter == "--style")
                {
                    string styleName;

                    if (!commandLine.GetBareOrQuotedWordsValue(out styleName))
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.ExpectedStyleName(param)", parameterAsEntered)
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else
                    {
                        commandLineConfig.ProjectInfo.StyleName = styleName;
                        commandLineConfig.ProjectInfo.StyleNamePropertyLocation = Source.CommandLine;
                    }
                }



                // Rebuild

                else if (parameter == "--rebuild")
                {
                    if (!commandLine.NoValue())
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.ExpectedNoValue(param)", parameterAsEntered)
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else
                    {
                        EngineInstance.Config.ReparseEverything = true;
                        EngineInstance.Config.RebuildAllOutput  = true;
                    }
                }

                else if (parameter == "--rebuild-output")
                {
                    if (!commandLine.NoValue())
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.ExpectedNoValue(param)", parameterAsEntered)
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else
                    {
                        EngineInstance.Config.RebuildAllOutput = true;
                    }
                }



                // Quiet

                else if (parameter == "--quiet")
                {
                    if (!commandLine.NoValue())
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.ExpectedNoValue(param)", parameterAsEntered)
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else
                    {
                        quiet = true;
                    }
                }



                // Worker Threads

                else if (parameter == "--worker-threads")
                {
                    int value;

                    if (!commandLine.GetIntegerValue(out value))
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.ExpectedNumber(param)", parameterAsEntered)
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else if (value < 1)
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.InvalidWorkerThreadCount")
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else
                    {
                        workerThreadCount = value;
                    }
                }



                // Benchmark

                else if (parameter == "--benchmark")
                {
                    if (!commandLine.NoValue())
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.ExpectedNoValue(param)", parameterAsEntered)
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else
                    {
                        benchmark = true;
                    }
                }



                // Pause Before Exit

                else if (parameter == "--pause-before-exit")
                {
                    if (!commandLine.NoValue())
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.ExpectedNoValue(param)", parameterAsEntered)
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else
                    {
                        pauseBeforeExit = true;
                    }
                }



                // Pause on Error

                else if (parameter == "--pause-on-error")
                {
                    if (!commandLine.NoValue())
                    {
                        errorList.Add(
                            Locale.Get("NaturalDocs.CLI", "CommandLine.ExpectedNoValue(param)", parameterAsEntered)
                            );

                        commandLine.SkipToNextParameter();
                    }
                    else
                    {
                        pauseOnError = true;
                    }
                }



                // Help

                else if (parameter == "--help")
                {
                    return(ParseCommandLineResult.ShowCommandLineReference);
                }



                // Version

                else if (parameter == "--version")
                {
                    return(ParseCommandLineResult.ShowVersion);
                }



                // No longer supported parameters

                else if (parameter == "--charset" ||
                         parameter == "--headers-only" ||
                         parameter == "--auto-group")
                {
                    errorList.Add(
                        Locale.Get("NaturalDocs.CLI", "CommandLine.NoLongerSupported(param)", parameterAsEntered)
                        );

                    commandLine.SkipToNextParameter();
                }



                // Everything else

                else
                {
                    errorList.Add(
                        Locale.Get("NaturalDocs.CLI", "CommandLine.UnrecognizedParameter(param)", parameterAsEntered)
                        );

                    commandLine.SkipToNextParameter();
                }
            }


            // Validation

            if (!commandLineConfig.ProjectConfigFolderPropertyLocation.IsDefined)
            {
                errorList.Add(
                    Locale.Get("NaturalDocs.CLI", "CommandLine.NoProjectConfigFolder")
                    );
            }


            // Done.

            if (errorList.Count == originalErrorCount)
            {
                return(ParseCommandLineResult.Run);
            }
            else
            {
                return(ParseCommandLineResult.Error);
            }
        }
        /// <summary>
        /// Parse the commandline arguments.
        /// </summary>
        /// <param name="args">Commandline arguments.</param>
        private void ParseCommandLine(string[] args)
        {
            for (int i = 0; i < args.Length; ++i)
            {
                string arg = args[i];
                if (null == arg || 0 == arg.Length)
                {
                    // skip blank arguments
                    continue;
                }

                if (1 == arg.Length)
                {
                    // treat '-' and '@' as filenames when by themselves.
                    this.inputFiles.AddRange(CommandLine.GetFiles(arg, "Source"));
                    continue;
                }

                if ('-' == arg[0] || '/' == arg[0])
                {
                    string parameter = arg.Substring(1);
                    if ("ext" == parameter)
                    {
                        if (!CommandLine.IsValidArg(args, ++i))
                        {
                            Messaging.Instance.OnMessage(WixErrors.TypeSpecificationForExtensionRequired("-ext"));
                            return;
                        }

                        this.extensionList.Add(args[i]);
                    }
                    else if ("nologo" == parameter)
                    {
                        this.showLogo = false;
                    }
                    else if ("o" == parameter || "out" == parameter)
                    {
                        string path = CommandLine.GetFileOrDirectory(parameter, args, ++i);

                        if (String.IsNullOrEmpty(path))
                        {
                            return;
                        }
                        else
                        {
                            this.outputFile = path;
                        }
                    }
                    else if ("v" == parameter)
                    {
                        Messaging.Instance.ShowVerboseMessages = true;
                    }
                    else if ("?" == parameter || "help" == parameter)
                    {
                        this.showHelp = true;
                        return;
                    }
                    else
                    {
                        this.invalidArgs.Add(parameter);
                    }
                }
                else if ('@' == arg[0])
                {
                    this.ParseCommandLine(CommandLineResponseFile.Parse(arg.Substring(1)));
                }
                else
                {
                    this.inputFiles.AddRange(CommandLine.GetFiles(arg, "Source"));
                }
            }

            return;
        }
Example #57
0
 /// <exception cref="Org.Apache.Commons.Cli.ParseException"/>
 private void ProcessOptions(CommandLine line, Options opts)
 {
     if (line.HasOption("help") || line.HasOption('?'))
     {
         HelpFormatter formatter = new HelpFormatter();
         System.Console.Out.WriteLine("Protobuf IPC benchmark.");
         System.Console.Out.WriteLine();
         formatter.PrintHelp(100, "java ... PBRPCBenchmark [options]", "\nSupported options:"
                             , opts, string.Empty);
         return;
     }
     if (line.HasOption('s'))
     {
         serverThreads = System.Convert.ToInt32(line.GetOptionValue('s'));
     }
     if (line.HasOption('r'))
     {
         serverReaderThreads = System.Convert.ToInt32(line.GetOptionValue('r'));
     }
     if (line.HasOption('c'))
     {
         clientThreads = System.Convert.ToInt32(line.GetOptionValue('c'));
     }
     if (line.HasOption('t'))
     {
         secondsToRun = System.Convert.ToInt32(line.GetOptionValue('t'));
     }
     if (line.HasOption('m'))
     {
         msgSize = System.Convert.ToInt32(line.GetOptionValue('m'));
     }
     if (line.HasOption('p'))
     {
         port = System.Convert.ToInt32(line.GetOptionValue('p'));
     }
     if (line.HasOption('h'))
     {
         host = line.GetOptionValue('h');
     }
     if (line.HasOption('e'))
     {
         string eng = line.GetOptionValue('e');
         if ("protobuf".Equals(eng))
         {
             rpcEngine = typeof(ProtobufRpcEngine);
         }
         else
         {
             if ("writable".Equals(eng))
             {
                 rpcEngine = typeof(WritableRpcEngine);
             }
             else
             {
                 throw new ParseException("invalid engine: " + eng);
             }
         }
     }
     string[] remainingArgs = line.GetArgs();
     if (remainingArgs.Length != 0)
     {
         throw new ParseException("Extra arguments: " + Joiner.On(" ").Join(remainingArgs)
                                  );
     }
 }
Example #58
0
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.DarkYellow;
            Console.WriteLine("spkl Task Runner v" + Assembly.GetEntryAssembly().GetName().Version + "\tTasks v" + Assembly.GetAssembly(typeof(SparkleXrm.Tasks.BaseTask)).GetName().Version);

            Console.ForegroundColor = ConsoleColor.Gray;
            bool            error     = false;
            CommandLineArgs arguments = null;

            try
            {
                arguments = CommandLine.Parse <CommandLineArgs>();

                Run(arguments);
            }
            catch (CommandLineException exception)
            {
                Console.WriteLine(exception.ArgumentHelp.Message);
                Console.WriteLine(exception.ArgumentHelp.GetHelpText(Console.BufferWidth));
            }
            catch (SparkleTaskException ex)
            {
                Console.WriteLine(ex.Message);
                error = true;
            }
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp);
                Console.WriteLine("Code: {0}", ex.Detail.ErrorCode);
                Console.WriteLine("Message: {0}", ex.Detail.Message);
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.WriteLine(ex.StackTrace);

                if (!string.IsNullOrEmpty(ex.Detail.TraceText))
                {
                    Console.WriteLine("Plugin Trace: {0}", ex.Detail.TraceText);
                }
                if (ex.Detail.InnerFault != null)
                {
                    Console.WriteLine("Inner Fault: {0}",
                                      null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
                }
                error = true;
                Console.ForegroundColor = ConsoleColor.White;
            }
            catch (System.TimeoutException ex)
            {
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Message: {0}", ex.Message);
                Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
                if (ex.InnerException != null)
                {
                    Console.WriteLine("Inner Fault: {0}",
                                      null == ex.InnerException.Message ? "No Inner Fault" : ex.InnerException.Message);
                }
                error = true;
                Console.ForegroundColor = ConsoleColor.White;
            }
            catch (System.Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine(ex.Message);
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.WriteLine(ex.StackTrace);

                // Display the details of the inner exception.
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message);

                    FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> fe = ex.InnerException
                                                                                     as FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault>;
                    if (fe != null)
                    {
                        Console.WriteLine("Timestamp: {0}", fe.Detail.Timestamp);
                        Console.WriteLine("Code: {0}", fe.Detail.ErrorCode);
                        Console.WriteLine("Message: {0}", fe.Detail.Message);
                        if (!string.IsNullOrEmpty(fe.Detail.TraceText))
                        {
                            Console.WriteLine("Plugin Trace: {0}", fe.Detail.TraceText);
                        }
                        if (fe.Detail.InnerFault != null)
                        {
                            Console.WriteLine("Inner Fault: {0}",
                                              null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
                        }
                    }
                }
                error = true;
                Console.ForegroundColor = ConsoleColor.White;
            }
            finally
            {
                if (error)
                {
                    Environment.ExitCode = 1;
                }
            }
            if (arguments != null && arguments.WaitForKey == true)
            {
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("Press any key...");
                Console.ReadKey();
            }
            Console.ForegroundColor = ConsoleColor.Gray;
        }
Example #59
0
 /// <inheritdoc/>
 public override async Task RunAsync(CommandLine commandLine)
 {
     Help();
     await Task.CompletedTask;
 }
Example #60
0
 private static int Help(string action = null)
 {
     return(CommandLine.Describe <Program>(action));
 }