예제 #1
0
        static void Main(string[] args)
        {
            var arguments = ArgsParser.Parse(args);
            var c         = new AsyncCompressor(arguments.BlockSize);

            c.Start(arguments.InputPath, arguments.IsCompression);
        }
예제 #2
0
        public void OptionArgumentCaseInsensitive()
        {
            string[] args = new string[] { "https", "server", "-ClientCertificate" };
            ArgsParser argsParser = new ArgsParser(args);

            Assert.AreEqual(true, argsParser.HasOption("clientcertificate"));
        }
예제 #3
0
        public async Task TestUserParser()
        {
            const string username = "******";
            var          origUser = new User(
                id: "1234567890", name: username, twitchDisplayName: username.ToUpper(), simpleName: username,
                color: null,
                firstActiveAt: Instant.FromUnixTimeSeconds(0), lastActiveAt: Instant.FromUnixTimeSeconds(0),
                lastMessageAt: null, pokeyen: 0, tokens: 0);
            var userRepoMock = new Mock <IUserRepo>();

            userRepoMock
            .Setup(r => r.FindBySimpleName(username))
            .ReturnsAsync(origUser);
            var argsParser = new ArgsParser();

            argsParser.AddArgumentParser(new UserParser(userRepoMock.Object));

            var resultUser = await argsParser.Parse <User>(args : ImmutableList.Create(username));

            Assert.AreEqual(origUser, resultUser);
            var resultUserPrefixed = await argsParser.Parse <User>(args : ImmutableList.Create('@' + username));

            Assert.AreEqual(origUser, resultUserPrefixed);

            var ex = Assert.ThrowsAsync <ArgsParseFailure>(() => argsParser
                                                           .Parse <User>(args: ImmutableList.Create("some_unknown_name")));

            Assert.AreEqual("did not recognize a user with the name 'some_unknown_name'", ex.Message);
            var exUserPrefixed = Assert.ThrowsAsync <ArgsParseFailure>(() => argsParser
                                                                       .Parse <User>(args: ImmutableList.Create("@some_unknown_name")));

            Assert.AreEqual("did not recognize a user with the name 'some_unknown_name'", exUserPrefixed.Message);
        }
예제 #4
0
 static void Main(string[] args)
 {
     try {
         bool   showHelp   = false;
         string targetXml  = null;
         var    argsParser = new ArgsParser(Path.GetFileName(Environment.GetCommandLineArgs()[0]), "");
         argsParser.AddOption(new ArgOption("?", true, v => showHelp        = true, "print this help"));
         argsParser.AddOption(new ArgOption("x|xml=", false, v => targetXml = v, "save xml to specified file"));
         bool showError = !argsParser.Parse(args, true);
         if (showError || showHelp)
         {
             if (showError)
             {
                 Console.Error.WriteLine("The syntax of the command is incorrect.");
             }
             Console.Write(argsParser.GetUsage());
             if (showError)
             {
                 Environment.Exit(1);
             }
         }
         else
         {
             BurningDiagramTool.Run(targetXml);
         }
     } catch (Exception e) {
         Console.Error.Write(e.ToStringEx());
         Environment.Exit(1);
     }
 }
예제 #5
0
        public async Task TestTimeSpanParser()
        {
            var argsParser = new ArgsParser();

            argsParser.AddArgumentParser(new TimeSpanParser());

            var result1 = await argsParser.Parse <TimeSpan>(args : ImmutableList.Create("8w3d20h48m5s"));

            var result2 = await argsParser.Parse <TimeSpan>(args : ImmutableList.Create("90d"));

            var expected = new TimeSpan(
                days: 8 * 7 + 3,
                hours: 20,
                minutes: 48,
                seconds: 5);

            Assert.AreEqual(expected, result1);
            Assert.AreEqual(TimeSpan.FromDays(90), result2);

            var ex1 = Assert.ThrowsAsync <ArgsParseFailure>(() => argsParser
                                                            .Parse <TimeSpan>(args: ImmutableList.Create("5s3d")));
            var ex2 = Assert.ThrowsAsync <ArgsParseFailure>(() => argsParser
                                                            .Parse <TimeSpan>(args: ImmutableList.Create("asdasdasd")));

            Assert.IsTrue(ex1.Message.Contains("did not recognize '5s3d' as a duration"));
            Assert.IsTrue(ex2.Message.Contains("did not recognize 'asdasdasd' as a duration"));
        }
