Exemplo n.º 1
0
        private IDictionary <string, PropertyInfo> InitializeMap(Assembly assembly)
        {
            Map <string, PropertyInfo> commandToPropertyInfoMap =
                new Map <string, PropertyInfo>( );

            foreach (TypeInfo typeInfo in
                     GetClassesWithAttribute <CommandLineInterface>(assembly))
            {
                foreach (PropertyInfo propertyInfo in
                         GetPropertiesWithAttribute <CommandLineSwitch>(typeInfo))
                {
                    CommandLineSwitch commandLineSwitch =
                        propertyInfo.GetCustomAttribute <CommandLineSwitch>( );

                    string loweredSwitchName = commandLineSwitch.Name.ToLower( );
                    AddCommandToMap(loweredSwitchName, propertyInfo, typeInfo,
                                    "Duplicate commands, defined at '{0}' and '{1}'",
                                    ref commandToPropertyInfoMap);

                    string loweredShortSwitchName = commandLineSwitch.ShortName.ToLower( );
                    AddCommandToMap(loweredShortSwitchName, propertyInfo, typeInfo,
                                    "Duplicate aliases, defined at '{0}' and '{1}'",
                                    ref commandToPropertyInfoMap);
                }
            }

            return(commandToPropertyInfoMap);
        }
Exemplo n.º 2
0
        public static IEnumerable <object[]> GetSwitchAndStringRepresentation()
        {
            var switch1 = new CommandLineSwitch("switch", 's', 0, "Test switch.");
            var switch2 = new CommandLineSwitch("switch", null, 0, "Test switch.");
            var switch3 = new CommandLineSwitch(null, 's', 0, "Test switch.");
            var switch4 = new CommandLineSwitch("switch", 's', 1, "Test switch.");
            var switch5 = new CommandLineSwitch("switch", null, 1, "Test switch.");
            var switch6 = new CommandLineSwitch(null, 's', 1, "Test switch.");
            var switch7 = new CommandLineSwitch("switch", 's', 5, "Test switch.");
            var switch8 = new CommandLineSwitch("switch", null, 5, "Test switch.");
            var switch9 = new CommandLineSwitch(null, 's', 5, "Test switch.");

            yield return(new object[] { switch1, "-s or -switch\n\tTest switch." });

            yield return(new object[] { switch2, "-switch\n\tTest switch." });

            yield return(new object[] { switch3, "-s\n\tTest switch." });

            yield return(new object[] { switch4, "-s or -switch <value>\n\tTest switch." });

            yield return(new object[] { switch5, "-switch <value>\n\tTest switch." });

            yield return(new object[] { switch6, "-s <value>\n\tTest switch." });

            yield return(new object[] { switch7, "-s or -switch <5 values>\n\tTest switch." });

            yield return(new object[] { switch8, "-switch <5 values>\n\tTest switch." });

            yield return(new object[] { switch9, "-s <5 values>\n\tTest switch." });
        }
        public void TestConfigureCommandLineParser()
        {
            IConfiguration    config = UnitTestHelper.GetConfig();
            CommandLineParser clp    = new CommandLineParser();

            capf.ConfigureCommandLineParser(clp, config);

            //The switches must be added correctly
            Assert.AreEqual(clp.AvailableSwitches.Count, 5, "Incorrect number of switches added.");

            string[] switchNames = new string[] {
                "assemblies", "docFiles", "modules", "documentPrivates", "typePrefixes"
            };

            for (int i = 0; i < 5; i++)
            {
                bool        found = false;
                IEnumerator en    = clp.AvailableSwitches.GetEnumerator();
                while (en.MoveNext())
                {
                    CommandLineSwitch cSwitch = en.Current as CommandLineSwitch;
                    if (cSwitch.Switch.Equals(switchNames[i]))
                    {
                        found = true;
                        break;
                    }
                }

                Assert.IsTrue(found, "missing switch: " + switchNames[i]);
            }
        }
