public void ShouldGiveCorrectOptionAndValue()
        {
            var options = new string[] { "option", "value" };
            var parser  = new CommandLineOptionsParser(options);

            Assert.AreEqual("value", parser.GetValue("option"), "Wrong value for option");
        }
コード例 #2
0
            public override void Done()
            {
                var args = GetAndResetAdditionalArguments();

                if (args.Count != 0)
                {
                    Next = CommandLineOptionsParser.Parse <Options>(args);
                }
            }
        public void ShouldReturnCorrectValuesForOptionsWithPrefixes()
        {
            var options         = new string[] { "-option1", "value1", "/option2", "value2" };
            var allowedPrefixes = new string[] { "-", "/" };
            var parser          = new CommandLineOptionsParser(options, new string[] {}, allowedPrefixes);

            Assert.AreEqual("value1", parser.GetValue("option1"));
            Assert.AreEqual("value2", parser.GetValue("option2"));
        }
コード例 #4
0
ファイル: BasicUseCase.cs プロジェクト: ywscr/OptionParsing
        public void SimpleExample()
        {
            // Note: In real-world code, don't parse the command line yourself; just call CommandLineOptionsParser.Parse without any arguments.
            var commandLine = Win32CommandLineLexer.Instance.Lex("test.mp4 -l smith --flag");
            var options     = CommandLineOptionsParser.Parse <Options>(commandLine);

            Assert.Equal("test.mp4", options.Filename);
            Assert.True(options.Flag);
            Assert.Equal("smith", options.Label);
        }
 public void ShouldThrowWithUnevenNumberOfItemsOnCommandLine()
 {
     Assert.Throws(typeof(IndexOutOfRangeException),
                   () =>
     {
         var items  = new string[] { "Test" };
         var parser = new CommandLineOptionsParser(items);
     },
                   "Accepted uneven number of items"
                   );
 }
        public void ShouldUnderstandOptionPrefixes()
        {
            var options         = new string[] { "-option1", "value1", "/option2", "value2" };
            var allowedPrefixes = new string[] { "-", "/" };

            Assert.DoesNotThrow(
                () =>
            {
                var parser = new CommandLineOptionsParser(options, new string[] {}, allowedPrefixes);
            },
                "Threw on valid prefix"
                );
        }
        public void ShouldThrowOnInvalidOptionOnCmdLine()
        {
            var options        = new string[] { "-option", "value" };
            var allowedOptions = new string[] { "option" };

            Assert.Throws(typeof(IndexOutOfRangeException),
                          () =>
            {
                var parser = new CommandLineOptionsParser(options, allowedOptions);
            },
                          "Did not throw on invalid option"
                          );
        }
        public void ShouldThrowOnUnParsedOption()
        {
            var options = new string[] { "option", "value" };

            Assert.Throws(typeof(IndexOutOfRangeException),
                          () =>
            {
                var parser = new CommandLineOptionsParser(options);
                parser.GetValue("option1");
            },
                          "Did not throw on unparsed option"
                          );
        }
コード例 #9
0
 public override void Done()
 {
     if (Command == Commands.Measure)
     {
         Measure = CommandLineOptionsParser.Parse <MeasureOptions>(GetAndResetAdditionalArguments());
     }
     else if (Command == Commands.Cut)
     {
         Cut = CommandLineOptionsParser.Parse <CutOptions>(GetAndResetAdditionalArguments());
     }
     else if (Command == Commands.Help)
     {
         Help = CommandLineOptionsParser.Parse <HelpOptions>(GetAndResetAdditionalArguments());
     }
 }