예제 #6
0
        public async Task TestAnyOrderParser()
        {
            var argsParser = new ArgsParser();

            argsParser.AddArgumentParser(new AnyOrderParser(argsParser));
            argsParser.AddArgumentParser(new StringParser());
            argsParser.AddArgumentParser(new IntParser());

            var args1 = ImmutableList.Create("123", "foo");
            var args2 = ImmutableList.Create("foo", "123");

            (int int1, string string1) = await argsParser.Parse <AnyOrder <int, string> >(args1);

            (int int2, string string2) = await argsParser.Parse <AnyOrder <int, string> >(args2);

            Assert.AreEqual(123, int1);
            Assert.AreEqual(123, int2);
            Assert.AreEqual("foo", string1);
            Assert.AreEqual("foo", string2);

            var ex = Assert.ThrowsAsync <ArgsParseFailure>(() => argsParser
                                                           .Parse <AnyOrder <int, string> >(ImmutableList.Create("foo", "bar")));

            Assert.AreEqual(2, ex.Failures.Count);
            Assert.AreEqual("did not recognize 'foo' as a number, or did not recognize 'bar' as a number", ex.Message);
        }
예제 #7
0
        public async Task TestPkmnSpeciesParser()
        {
            const string speciesId   = "79317";
            const string speciesName = "Uniquamon";
            var          argsParser  = new ArgsParser();
            PkmnSpecies  species     = PkmnSpecies.RegisterName(speciesId, speciesName);

            argsParser.AddArgumentParser(new PkmnSpeciesParser(new[] { species }));

            PkmnSpecies resultById = await argsParser.Parse <PkmnSpecies>(args : ImmutableList.Create("#" + speciesId));

            PkmnSpecies resultByPaddedId = await argsParser.Parse <PkmnSpecies>(args : ImmutableList.Create("#0" + speciesId));

            PkmnSpecies resultByName1 = await argsParser.Parse <PkmnSpecies>(args : ImmutableList.Create(speciesName));

            PkmnSpecies resultByName2 = await argsParser.Parse <PkmnSpecies>(args : ImmutableList.Create("uNiQuAmOn"));

            Assert.AreEqual(species, resultById);
            Assert.AreEqual(species, resultByPaddedId);
            Assert.AreEqual(species, resultByName1);
            Assert.AreEqual(species, resultByName2);

            ArgsParseFailure exNotPrefixed = Assert.ThrowsAsync <ArgsParseFailure>(() => argsParser
                                                                                   .Parse <PkmnSpecies>(args: ImmutableList.Create(speciesId)));

            Assert.AreEqual("Please prefix with '#' to supply and pokedex number", exNotPrefixed.Message);
            ArgsParseFailure exUnknown = Assert.ThrowsAsync <ArgsParseFailure>(() => argsParser
                                                                               .Parse <PkmnSpecies>(args: ImmutableList.Create("unknown")));

            Assert.AreEqual(
                "No pokemon with the name 'unknown' was recognized. Please supply a valid name, " +
                "or prefix with '#' to supply and pokedex number instead", exUnknown.Message);
        }
예제 #8
0
        public void ArgsParser_WithArgOptionalArgSet_IsCorrect()
        {
            var opts = ArgsParser <MyOption> .Parse(new[] { "--flag", "--my-int", "0", "--my-nullable-int", "1" });

            Assert.True(opts.MyNullableInt.HasValue);
            Assert.Equal(1, opts.MyNullableInt.Value);
        }
        public void argsParser_should_fail_on_unknown_command()
        {
            var badCommandArgs = new string[] { "tron", "--input-assembly-path", "test", "-o", "test", "--open-api-file", "test" };
            var badCommandArgsParserExitCode = ArgsParser.TryParse(badCommandArgs, out ArgsParser badCommandArgsParser);

            badCommandArgsParserExitCode.Should().Be(ExitCode.CommandUnknown);
        }
예제 #10
0
        /// <summary>
        /// コマンドライン引数をパースして、オプション ディクショナリを組み立てます。
        /// </summary>
        /// <param name="args">コマンドライン引数。</param>
        /// <param name="configOptions">コンフィグから読み込んだオプション。</param>
        /// <returns>パース結果のオプション ディクショナリ。</returns>
        private static IDictionary <string, IList <string> > ParseArgs(string[] args, IDictionary <string, string[]> configOptions)
        {
            // コマンドライン オプションのシンタックス。
            OptionSyntaxDictionary syntaxes = new OptionSyntaxDictionary {
                new OptionSyntax("server", "LDAP サーバーのホスト名または IP アドレス。", 1, 1, new char[] { 's' }, false, true, true),
                new OptionSyntax("tls", "LDAPS にする。コンフィグ ファイルで tls を指定した場合も、「--tls off」で LDAP 接続できます。", 0, 1, new char[] { 't' }, false, false, false, new System.Text.RegularExpressions.Regex("^(on|off)$")),
                new OptionSyntax("dn", "ユーザー名。", 1, 1, new char[] { 'd' }),
                new OptionSyntax("oldpassword", "ユーザー エントリのある DN。", 1, 1, new char[] { 'o' }),
                new OptionSyntax("newpassword", "パスワード。", 1, 1, new char[] { 'n' })
            };

            // パーサー組み立て
            var argsParser = new ArgsParser
            {
                OptionSyntaxDictionary = syntaxes,
                ConfigOptionDictionary = configOptions
            };

            IDictionary <string, IList <string> > options = null;

            try
            {
                // パース処理。
                options = argsParser.Parse(args);
            }
            catch (Exception e)
            {
                // パースに失敗したら、ヘルプと元の Exception の文字列をいれた Exception を投げる
                throw new Exception(syntaxes.GetHelp() + "\n" + e);
            }

            return(options);
        }