Exemplo n.º 4
0
        public static IEnumerable <object[]> GetCorrectCommandLineArguments()
        {
            var emptySwitches = new CommandLineSwitchSet();

            var switch1 = new CommandLineSwitch("switch1", 's', 0, "Test switch.");
            var switch2 = new CommandLineSwitch("switch2", 'p', 1, "Test switch.");

            var switches = new CommandLineSwitchSet(new CommandLineSwitch[] { switch1, switch2 });

            var emptyArguments = new string[] { };
            var arguments1     = new string[] { "-switch1" };
            var arguments2     = new string[] { "-switch2", "param" };
            var arguments3     = new string[] { "-s" };
            var arguments4     = new string[] { "-p", "param" };
            var arguments5     = new string[] { "-switch1", "-p", "param" };
            var arguments6     = new string[] { "-switch2", "param", "-s" };

            yield return(new object[] { emptySwitches, emptyArguments });

            yield return(new object[] { switches, emptyArguments });

            yield return(new object[] { switches, arguments1 });

            yield return(new object[] { switches, arguments2 });

            yield return(new object[] { switches, arguments3 });

            yield return(new object[] { switches, arguments4 });

            yield return(new object[] { switches, arguments5 });

            yield return(new object[] { switches, arguments6 });
        }
Exemplo n.º 5
0
        public void MultipleUnclaimed()
        {
            CommandLineConfiguration config = new CommandLineConfiguration();

            config.Add(new CommandLineSwitch()
            {
                Name            = "file",
                IsMultiple      = true,
                IsDefaultOption = true
            });
            var result = parser.Parse(new string[] { "f1", "f2", "f3" }, config);

            Assert.AreEqual(true, result != null);
            Assert.AreEqual(1, result.Count);
            Assert.AreEqual(true, result.ContainsKey("file"));
            CommandLineSwitch item = result["file"];

            Assert.AreEqual(true, item != null);
            Assert.AreEqual(0, item.Index);
            Assert.AreEqual(null, item.Value);
            Assert.AreEqual(true, item.Values != null);
            Assert.AreEqual(3, item.Values.Count);
            Assert.AreEqual("f1", item.Values[0]);
            Assert.AreEqual("f2", item.Values[1]);
            Assert.AreEqual("f3", item.Values[2]);
        }
Exemplo n.º 6
0
            public void WhenConfigured_isExpected()
            {
                var method            = _driver.GetType().GetMethod("Debug");
                var commandLineSwitch = new CommandLineSwitch(_driver, method);

                commandLineSwitch.ShortName.Should().Be("-d");
            }
Exemplo n.º 7
0
        public void FullPrefixedNameCheck(
            string name, char?shortcut, int parametersCount, string meaning, string result)
        {
            var @switch = new CommandLineSwitch(name, shortcut, parametersCount, meaning);

            Assert.Equal(@switch.FullPrefixedName, result);
        }