コード例 #10
0
        protected override void Configure()
        {
            this.options = this.Container.Get <CommandLineOptionsParser>();
            if (!this.options.Parse(this.Args))
            {
                Environment.Exit(0);
            }

            var pathTransformer = this.Container.Get <IPathTransformer>();

            // Have to set the log path before anything else
            var pathConfiguration = AppSettings.Instance.PathConfiguration;

            GlobalDiagnosticsContext.Set("LogFilePath", pathTransformer.MakeAbsolute(pathConfiguration.LogFilePath));

            AppDomain.CurrentDomain.UnhandledException += (o, e) => OnAppDomainUnhandledException(e);

            var logger   = LogManager.GetCurrentClassLogger();
            var assembly = this.Container.Get <IAssemblyProvider>();

            logger.Info("SyncTrazor version {0} ({1}) started at {2} (.NET version: {3})", assembly.FullVersion, assembly.ProcessorArchitecture, assembly.Location, DotNetVersionFinder.FindDotNetVersion());

            // This needs to happen before anything which might cause the unhandled exception stuff to be shown, as that wants to know
            // where to find the log file.
            this.Container.Get <IApplicationPathsProvider>().Initialize(pathConfiguration);

            var client = this.Container.Get <IIpcCommsClientFactory>().TryCreateClient();

            if (client != null)
            {
                try
                {
                    if (this.options.StartSyncthing || this.options.StopSyncthing)
                    {
                        if (this.options.StartSyncthing)
                        {
                            client.StartSyncthing();
                        }
                        else if (this.options.StopSyncthing)
                        {
                            client.StopSyncthing();
                        }
                        if (!this.options.StartMinimized)
                        {
                            client.ShowMainWindow();
                        }
                        Environment.Exit(0);
                    }

                    if (AppSettings.Instance.EnforceSingleProcessPerUser)
                    {
                        if (!this.options.StartMinimized)
                        {
                            client.ShowMainWindow();
                        }
                        Environment.Exit(0);
                    }
                }
                catch (Exception e)
                {
                    logger.Error(e, $"Failed to talk to {client}: {e.Message}. Pretending that it doesn't exist...");
                }
            }

            var configurationProvider = this.Container.Get <IConfigurationProvider>();

            configurationProvider.Initialize(AppSettings.Instance.DefaultUserConfiguration);
            var configuration = this.Container.Get <IConfigurationProvider>().Load();

            if (AppSettings.Instance.EnforceSingleProcessPerUser)
            {
                this.Container.Get <IIpcCommsServer>().StartServer();
            }

            // Has to be done before the VMs are fetched from the container
            var languageArg = this.Args.FirstOrDefault(x => x.StartsWith("-culture="));

            if (languageArg != null)
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(languageArg.Substring("-culture=".Length));
            }
            else if (!configuration.UseComputerCulture)
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
            }

            // WPF ignores the current culture by default - so we have to force it
            FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.IetfLanguageTag)));

            var autostartProvider = this.Container.Get <IAutostartProvider>();

#if DEBUG
            autostartProvider.IsEnabled = false;
#endif

            // If it's not in portable mode, and if we had to create config (i.e. it's the first start ever), then enable autostart
            if (autostartProvider.CanWrite && AppSettings.Instance.EnableAutostartOnFirstStart && configurationProvider.HadToCreateConfiguration)
            {
                autostartProvider.SetAutoStart(new AutostartConfiguration()
                {
                    AutoStart = true, StartMinimized = true
                });
            }

            // Needs to be done before ConfigurationApplicator is run
            this.Container.Get <IApplicationWindowState>().Setup(this.RootViewModel);

            this.Container.Get <ConfigurationApplicator>().ApplyConfiguration();

            this.Container.Get <MemoryUsageLogger>().Enabled = true;

            // Handles Restart Manager requests - sent by the installer. We need to shutdown syncthing in this case
            this.Application.SessionEnding += (o, e) =>
            {
                LogManager.GetCurrentClassLogger().Info("Shutting down: {0}", e.ReasonSessionEnding);
                var manager = this.Container.Get <ISyncthingManager>();
                manager.StopAndWaitAsync().Wait(2000);
                manager.Kill();
            };

            MessageBoxViewModel.ButtonLabels = new Dictionary <MessageBoxResult, string>()
            {
                { MessageBoxResult.Cancel, Resources.Generic_Dialog_Cancel },
                { MessageBoxResult.No, Resources.Generic_Dialog_No },
                { MessageBoxResult.OK, Resources.Generic_Dialog_OK },
                { MessageBoxResult.Yes, Resources.Generic_Dialog_Yes },
            };

            MessageBoxViewModel.DefaultFlowDirection = Localizer.FlowDirection;

            RecycleBinDeleter.Logger = s => LogManager.GetLogger(typeof(RecycleBinDeleter).FullName).Error(s);
        }
コード例 #11
0
 public void SetUp()
 {
     this.parser = new CommandLineOptionsParser();
 }
コード例 #12
0
ファイル: OptionParsing.cs プロジェクト: ywscr/OptionParsing
 public static T Parse <T>(params string[] commandLine) where T : class, ICommandLineOptions => CommandLineOptionsParser.Parse <T>(commandLine);