예제 #11
0
        public void ArgsParserShort_WithArgOptionalArgSet_IsCorrect()
        {
            var opts = ArgsParser <MyShortOption> .Parse(new[] { "-f", "-m", "0", "-n", "1" });

            Assert.True(opts.MyNullableInt.HasValue);
            Assert.Equal(1, opts.MyNullableInt.Value);
        }
예제 #12
0
        public void SStartingWithHash_SourceTypeIsRaw()
        {
            var args   = new string[] { "-s", "#X.|.X" };
            var parser = new ArgsParser(args);

            Assert.AreEqual(InitialWorld.Raw, parser.SourceType);
        }
예제 #13
0
        public static ArgsParser SetUpArgsParser(IUserRepo userRepo, PokedexData pokedexData)
        {
            var argsParser = new ArgsParser();

            argsParser.AddArgumentParser(new SignedIntParser());
            argsParser.AddArgumentParser(new PositiveIntParser());
            argsParser.AddArgumentParser(new NonNegativeIntParser());
            argsParser.AddArgumentParser(new StringParser());
            argsParser.AddArgumentParser(new InstantParser());
            argsParser.AddArgumentParser(new TimeSpanParser());
            argsParser.AddArgumentParser(new HexColorParser());
            argsParser.AddArgumentParser(new PokeyenParser());
            argsParser.AddArgumentParser(new TokensParser());
            argsParser.AddArgumentParser(new SignedPokeyenParser());
            argsParser.AddArgumentParser(new SignedTokensParser());
            argsParser.AddArgumentParser(new PkmnSpeciesParser(pokedexData.KnownSpecies, PokedexData.NormalizeName));

            argsParser.AddArgumentParser(new AnyOrderParser(argsParser));
            argsParser.AddArgumentParser(new OneOfParser(argsParser));
            argsParser.AddArgumentParser(new OptionalParser(argsParser));
            argsParser.AddArgumentParser(new ManyOfParser(argsParser));

            argsParser.AddArgumentParser(new UserParser(userRepo));
            return(argsParser);
        }
예제 #14
0
        public async Task TestOneOfParser()
        {
            var argsParser = new ArgsParser();

            argsParser.AddArgumentParser(new OneOfParser(argsParser));
            argsParser.AddArgumentParser(new StringParser());
            argsParser.AddArgumentParser(new IntParser());
            argsParser.AddArgumentParser(new InstantParser());

            OneOf <int, string> result1 = await argsParser.Parse <OneOf <int, string> >(ImmutableList.Create("123"));

            OneOf <int, string> result2 = await argsParser.Parse <OneOf <int, string> >(ImmutableList.Create("foo"));

            Assert.IsTrue(result1.Item1.IsPresent);
            Assert.IsFalse(result1.Item2.IsPresent);
            Assert.AreEqual(123, result1.Item1.Value);
            Assert.IsFalse(result2.Item1.IsPresent);
            Assert.IsTrue(result2.Item2.IsPresent);
            Assert.AreEqual("foo", result2.Item2.Value);

            var exUnrecognized = Assert.ThrowsAsync <ArgsParseFailure>(() => argsParser
                                                                       .Parse <OneOf <int, Instant> >(ImmutableList.Create("foo")));

            Assert.AreEqual(2, exUnrecognized.Failures.Count);
            const string errorText = "did not recognize 'foo' as a number, or did not recognize 'foo' as a UTC-instant";

            Assert.AreEqual(errorText, exUnrecognized.Message);
            var exTooManyArgs = Assert.ThrowsAsync <ArgsParseFailure>(() => argsParser
                                                                      .Parse <OneOf <int, int> >(ImmutableList.Create("123", "234")));

            Assert.AreEqual("too many arguments", exTooManyArgs.Message);
        }
예제 #15
0
파일: Program.cs 프로젝트: noneback/QRFT
        public static void Main(string[] args)
        {
            try {
                config.Port    = Utils.GetRandomPort();
                config.LANAddr = Utils.GetLocalIp();

                if (args == null || args.Length == 0)
                {
                    Logger.Error("args missing or Error\n");
                    args = new string[] { "--help" };
                }

                var state = Parser.Default.ParseArguments <SendOptions, ReceiveOptions>(args).MapResult(
                    (SendOptions o) => ArgsParser.SendSolution(o),
                    (ReceiveOptions o) => ArgsParser.ReceiveSolution(o),
                    error => 1
                    );
                if (state != 0)
                {
                    Environment.Exit(1);
                }

                if (args[0].Equals("--help"))
                {
                    Environment.Exit(1);
                }
                CreateHostBuilder(new string[] { "--urls", $"http://*:{config.Port}" }).Build().Run();
            } catch (Exception e) {
                Logger.Error($"internal error occured:{e.Message}");
            }
        }