Exemplo n.º 8
0
        /// <summary>
        /// <para>This method registers the command line switches used by this CSharpAPIProcessorFactory.</para>
        ///
        /// <para>The default switch keys are:</para>
        /// <list type="bullet">
        /// <item>
        /// <term>assemblies</term>
        /// <description>the set of assemblies to analyze. This switch is mandatory.</description>
        /// </item>
        /// <item>
        /// <term>docFiles</term>
        /// <description>The set of /doc XML files to analyze. /doc XML files are generated by compiler and
        /// contain inline documentation. Optional.</description>
        /// </item>
        /// <item>
        /// <term>modules</term>
        /// <description>
        /// The set of modules to analyze. Using this to screen only interested modules. Optional.
        /// </description>
        /// </item>
        /// <item>
        /// <term>typePrefixes</term>
        /// <description>
        /// The set of prefixes of types to analyze. Using this to screen only interested namespaces or types. Optional.
        /// </description>
        /// </item>
        /// <item>
        /// <term>documentPrivates</term>
        /// <description>Whether to list private types and members. Optional.</description>
        /// </item>
        /// </list>
        ///
        /// </summary>
        /// <param name="commandLineParser">the command line parser to use</param>
        /// <param name="configuration">the configuration node to use</param>
        /// <exception cref="ArgumentNullException">if any argument is null</exception>
        /// <exception cref="XmlProcessorFactoryException">
        /// If anything else goes wrong. Thrown by base class.
        /// </exception>
        public override void ConfigureCommandLineParser(CommandLineParser commandLineParser,
                                                        IConfiguration configuration)
        {
            Helper.ValidateNotNull(commandLineParser, "commandLineParser");
            Helper.ValidateNotNull(configuration, "configuration");

            //Create 'assemblies' switch and set it to mandatory.
            CommandLineSwitch assembliesSwitch = new CommandLineSwitch(
                "assemblies", "[BasePath]/MyAssembly.dll", "The set of assemblies to analyze.");

            assembliesSwitch.Factor = (int)FactorParams.ONE_OR_MORE;

            //Create the switches to support
            CommandLineSwitch[] switches = new CommandLineSwitch[] {
                assembliesSwitch,
                new CommandLineSwitch("docFiles", "BasePath/MyAssembly1.xml;BasePath/MyAssembly2.xml",
                                      "The set of /doc XML files to analyze."),
                new CommandLineSwitch("modules", "MyModule1;MyModule2",
                                      "The set of prefixes of types to analyze."),
                new CommandLineSwitch("documentPrivates",
                                      "This switch if specified means that private members will be documented.",
                                      "Whether to list private types and members."),
                new CommandLineSwitch("typePrefixes", "MyType1;MyType2",
                                      "Use this to screen only interested namespaces or types.")
            };

            base.ConfigureCommandLineParser(switches, commandLineParser, configuration);
        }
Exemplo n.º 9
0
    public NfsServerProgramOptions()
    {
        listenIPAddress         = new CommandLineArgument <IPAddress>(IPAddress.Parse, 'l', "Listen IP Address");
        listenIPAddress.Default = IPAddress.Any;
        Add(listenIPAddress);

        //
        // Debug Server
        //
        debugListenPort = new CommandLineArgument <UInt16>(UInt16.Parse, 'd', "DebugListenPort", "The TCP port that the debug server will be listening to (If no port is specified, the debug server will not be running)");
        Add(debugListenPort);

        //
        // Npc Server
        //
        npcListenPort = new CommandLineArgument <UInt16>(UInt16.Parse, 'n', "NpcListenPort", "The TCP port that the NPC server will be listening to (If no port is specified, the NPC server will not be running)");
        Add(npcListenPort);

        logFile = new CommandLineArgumentString('f', "LogFile", "Log file (logs to stdout if not specified)");
        Add(logFile);


        logLevel = new CommandLineArgumentEnum <LogLevel>('v', "LogLevel", "Level of statements to log");
        logLevel.SetDefault(LogLevel.None);
        Add(logLevel);

        performanceLog = new CommandLineArgumentString('p', "PerformanceLog", "Where to log performance ('internal',<filename>)");
        Add(performanceLog);

#if WindowsCE
        jediTimer = new CommandLineSwitch('j', "JediTimer", "Adds the jedi timer timestamp to printed commands");
        Add(jediTimer);
#endif
    }
Exemplo n.º 10
0
        public void CreateSwicthCollectionWithSwitches(
            CommandLineSwitch firstSwitch, CommandLineSwitch secondSwitch)
        {
            var switchArray = new CommandLineSwitch[] { firstSwitch, secondSwitch };

            var switches = new CommandLineSwitchSet(switchArray);
        }