コード例 #13
0
ファイル: Bootstrapper.cs プロジェクト: Lillecarl/SyncTrayzor
        protected override void Configure()
        {
            // GitHub uses Tls 1.2 only, and it isn't enabled by default before .NET 4.6. Since we target an earlier
            // .NET version, we have to enable this ourselves.
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            this.options = this.Container.Get <CommandLineOptionsParser>();
            if (!this.options.Parse(this.Args))
            {
                Environment.Exit(0);
            }

            var pathTransformer = this.Container.Get <IPathTransformer>();

            // Have to set the log path before anything else
            var pathConfiguration = AppSettings.Instance.PathConfiguration;

            GlobalDiagnosticsContext.Set("LogFilePath", pathTransformer.MakeAbsolute(pathConfiguration.LogFilePath));

            AppDomain.CurrentDomain.UnhandledException += (o, e) => OnAppDomainUnhandledException(e);

            var logger   = LogManager.GetCurrentClassLogger();
            var assembly = this.Container.Get <IAssemblyProvider>();

            logger.Info("SyncTrazor version {0} ({1}) started at {2} (.NET version: {3})", assembly.FullVersion, assembly.ProcessorArchitecture, assembly.Location, DotNetVersionFinder.FindDotNetVersion());

            // This needs to happen before anything which might cause the unhandled exception stuff to be shown, as that wants to know
            // where to find the log file.
            this.Container.Get <IApplicationPathsProvider>().Initialize(pathConfiguration);

            var client = this.Container.Get <IIpcCommsClientFactory>().TryCreateClient();

            if (client != null)
            {
                try
                {
                    if (this.options.Shutdown)
                    {
                        client.Shutdown();
                        // Give it some time to shut down
                        var elapsed = Stopwatch.StartNew();
                        while (elapsed.Elapsed < TimeSpan.FromSeconds(10) &&
                               this.Container.Get <IIpcCommsClientFactory>().TryCreateClient() != null)
                        {
                            Thread.Sleep(100);
                        }
                        // Wait another half-second -- it seems it can take the browser process a little longer to exit
                        Thread.Sleep(500);
                        Environment.Exit(0);
                    }

                    if (this.options.StartSyncthing || this.options.StopSyncthing)
                    {
                        if (this.options.StartSyncthing)
                        {
                            client.StartSyncthing();
                        }
                        else if (this.options.StopSyncthing)
                        {
                            client.StopSyncthing();
                        }
                        if (!this.options.StartMinimized)
                        {
                            client.ShowMainWindow();
                        }
                        Environment.Exit(0);
                    }

                    if (AppSettings.Instance.EnforceSingleProcessPerUser)
                    {
                        if (!this.options.StartMinimized)
                        {
                            client.ShowMainWindow();
                        }
                        Environment.Exit(0);
                    }
                }
                catch (Exception e)
                {
                    logger.Error(e, $"Failed to talk to {client}: {e.Message}. Pretending that it doesn't exist...");
                }
            }

            // If we got this far, there probably isn't another instance running, and we should just shut down
            if (this.options.Shutdown)
            {
                Environment.Exit(0);
            }

            var configurationProvider = this.Container.Get <IConfigurationProvider>();

            configurationProvider.Initialize(AppSettings.Instance.DefaultUserConfiguration);
            var configuration = this.Container.Get <IConfigurationProvider>().Load();

            if (AppSettings.Instance.EnforceSingleProcessPerUser)
            {
                this.Container.Get <IIpcCommsServer>().StartServer();
            }

            // Has to be done before the VMs are fetched from the container
            if (this.options.Culture != null)
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(this.options.Culture);
            }
            else if (!configuration.UseComputerCulture)
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
            }

            // WPF ignores the current culture by default - so we have to force it
            FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.IetfLanguageTag)));

            var autostartProvider = this.Container.Get <IAutostartProvider>();

#if DEBUG
            autostartProvider.IsEnabled = false;
#endif

            // If it's not in portable mode, and if we had to create config (i.e. it's the first start ever), then enable autostart
            if (autostartProvider.CanWrite && AppSettings.Instance.EnableAutostartOnFirstStart && configurationProvider.HadToCreateConfiguration)
            {
                autostartProvider.SetAutoStart(new AutostartConfiguration()
                {
                    AutoStart = true, StartMinimized = true
                });
            }

            // Needs to be done before ConfigurationApplicator is run
            this.Container.Get <IApplicationWindowState>().Setup(this.RootViewModel);

            this.Container.Get <ConfigurationApplicator>().ApplyConfiguration();

            this.Container.Get <MemoryUsageLogger>().Enabled = true;

            // Handles Restart Manager requests - sent by the installer. We need to shutdown syncthing in this case
            this.Application.SessionEnding += (o, e) =>
            {
                LogManager.GetCurrentClassLogger().Info("Shutting down: {0}", e.ReasonSessionEnding);
                var manager = this.Container.Get <ISyncthingManager>();
                manager.StopAndWaitAsync().Wait(2000);
                manager.Kill();
            };

            MessageBoxViewModel.ButtonLabels = new Dictionary <MessageBoxResult, string>()
            {
                { MessageBoxResult.Cancel, Resources.Generic_Dialog_Cancel },
                { MessageBoxResult.No, Resources.Generic_Dialog_No },
                { MessageBoxResult.OK, Resources.Generic_Dialog_OK },
                { MessageBoxResult.Yes, Resources.Generic_Dialog_Yes },
            };

            MessageBoxViewModel.DefaultFlowDirection = Localizer.FlowDirection;

            RecycleBinDeleter.Logger = s => LogManager.GetLogger(typeof(RecycleBinDeleter).FullName).Error(s);

            // Workaround for Intel Xe processors, which mess up CefSharp unless we disable hardware
            // rendering for WPF. See #606.
            if (configuration.DisableHardwareRendering)
            {
                RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
            }
        }