예제 #16
0
        public void OmittingW_WidthIsOne()
        {
            var args   = new string[] { "-s", "glider" };
            var parser = new ArgsParser(args);

            Assert.AreEqual(1, parser.Width);
        }
예제 #17
0
        public void OmittingF_FixedIsFalse()
        {
            var args   = new string[] { "-s", "glider" };
            var parser = new ArgsParser(args);

            Assert.IsFalse(parser.FixedSize);
        }
예제 #18
0
            public void ReturnsFalseIfTransformFileDoesNotExist()
            {
                var argumentParser = new ArgsParser(new[] { "1", "2", "3" });

                Assert.False(argumentParser.IsValid(str => str != "2"));
                Assert.True(argumentParser.ErrorMessage.Contains(": 2"));
            }
예제 #19
0
        public void GivingW40_SetsWidthAs40()
        {
            var args   = new string[] { "-w", "40", "-h", "20" };
            var parser = new ArgsParser(args);

            Assert.AreEqual(40, parser.Width);
        }
예제 #20
0
        public void SGivenPulsar_SourceTypeIsSample()
        {
            var args   = new string[] { "-s", "pulsar" };
            var parser = new ArgsParser(args);

            Assert.AreEqual(InitialWorld.Sample, parser.SourceType);
        }
예제 #21
0
        public void SubparserInCleaningIssueTest()
        {
            var defaultParser = false;
            var pos           = 0;

            var result = new ArgsParser(new [] { "1" })
                         .Help("h", "help")
                         .Comment("Subparser default argparse test")
                         .Keys("t1", "t2").Tip("first test subparser").Subparser(parser =>
            {
                if (parser
                    .Keys("flag").Flag(out var flag)
                    .Result() != null)
                {
                    return;
                }
                throw new InvalidOperationException();
            })
                         .Subparser(parser =>
            {
                if (parser
                    .Name("pos").Value(out pos)
                    .Result() != null)
                {
                    return;
                }
                defaultParser = true;
            })
                         .Result();

            Assert.IsNull(result);
            Assert.IsTrue(defaultParser);
            Assert.AreEqual(1, pos);
        }
예제 #22
0
        public void GivingF_FixedIsTrue()
        {
            var args   = new string[] { "-s", "glider", "-f" };
            var parser = new ArgsParser(args);

            Assert.IsTrue(parser.FixedSize);
        }
예제 #23
0
        public void OmittingS_SourceTypeIsRandom()
        {
            var args   = new string[] { "-w", "40", "-h", "40" };
            var parser = new ArgsParser(args);

            Assert.AreEqual(InitialWorld.Random, parser.SourceType);
        }
        public void argsParser_should_parse_good_args()
        {
            var args      = new string[] { "generate", "-a", "testAssemblyPath", "-o", "testOutputPath", "-f", "testOpenApiPath" };
            var longArgs  = new string[] { "_generate", "--input-assembly-path", "testAssemblyPath", "--output-path", "testOutputPath", "--open-api-file", "testOpenApiPath" };
            var mixedArgs = new string[] { "generate", "--input-assembly-path", "testAssemblyPath", "-o", "testOutputPath", "--open-api-file", "testOpenApiPath" };

            var shortArgsParserExitCode = ArgsParser.TryParse(args, out ArgsParser shortArgsParser);
            var longArgsParserExitCode  = ArgsParser.TryParse(longArgs, out ArgsParser longArgsParser);
            var mixedArgsParserExitCode = ArgsParser.TryParse(mixedArgs, out ArgsParser mixedArgsParser);

            shortArgsParserExitCode.Should().Be(ExitCode.Success);
            shortArgsParser.Command.Should().Be("generate");
            shortArgsParser.InputAssemblyPath.Should().Be("testAssemblyPath");
            shortArgsParser.OutputPath.Should().Be("testOutputPath");
            shortArgsParser.OpenApiPath.Should().Be("testOpenApiPath");

            longArgsParserExitCode.Should().Be(ExitCode.Success);
            longArgsParser.Command.Should().Be("_generate");
            longArgsParser.InputAssemblyPath.Should().Be("testAssemblyPath");
            longArgsParser.OutputPath.Should().Be("testOutputPath");
            longArgsParser.OpenApiPath.Should().Be("testOpenApiPath");


            mixedArgsParserExitCode.Should().Be(ExitCode.Success);
            mixedArgsParser.Command.Should().Be("generate");
            mixedArgsParser.InputAssemblyPath.Should().Be("testAssemblyPath");
            mixedArgsParser.OutputPath.Should().Be("testOutputPath");
            mixedArgsParser.OpenApiPath.Should().Be("testOpenApiPath");
        }