Exemplo n.º 11
0
        public void Invoke(IConsoleHost consoleHost, string[] args)
        {
            var commandName = args[0];

            try
            {
                var options = CommandLineSwitch.Parse <Options>(ref args);
                if (args.Skip(1).Any() == false || options.Help)
                {
                    Usage(consoleHost, commandName);
                    return;
                }

                var found = _Fonts.Value.TryGetValue(options.Font.ToLower(), out var getFont);
                if (!found)
                {
                    throw new FontNotFoundException(options.Font);
                }

                var bannerText = getFont().Render(string.Join(' ', args.Skip(1)));
                consoleHost.WriteLine(bannerText);
            }

            catch (FontNotFoundException e) { consoleHost.WriteLine(Yellow(e.Message)); }
            catch (InvalidCommandLineSwitchException e)
            {
                consoleHost.WriteLine(Yellow(e.Message));
                Usage(consoleHost, commandName);
            }
        }
Exemplo n.º 12
0
        public static TCommand AddSwitch <TCommand>(this TCommand command, CommandLineSwitch cliSwitch) where TCommand : Command
        {
            var clone = (CommandLineSwitch)cliSwitch.Clone();

            command.Switches.Add(clone);
            return(command);
        }
Exemplo n.º 13
0
            public void GivenEmptyArguments_ReturnsFalse()
            {
                var method            = _driver.GetType().GetMethod("Debug");
                var commandLineSwitch = new CommandLineSwitch(_driver, method);
                var arguments         = new Queue <string>();

                commandLineSwitch.TryActivate(arguments).Should().BeFalse();
            }
Exemplo n.º 14
0
 public void CreateIncorrectSwitch(
     string name, char?shortcut, int parametersCount, string meaning)
 {
     Assert.Throws <ArgumentException>(() =>
     {
         var @switch = new CommandLineSwitch(name, shortcut, parametersCount, meaning);
     });
 }
Exemplo n.º 15
0
        public void AddCorrectSwitchesToEmptyCollection(
            CommandLineSwitch firstSwitch, CommandLineSwitch secondSwitch)
        {
            var switches = new CommandLineSwitchSet();

            switches.AddSwitch(firstSwitch);
            switches.AddSwitch(secondSwitch);
        }
Exemplo n.º 16
0
        public void AddCorrectSwitchesToCollection(CommandLineSwitch[] switches)
        {
            var switchArray = new CommandLineSwitch[] { switches[0], switches[1] };

            var switchesCollection = new CommandLineSwitchSet(switchArray);

            switchesCollection.AddSwitch(switches[2]);
        }
Exemplo n.º 17
0
        public void Parse_LongNameOnly_Test()
        {
            var args    = "http://localhost:32767 --authenticationtype cookie --allowanonymous".Split(' ');
            var options = CommandLineSwitch.Parse <HttpServerOptions>(ref args);

            options.AuthenticationType.Is(AuthenticationType.Cookie);
            options.AllowAnonymous.IsTrue();
        }
Exemplo n.º 18
0
        public void Parse_Enum_Test()
        {
            var args    = "-t svn commit".Split(' ');
            var options = CommandLineSwitch.Parse <VCSCommandOptions>(ref args);

            options.Type.Is(VCSTypes.SVN);
            args.Is("commit");
        }
Exemplo n.º 19
0
        public void AddCorrectSwitchesToCopiedCollection(CommandLineSwitch[] switches)
        {
            var switchArray = new CommandLineSwitch[] { switches[0], switches[1] };

            var sourceSwitches = new CommandLineSwitchSet(switchArray);
            var copySwitches   = new CommandLineSwitchSet(sourceSwitches);

            copySwitches.AddSwitch(switches[2]);
        }
Exemplo n.º 20
0
        public void EmptyArgs_Test()
        {
            var args    = new string[] { };
            var options = CommandLineSwitch.Parse <HttpServerOptions>(ref args);

            options.Recursive.Is(false);
            options.Port.Is <uint>(8080);
            args.Is();
        }
Exemplo n.º 21
0
        public void ComplexArgs_Test()
        {
            var args    = new[] { "--port", "80", @"c:\wwwroot\inetpub", "-r" };
            var options = CommandLineSwitch.Parse <HttpServerOptions>(ref args);

            options.Recursive.Is(true);
            options.Port.Is <uint>(80);
            args.Is(@"c:\wwwroot\inetpub");
        }