예제 #25
0
        public void UnquoteArgVal()
        {
            int    count;
            string text;

            string[] args;

            args  = new string[] { "text" };
            count = ArgsParser.UnquoteArgVal(args, out text);
            Assert.AreEqual(count, 0);
            Assert.AreEqual(text, null);

            args  = new string[] { "\"hello", "my", "dear", "friend\"", "---" };
            count = ArgsParser.UnquoteArgVal(args, out text);
            Assert.AreEqual(count, 4);
            Assert.AreEqual(text, "hello my dear friend");

            args  = new string[] { "msg=\"hello", "friend\"" };
            count = ArgsParser.UnquoteArgVal(args, out text, offset: 4);
            Assert.AreEqual(count, 2);
            Assert.AreEqual(text, "hello friend");

            args  = new string[] { "'Dwayne", "\"The", "Rock\"", "Johnson'" };
            count = ArgsParser.UnquoteArgVal(args, out text);
            Assert.AreEqual(count, 4);
            Assert.AreEqual(text, "Dwayne \"The Rock\" Johnson");

            args  = new string[] { "i", "see", "what", "you", "'did", "there'" };
            count = ArgsParser.UnquoteArgVal(args, out text, startIndex: 4);
            Assert.AreEqual(count, 2);
            Assert.AreEqual(text, "did there");
        }
예제 #26
0
        static void Main(string[] args)
        {
            string errorMessage;

            if (ArgsParser.Validate(args, out errorMessage) != true)
            {
                Console.WriteLine(errorMessage);
                Environment.ExitCode = 1; // error
                return;
            }

            try
            {
                // parse the args
                var programArgs = ArgsParser.Parse(args);

                // parse the solution file
                var testProjects = SolutionParser.GetTestProjects(programArgs.SolutionFile, programArgs.TestsProjectExtension);

                // write to nunit project file
                NunitWriter.WriteProjectFile(testProjects, programArgs);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Environment.ExitCode = 1; // error
            }


            Environment.ExitCode = 0; // success
        }
예제 #27
0
        private static void WorkingCycle(string[] args, bool launchingWithArgs, Parser parser)
        {
            bool firstCommand = true;

            while (true)
            {
                if (launchingWithArgs && firstCommand)
                {
                    lastParserResult = parser.ParseArguments(args, quiteableCommands);
                    lastParserResult
                    .WithParsed <Command.ICommand>(Execute)
                    .WithNotParsed(HandleErrorsArgsLaunching);
                }
                else
                {
                    Console.Write("{0}> ", WorkingDir);
                    string readParameters = Console.ReadLine();

                    lastParserResult = parser.ParseArguments(ArgsParser.SplitCommandLine(readParameters ?? string.Empty), notQuiteableCommands);
                    lastParserResult
                    .WithParsed <Command.ICommand>(Execute)
                    .WithNotParsed(HandleErrors);
                }
                firstCommand = false;
            }
        }
예제 #28
0
    public static IEnumerable <Argument> ParseOptionTrailingArguments(
        this ArgsParser parser)
    {
        var args = new List <Argument>();

        ///

        while (!parser.Tokenizer.IsEof())
        {
            if (parser.Tokenizer.MatchOptionToken())
            {
                break;
            }

            ///

            var arg = parser.Tokenizer.MaybeNextArgument();

            if (arg == null)
            {
                break;
            }

            args.Add(arg);
        }

        ///

        return(args);
    }
예제 #29
0
        public void SubparserOutCleaningIssueTest()
        {
            var defaultParser = false;

            var result = new ArgsParser(new string [0])
                         .Help("h", "help")
                         .Comment("Subparser default argparse test")
                         .Keys("t1", "t2").Tip("first test subparser").Subparser(parser =>
            {
                if (parser.Result() != null)
                {
                    return;
                }
                throw new InvalidOperationException();
            })
                         .Subparser(parser =>
            {
                if (parser.Result() != null)
                {
                    return;
                }
                defaultParser = true;
            })
                         .Result();

            Assert.IsNull(result);
            Assert.IsTrue(defaultParser);
        }
예제 #30
0
        public void SGivenPulsar_SourceValIsPulsar()
        {
            var args   = new string[] { "-s", "pulsar" };
            var parser = new ArgsParser(args);

            Assert.AreEqual("pulsar", parser.Source);
        }
예제 #31
0
        public void One_Required_String_Arg_Can_Be_Parsed()
        {
            var parser = new ArgsParser<ArgsWith1RequiredStringArg>();
            var output = parser.Parse(new string[] { "foo" });

            Assert.IsNotNull(output);
            Assert.AreEqual("foo", output.String1);
        }
예제 #32
0
        public void Custom_Names_Can_Be_Parsed()
        {
            var parser = new ArgsParser<ArgsWithCustomNames>();
            var output = parser.Parse(new string[] { "-Foo", "Hello", "-Bar", "World!" });

            Assert.IsNotNull(output);
            Assert.AreEqual("Hello", output.String1);
            Assert.AreEqual("World!", output.String2);
        }
예제 #33
0
        public static int Main(string[] args)
        {
            var parser = new ArgsParser();
            parser.Parse(args);

            if (parser.Help)
            {
                DisplayHelpContent();
                return 0;
            }

            try
            {
                var baseDirectory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
                var assemblyScanner = new AssemblyScanner(baseDirectory);
                var configureThisEndpointType = assemblyScanner.GetEndPointType();

                var cfg = RunnerConfigurator.New(x =>
                {
                    x.ConfigureService<AppDomainBridge>(s =>
                    {
                        s.HowToBuildService(name => new AppDomainBridge(baseDirectory, configureThisEndpointType));
                        s.WhenStarted(h => h.Start());
                        s.WhenStopped(h => h.Stop());
                    });

                    if ((parser.Username != null) && (parser.Password != null))
                        x.RunAs(parser.Username, parser.Password);
                    else
                        x.RunAsNetworkService();

                    if (parser.StartManually)
                        x.DoNotStartAutomatically();

                    var endpointName = configureThisEndpointType.Assembly.GetName().Name;
                    var endpointId = string.Format("{0}_v{1}", endpointName, configureThisEndpointType.Assembly.GetName().Version);

                    x.SetDisplayName(parser.DisplayName ?? endpointId);
                    x.SetServiceName(parser.ServiceName ?? endpointId);
                    x.SetDescription(parser.Description ?? string.Format("Colombo Host Service for endpoint {0}.", endpointId));
                });

                Runner.Host(cfg, args);

                return 0;
            }
            catch (ColomboHostException ex)
            {
                Console.Error.WriteLine(ex.Message);
                return -1;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                return -1;
            }
        }
예제 #34
0
        public Rotater( string[] args )
        {
            this._argsParser = null;
            this._globalConfig = new LogrotateConf();
            this._filePathConfigSection = new Dictionary<string, LogrotateConf>();
            this._status = null;

            this.Init( args );
        }
예제 #35
0
        public void Optional_String_Arg_Must_Not_Be_Provided()
        {
            var parser = new ArgsParser<ArgsWith2RequiredAnd1OptionalStringArgs>();
            var output = parser.Parse(new string[] { "foo", "bar" });

            Assert.IsNotNull(output);
            Assert.AreEqual("foo", output.String1);
            Assert.AreEqual("bar", output.String2);
            Assert.IsNull(output.String3);
        }
예제 #36
0
        public void Basic_Types_Can_Be_Parsed()
        {
            var parser = new ArgsParser<ArgsWithBasicTypes>();
            var output = parser.Parse(new string[] { "-String", "Hello", "-Integer", "42", "-Float", "123.4", "-Double", "456.7", "-Boolean" });

            Assert.IsNotNull(output);
            Assert.AreEqual("Hello", output.String);
            Assert.AreEqual(42, output.Integer);
            Assert.AreEqual(123.4f, output.Float, 1.0f);
            Assert.AreEqual(456.7f, output.Double, 1.0f);
            Assert.IsTrue(output.Boolean);
        }
예제 #37
0
 public void SetUp()
 {
     string[] args = { "pathToSite",  "--key1", "value1", "--key2",  "value2" };
     var parser = new ArgsParser();
     _dictionary = parser.Parse(args);
 }
예제 #38
0
 public void Not_Enough_Args_Is_Exception()
 {
     var parser = new ArgsParser<ArgsWith1RequiredStringArg>();
     parser.Parse(new string[] { });
 }
예제 #39
0
 public void Null_Args_Is_Exception()
 {
     var parser = new ArgsParser<ArgsWith1RequiredStringArg>();
     parser.Parse(null);
 }
예제 #40
0
 public void Too_Many_Args_Is_Exception()
 {
     var parser = new ArgsParser<ArgsWith1RequiredStringArg>();
     parser.Parse(new string[] { "foo", "bar" });
 }
예제 #41
0
 static void TestTriangulationOnSmallGraph(ArgsParser.ArgsParser parser) {
     var polyline = new Polyline(
         new Point(20.8211097717285, 40.9088821411133),
         new Point(21.4894065856934, 46.6845321655273),
         new Point(22.9755554199219, 41.3355484008789),
         new Point(20.8211097717285, 40.9088821411133));
     var polylines = new List<Polyline>();
     polylines.Add(polyline);
     var points = new List<Point>();
     var centroid = new Point(21.7620239257813, 42.9763209025065);
     points.Add(centroid);
     var testCdt = new Cdt(points, polylines, null);
     testCdt.Run();
 }