Exemplo n.º 22
0
        public void CreateSwitchCollectionWithIncompatibleSwitches(
            CommandLineSwitch firstSwitch, CommandLineSwitch secondSwitch)
        {
            var switchArray = new CommandLineSwitch[] { firstSwitch, secondSwitch };

            Assert.Throws <InvalidOperationException>(() =>
            {
                var switches = new CommandLineSwitchSet(switchArray);
            });
        }
Exemplo n.º 23
0
        protected override ProgramBase.StandardSwitches DefineCommandLine(CommandLineParser parser)
        {
            _vhdFile   = new CommandLineParameter("vhd_file", "Path to the VHD file to inspect.", false);
            _dontCheck = new CommandLineSwitch("nc", "noCheck", null, "Don't check the VHD file format for corruption");

            parser.AddParameter(_vhdFile);
            parser.AddSwitch(_dontCheck);

            return(StandardSwitches.Default);
        }
Exemplo n.º 24
0
        public void Parse_LongNameOnly_Ambiguous_Test()
        {
            var args = "http://localhost:32767 -a".Split(' ');
            var e    = Assert.Throws <InvalidCommandLineSwitchException>(() =>
            {
                var options = CommandLineSwitch.Parse <HttpServerOptions>(ref args);
            });

            e.ParserError.ErrorType.Is(ErrorTypes.UnknownOption);
        }
Exemplo n.º 25
0
            public void GivenNullArguments_ThrowsException()
            {
                var method            = _driver.GetType().GetMethod("Debug");
                var commandLineSwitch = new CommandLineSwitch(_driver, method);
                var exception         =
                    Assert.Throws <ArgumentNullException>(
                        () => commandLineSwitch.TryActivate(null));

                exception.ParamName.Should().Be("arguments");
            }
Exemplo n.º 26
0
            public void WhenConfigured_CallsMethod()
            {
                var method            = _driver.GetType().GetMethod("Debug");
                var commandLineSwitch = new CommandLineSwitch(_driver, method);
                var arguments         = new Queue <string>();

                arguments.Enqueue("-d");
                commandLineSwitch.TryActivate(arguments);
                _driver.ShowDiagnostics.Should().BeTrue();
            }
Exemplo n.º 27
0
        public static async Task <int> Main(string[] args)
        {
            var commandLineOptions  = CommandLineSwitch.Parse <CommandLineOptions>(ref args, options => options.EnumParserStyle = EnumParserStyle.OriginalCase);
            var assemblyLoader      = new CustomAssemblyLoader();
            var prerenderingOptions = BuildPrerenderingOptions(assemblyLoader, commandLineOptions);

            var crawlingResult = await PreRenderToStaticFilesAsync(commandLineOptions, assemblyLoader, prerenderingOptions);

            return(crawlingResult.HasFlag(StaticlizeCrawlingResult.HasErrors) ? 1 : 0);
        }
        public void IntSwitch_ToString_Test()
        {
            // Arrange
            var cliSwitch = new CommandLineSwitch <int>("/test", 52);

            // Act
            var output = cliSwitch.ToString();

            // Assert
            Assert.AreEqual("/test 52", output);
        }
        public void StringWithSpacesAsArgument_Test()
        {
            // Arrange
            var cliSwitch = new CommandLineSwitch <string>("/password", "horse test debug");

            // Act
            var output = cliSwitch.ToString();

            // Assert
            Assert.AreEqual("/password \"horse test debug\"", output);
        }
        public void EnumSwitch_ToString_Test()
        {
            // Arrange
            var cliSwitch = new CommandLineSwitch <TestValue>("/test", TestValue.Blue);

            // Act
            var output = cliSwitch.ToString();

            // Assert
            Assert.AreEqual("/test Blue", output);
        }