예제 #42
0
        bool Init( string[] args )
        {
            if ( args.Length == 0 )
            {
                this.PrintVersion();
                this.PrintUsage();
                return false;
                //Environment.Exit(0);
            }

            this._argsParser = new ArgsParser( args );
            if ( this._argsParser.Usage )
            {
                this.PrintUsage();
                return false;
                //Environment.Exit(0);
            }

            this._status = new LogrotateStatus( this._argsParser.AlternateStateFile );

            // now process the config files
            foreach ( string str in this._argsParser.ConfigFilePaths )
            {
                this.ProcessConfigPath( str );
            }
            return true;
        }
예제 #43
0
        static BundlingSettings GetBundlingSettings(ArgsParser.ArgsParser argsParser) {
            if (!argsParser.OptionIsUsed(BundlingOption))
                return null;
            var bs = new BundlingSettings();
            string ink = argsParser.GetValueOfOptionWithAfterString(InkImportanceOption);
            double inkCoeff;
            if (ink != null && double.TryParse(ink, out inkCoeff)) {
                bs.InkImportance = inkCoeff;
                BundlingSettings.DefaultInkImportance = inkCoeff;
            }

            string esString = argsParser.GetValueOfOptionWithAfterString(EdgeSeparationOption);
            if (esString != null) {
                double es;
                if (double.TryParse(esString, out es)) {
                    BundlingSettings.DefaultEdgeSeparation = es;
                    bs.EdgeSeparation = es;
                }
                else {
                    Console.WriteLine("cannot parse {0}", esString);
                    Environment.Exit(1);
                }
            }

            string capacityCoeffString = argsParser.GetValueOfOptionWithAfterString(CapacityCoeffOption);
            if (capacityCoeffString != null) {
                double capacityCoeff;
                if (double.TryParse(capacityCoeffString, out capacityCoeff)) {
                    bs.CapacityOverflowCoefficient = capacityCoeff;
                }
                else {
                    Console.WriteLine("cannot parse {0}", capacityCoeffString);
                    Environment.Exit(1);
                }
            }


            return bs;
        }
예제 #44
0
 static double GetPaddings(ArgsParser.ArgsParser argsParser, out double loosePadding) {
     double tightPadding = 0.5;
     if (argsParser.OptionIsUsed(TightPaddingOption)) {
         string tightPaddingString = argsParser.GetValueOfOptionWithAfterString(TightPaddingOption);
         if (!double.TryParse(tightPaddingString, out tightPadding)) {
             Console.WriteLine("cannot parse {0} {1}", TightPaddingOption, tightPaddingString);
             Environment.Exit(1);
         }
     }
     loosePadding = 2.25;
     if (argsParser.OptionIsUsed(LoosePaddingOption)) {
         string loosePaddingString = argsParser.GetValueOfOptionWithAfterString(LoosePaddingOption);
         if (!double.TryParse(loosePaddingString, out loosePadding)) {
             Console.WriteLine("cannot parse {0} {1}", LoosePaddingOption, loosePaddingString);
             Environment.Exit(1);
         }
     }
     return tightPadding;
 }
예제 #45
0
        static void RouteBundledEdges(GeometryGraph geometryGraph, ArgsParser.ArgsParser argsParser) {
            double loosePadding;
            double tightPadding = GetPaddings(argsParser, out loosePadding);

            var br = new SplineRouter(geometryGraph, tightPadding, loosePadding, Math.PI/6, new BundlingSettings());
            br.Run();
        }
예제 #46
0
        static void ProcessMsaglFile(string fileName, ArgsParser.ArgsParser argsParser) {
            Graph graph = Graph.Read(fileName);
            if (graph == null) {
                Console.WriteLine("cannot read " + fileName);
                return;
            }

            if (graph.GeometryGraph != null && graph.BoundingBox.Width > 0) {
                //graph does not need a layout
                if (argsParser.OptionIsUsed(BundlingOption)) {
                    RouteBundledEdges(graph.GeometryGraph, argsParser);
                    if (!argsParser.OptionIsUsed(QuietOption)) {
                        var gviewer = new GViewer();
                        gviewer.MouseMove += Draw.GviewerMouseMove;
                        Form form = CreateForm(graph, gviewer);
                        form.ShowDialog(); // to block the thread
                    }
                }
            }
        }
예제 #47
0
 static void ProcessMsaglGeomFile(string fileName, ArgsParser.ArgsParser argsParser) {
 }
예제 #48
0
 static void ProcessFile(string fileName, ArgsParser.ArgsParser argsParser, GViewer gViewer, ref int nOfBugs) {
     Console.WriteLine("processing " + fileName);
     try {
         string extension = Path.GetExtension(fileName);
         if (extension == ".msagl")
             ProcessMsaglFile(fileName, argsParser);
         else if (extension == ".dot") {
             ProcessDotFile(gViewer, argsParser, fileName);
         }
         else if (extension == ".geom") {
             ProcessMsaglGeomFile(fileName, argsParser);
         }
     }
     catch (Exception e) {
         nOfBugs++;
         Console.WriteLine("bug " + nOfBugs);
         Console.WriteLine(e.ToString());
     }
 }
예제 #49
0
 static void ProcessListOfFiles(string listOfFilesFile, ArgsParser.ArgsParser argsParser) {
     StreamReader sr;
     try {
         sr = new StreamReader(listOfFilesFile);
     }
     catch (Exception e) {
         Console.WriteLine(e.Message);
         return;
     }
     string fileName;
     string dir = Path.GetDirectoryName(listOfFilesFile);
     var gviewer = new GViewer();
     Form form = FormStuff.CreateForm(gviewer);
     int nOfBugs = 0;
     while ((fileName = sr.ReadLine()) != null) {
         if (String.IsNullOrEmpty(fileName)) continue;
         fileName = Path.Combine(dir, fileName.ToLower());
         ProcessFile(fileName, argsParser, gviewer, ref nOfBugs);
         if (form != null && argsParser.OptionIsUsed(QuietOption) == false)
             form.ShowDialog();
     }
 }
예제 #50
0
        public void Two_Required_String_Args_Can_Be_Parsed()
        {
            var parser = new ArgsParser<ArgsWith2RequiredStringArgs>();
            var output = parser.Parse(new string[] { "foo", "bar" });

            Assert.IsNotNull(output);
            Assert.AreEqual("foo", output.String1);
            Assert.AreEqual("bar", output.String2);
        }
예제 #51
0
        public void Two_Required_String_Args_And_One_Optional_String_Arg_Can_Be_Parsed()
        {
            var parser = new ArgsParser<ArgsWith2RequiredAnd1OptionalStringArgs>();
            var output = parser.Parse(new string[] { "foo", "bar", "-String3", "abc" });

            Assert.IsNotNull(output);
            Assert.AreEqual("foo", output.String1);
            Assert.AreEqual("bar", output.String2);
            Assert.AreEqual("abc", output.String3);
        }
예제 #52
0
 public ArgsParsing()
 {
     _subject = new ArgsParser();
 }
예제 #53
0
        static void ProcessDotFile(GViewer gviewer, ArgsParser.ArgsParser argsParser, string dotFileName) {
            int line;
            int col;
            string msg;
            Graph graph = Parser.Parse(dotFileName, out line, out col, out msg);
            if (graph == null) {
                Console.WriteLine("{0}({1},{2}): error: {3}", dotFileName, line, col, msg);
                Environment.Exit(1);
            }
            if (argsParser.OptionIsUsed(RecoverSugiyamaTestOption)) {
                gviewer.CalculateLayout(graph);
                graph.GeometryGraph.AlgorithmData = null;
                LayeredLayout.RecoverAlgorithmData(graph.GeometryGraph);

                Node node = graph.GeometryGraph.Nodes[1];
                node.BoundaryCurve = node.BoundaryCurve.Transform(new PlaneTransformation(3, 0, 0, 0, 3, 0));

                LayeredLayout.IncrementalLayout(graph.GeometryGraph, node);
                gviewer.NeedToCalculateLayout = false;
                gviewer.Graph = graph;
                gviewer.NeedToCalculateLayout = true;
                return;
            }

            if (argsParser.OptionIsUsed(MdsOption))
                graph.LayoutAlgorithmSettings = new MdsLayoutSettings();
            else if (argsParser.OptionIsUsed(FdOption))
                graph.LayoutAlgorithmSettings = new FastIncrementalLayoutSettings();

            if (argsParser.OptionIsUsed(BundlingOption)) {
                graph.LayoutAlgorithmSettings.EdgeRoutingSettings.EdgeRoutingMode = EdgeRoutingMode.SplineBundling;
                BundlingSettings bs = GetBundlingSettings(argsParser);
                graph.LayoutAlgorithmSettings.EdgeRoutingSettings.BundlingSettings = bs;
                string ink = argsParser.GetValueOfOptionWithAfterString(InkImportanceOption);
                if (ink != null) {
                    double inkCoeff;
                    if (double.TryParse(ink, out inkCoeff)) {
                        bs.InkImportance = inkCoeff;
                        BundlingSettings.DefaultInkImportance = inkCoeff;
                    }
                    else {
                        Console.WriteLine("cannot parse {0}", ink);
                        Environment.Exit(1);
                    }
                }

                string esString = argsParser.GetValueOfOptionWithAfterString(EdgeSeparationOption);
                if (esString != null) {
                    double es;
                    if (double.TryParse(esString, out es)) {
                        BundlingSettings.DefaultEdgeSeparation = es;
                        bs.EdgeSeparation = es;
                    }
                    else {
                        Console.WriteLine("cannot parse {0}", esString);
                        Environment.Exit(1);
                    }
                }
            }


            gviewer.Graph = graph;
        }