Exemplo n.º 1
0
        public void PositionalArguments(
            string[] args,
            string firstParsedArgument,
            string secondParsedArgument,
            ICommandLineParser parser)
        {
            const string FirstArgument  = "firstArgument";
            const string SecondArgument = "secondArgument";

            "establish positional arguments".x(() =>
                                               args = new[]
            {
                FirstArgument, SecondArgument
            });

            "establish a parser with parsing configuration for positional arguments".x(() =>
            {
                parser = new CommandLineParser(CommandLineParserConfigurator
                                               .Create()
                                               .WithPositional(v => firstParsedArgument  = v)
                                               .WithPositional(v => secondParsedArgument = v)
                                               .BuildConfiguration());
            });

            "when parsing".x(() =>
                             parser.Parse(args));

            "should parse positional argument".x(() =>
                                                 new[]
            {
                firstParsedArgument, secondParsedArgument
            }
                                                 .Should().Equal(FirstArgument, SecondArgument));
        }
Exemplo n.º 2
0
        public void ValueConvertion(
            string[] args,
            int firstParsedArgument,
            bool secondParsedArgument,
            ICommandLineParser parser)
        {
            const int Value = 42;

            "establish non-string arguments".x(() =>
                                               args = new[]
            {
                "-value", Value.ToString(), "true"
            });

            "establish a parser with parsing configuration with type convertion".x(() =>
            {
                parser = new CommandLineParser(CommandLineParserConfigurator
                                               .Create()
                                               .WithNamed("value", (int v) => firstParsedArgument = v)
                                               .WithPositional((bool v) => secondParsedArgument   = v)
                                               .BuildConfiguration());
            });

            "when parsing".x(() =>
                             parser.Parse(args));

            "should convert parsed named arguments".x(() =>
                                                      firstParsedArgument.Should().Be(Value));

            "should convert parsed positional arguments".x(() =>
                                                           secondParsedArgument.Should().BeTrue());
        }
Exemplo n.º 3
0
        public void SupportsRestrictedValues(
            string value,
            string expectedParsedValue,
            bool expectedSuccessful,
            string[] args,
            string parsedValue,
            ICommandLineParser parser,
            ParseResult parseResult)
        {
            "establish arguments".x(() =>
                                    args = new[]
            {
                "-n", value
            });

            "establish a parser with parsing configuration with value check".x(() =>
            {
                parser = new CommandLineParser(CommandLineParserConfigurator
                                               .Create()
                                               .WithNamed("n", v => parsedValue = v)
                                               .RestrictedTo(KnownValue)
                                               .BuildConfiguration());
            });

            "when parsing".x(() =>
                             parseResult = parser.Parse(args));

            "should parse allowed values".x(() =>
                                            parsedValue.Should().Be(expectedParsedValue));

            "should fail for not allowed values".x(() =>
                                                   parseResult.Succeeded.Should().Be(expectedSuccessful));
        }
Exemplo n.º 4
0
        public void SupportsLongAliasForSwitch(
            string[] args,
            bool firstParsedSwitch,
            string secondParsedSwitch,
            ICommandLineParser parser)
        {
            "establish arguments with switch with long alias".x(() =>
                                                                args = new[]
            {
                "-f", "--secondSwitch"
            });

            "establish a parser with parsing configuration for switches with long aliases".x(() =>
            {
                parser = new CommandLineParser(CommandLineParserConfigurator
                                               .Create()
                                               .WithSwitch("f", () => firstParsedSwitch = true)
                                               .HavingLongAlias("firstSwitch")
                                               .WithSwitch("s", () => secondParsedSwitch = "yeah")
                                               .HavingLongAlias("secondSwitch")
                                               .BuildConfiguration());
            });

            "when parsing".x(() =>
                             parser.Parse(args));

            "should parse switch".x(() =>
                                    new object[]
            {
                firstParsedSwitch, secondParsedSwitch
            }
                                    .Should().Equal(true, "yeah"));
        }
Exemplo n.º 5
0
        public void RequiredPositional(
            string[] args,
            string firstParsedArgument,
            string secondParsedArgument,
            ICommandLineParser parser,
            ParseResult result)
        {
            const string FirstName   = "firstName";
            const string FirstValue  = "firstValue";
            const string SecondName  = "secondName";
            const string SecondValue = "secondValue";

            "establish some arguments with missing required positional argument".x(() =>
                                                                                   args = new[]
            {
                "-" + FirstName, FirstValue, "-" + SecondName, SecondValue
            });

            "establish a parser with parsing configuration with required positional arguments".x(() =>
            {
                parser = new CommandLineParser(CommandLineParserConfigurator
                                               .Create()
                                               .WithPositional(v => { })
                                               .Required()
                                               .WithNamed(FirstName, v => { })
                                               .WithNamed(SecondName, v => { })
                                               .BuildConfiguration());
            });

            "when parsing".x(() =>
                             result = parser.Parse(args));

            "should return parsing failure".x(() =>
                                              result.Succeeded.Should().BeFalse());
        }
Exemplo n.º 6
0
        public void Switch(
            string[] args,
            bool firstParsedSwitch,
            string secondParsedSwitch,
            ICommandLineParser parser)
        {
            "establish arguments with switch".x(() =>
                                                args = new[]
            {
                "-firstSwitch", "-secondSwitch"
            });

            "establish a parser with parsing configuration for switches".x(() =>
            {
                CommandLineConfiguration configuration = CommandLineParserConfigurator
                                                         .Create()
                                                         .WithSwitch("firstSwitch", () => firstParsedSwitch   = true)
                                                         .WithSwitch("secondSwitch", () => secondParsedSwitch = "yeah")
                                                         .BuildConfiguration();

                parser = new CommandLineParser(configuration);
            });

            "when parsing".x(() =>
                             parser.Parse(args));

            "should parse switch".x(() =>
                                    new object[]
            {
                firstParsedSwitch, secondParsedSwitch
            }
                                    .Should().Equal(true, "yeah"));
        }
Exemplo n.º 7
0
        public static void Main(string[] args)
        {
            const string ShortOutput = "short";
            const string LongOutput  = "long";

            // set default values here
            string output    = null;
            bool   debug     = false;
            string path      = null;
            string value     = null;
            int    threshold = 0;

            var configuration = CommandLineParserConfigurator
                                .Create()
                                .WithNamed("o", v => output = v)
                                .HavingLongAlias("output")
                                .Required()
                                .RestrictedTo(ShortOutput, LongOutput)
                                .DescribedBy("method", "specifies the output method.")
                                .WithNamed("t", (int v) => threshold = v)
                                .HavingLongAlias("threshold")
                                .DescribedBy("value", "specifies the threshold used in output.")
                                .WithSwitch("d", () => debug = true)
                                .HavingLongAlias("debug")
                                .DescribedBy("enables debug mode")
                                .WithPositional(v => path = v)
                                .Required()
                                .DescribedBy("path", "path to the output file.")
                                .WithPositional(v => value = v)
                                .DescribedBy("value", "some optional value.")
                                .BuildConfiguration();

            var parser = new CommandLineParser(configuration);

            var parseResult = parser.Parse(args);

            if (!parseResult.Succeeded)
            {
                Usage usage = new UsageComposer(configuration).Compose();
                Console.WriteLine(parseResult.Message);
                Console.WriteLine("usage:" + usage.Arguments);
                Console.WriteLine("options");
                Console.WriteLine(usage.Options.IndentBy(4));
                Console.WriteLine();

                return;
            }

            Console.WriteLine("parsed successfully: path = " + path + ", value = " + value + "output = " + output + ", debug = " + debug + ", threshold = " + threshold);
        }
Exemplo n.º 8
0
        public void RealWorldScenario(
            string[] args,
            bool firstParsedSwitch,
            string secondParsedSwitch,
            string firstNamedValue,
            string secondNamedValue,
            string firstPositionalValue,
            string secondPositionalValue,
            ICommandLineParser parser)
        {
            "establish arguments".x(() =>
                                    args = new[]
            {
                "1u", "-secondSwitch", "-firstName", "1n", "-firstSwitch", "-secondName", "2n", "2u"
            });

            "establish a parsing configuration".x(() =>
            {
                var configuration = CommandLineParserConfigurator
                                    .Create()
                                    .WithNamed("firstName", s => firstNamedValue = s)
                                    .Required()
                                    .RestrictedTo("1n", "??")
                                    .DescribedBy("name", "the first name")
                                    .WithSwitch("firstSwitch", () => firstParsedSwitch = true)
                                    .WithPositional(x => firstPositionalValue          = x)
                                    .Required()
                                    .WithSwitch("secondSwitch", () => secondParsedSwitch = "yeah")
                                    .HavingLongAlias("theOtherSwitch")
                                    .DescribedBy("the second switch")
                                    .WithPositional(x => secondPositionalValue     = x)
                                    .WithNamed("secondName", s => secondNamedValue = s)
                                    .BuildConfiguration();

                parser = new CommandLineParser(configuration);
            });

            "when parsing".x(() =>
                             parser.Parse(args));

            "should parse arguments".x(() =>
                                       new object[]
            {
                firstParsedSwitch, secondParsedSwitch, firstNamedValue, secondNamedValue, firstPositionalValue, secondPositionalValue
            }
                                       .Should().Equal(true, "yeah", "1n", "2n", "1u", "2u"));
        }
Exemplo n.º 9
0
        public void UnknownArgument(
            string[] args,
            CommandLineConfiguration configuration,
            UsageComposer usageComposer,
            Usage usage)
        {
            "establish a parsing configuration"._(() =>
            {
                configuration = CommandLineParserConfigurator
                                .Create()
                                .WithNamed("optional", _)
                                .DescribedBy("placeholder", "optional description")
                                .WithNamed("required", _)
                                .Required()
                                .DescribedBy("placeholder", "required description")
                                .BuildConfiguration();
            });

            "establish a usage composer using the parsing configuration"._(() =>
            {
                usageComposer = new UsageComposer(configuration);
            });

            "when composing usage"._(() =>
                                     usage = usageComposer.Compose());

            "should list arguments"._(() =>
                                      usage.Arguments
                                      .Should().Contain("-optional <placeholder>")
                                      .And.Contain("-required <placeholder>"));

            "should show whether an argument is optional or required"._(() =>
                                                                        (usage.Arguments + " ")
                                                                        .Should().Contain("[-optional <placeholder>]")
                                                                        .And.Contain(" -required <placeholder> "));

            "should list options per argument with description"._(() =>
                                                                  usage.Options
                                                                  .Should().Contain("optional description")
                                                                  .And.Contain("required description"));
        }
Exemplo n.º 10
0
        public void SupportsLongAliasForNamed(
            string[] args,
            string nameParsedArgument,
            string longAliasParsedArgument,
            ICommandLineParser parser)
        {
            const string Name           = "s";
            const string ShortValue     = "short";
            const string LongAlias      = "long";
            const string LongAliasValue = "long";

            "establish named arguments with long alias".x(() =>
                                                          args = new[]
            {
                "-" + Name, ShortValue, "--" + LongAlias, LongAliasValue
            });

            "establish a parser with parsing configuration with long aliases".x(() =>
            {
                parser = new CommandLineParser(CommandLineParserConfigurator
                                               .Create()
                                               .WithNamed(Name, v => nameParsedArgument = v)
                                               .HavingLongAlias("_")
                                               .WithNamed("_", v => longAliasParsedArgument = v)
                                               .HavingLongAlias(LongAlias)
                                               .BuildConfiguration());
            });

            "when parsing".x(() =>
                             parser.Parse(args));

            "should parse named arguments".x(() =>
                                             new[]
            {
                nameParsedArgument, longAliasParsedArgument
            }
                                             .Should().Equal(ShortValue, LongAliasValue));
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            List <AbsoluteFilePath> paths = null;

            var configuration = CommandLineParserConfigurator.Create()
                                .WithPositional(v => paths = v.Split(';').Select(x => new AbsoluteFilePath(Path.GetFullPath(x))).ToList())
                                .BuildConfiguration();

            var parser = new CommandLineParser(configuration);

            var result = parser.Parse(args);

            if (!result.Succeeded)
            {
                Console.WriteLine(result.Message);
                return;
            }

            foreach (AbsoluteFilePath path in paths)
            {
                ConvertFile(path);
            }
        }
Exemplo n.º 12
0
        public void NamedArguments(
            string[] args,
            string firstParsedArgument,
            string secondParsedArgument,
            ICommandLineParser parser)
        {
            const string FirstName   = "firstName";
            const string FirstValue  = "firstValue";
            const string SecondName  = "secondName";
            const string SecondValue = "secondValue";

            "establish named arguments".x(() =>
                                          args = new[]
            {
                "-" + FirstName, FirstValue, "-" + SecondName, SecondValue
            });

            "establish a parser with parsing configuration for named arguments".x(() =>
            {
                parser = new CommandLineParser(CommandLineParserConfigurator
                                               .Create()
                                               .WithNamed(FirstName, v => firstParsedArgument   = v)
                                               .WithNamed(SecondName, v => secondParsedArgument = v)
                                               .BuildConfiguration());
            });

            "when parsing".x(() =>
                             parser.Parse(args));

            "should parse named arguments".x(() =>
                                             new[]
            {
                firstParsedArgument, secondParsedArgument
            }
                                             .Should().Equal(FirstValue, SecondValue));
        }
Exemplo n.º 13
0
        public static int Main(string[] args)
        {
            string input  = null;
            string output = null;
            string markup = Markdown;

            var configuration = CommandLineParserConfigurator
                                .Create()
                                .WithNamed("i", v => input = v)
                                .HavingLongAlias("input")
                                .Required()
                                .DescribedBy("path", "specifies the input path pointing to a xBehave/xUnit XML report.")
                                .WithNamed("o", v => output = v)
                                .HavingLongAlias("output")
                                .Required()
                                .DescribedBy("path", "specifies the output path where the generated markdown will be written to.")
                                .WithNamed("m", v => markup = v)
                                .HavingLongAlias("markup")
                                .DescribedBy($"markup [{Markdown} | {DokuWiki}]", "specifies which markup to use")
                                .BuildConfiguration();

            var parser      = new CommandLineParser(configuration);
            var parseResult = parser.Parse(args);

            if (!parseResult.Succeeded)
            {
                Usage usage = new UsageComposer(configuration).Compose();
                Console.WriteLine(parseResult.Message);
                Console.WriteLine("usage:" + usage.Arguments);
                Console.WriteLine("options");
                Console.WriteLine(usage.Options.IndentBy(4));
                Console.WriteLine();
                return(InvalidFunction);
            }

            if (!File.Exists(input))
            {
                Console.WriteLine("Input file '{0}' does not exist, please define an existing file.", input);
                return(FileNotFound);
            }

            IMarkupWriter markupWriter;

            switch (markup.ToLowerInvariant())
            {
            case Markdown:
                markupWriter = new MarkdownWriter();
                break;

            case DokuWiki:
                markupWriter = new DokuWikiWriter();
                break;

            default:
                return(InvalidMarkup);
            }

            var inputXml = XDocument.Load(input);

            var converter = new Converter(markupWriter);

            var outputMarkdown = converter.Convert(inputXml);

            using (var writer = new StreamWriter(output))
            {
                writer.Write(outputMarkdown);
            }

            return(Ok);
        }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            string direction  = string.Empty;
            bool   query      = false;
            bool   raw        = false;
            bool   init       = false;
            bool   deInit     = false;
            bool   help       = false;
            bool   htmlReport = false;
            string inject     = string.Empty;
            string tags       = string.Empty;
            string timeSpan   = string.Empty;
            bool   pause      = false;

            var configuration = CommandLineParserConfigurator
                                .Create()
                                .WithSwitch("q", () => query      = true).HavingLongAlias("query").DescribedBy("Call the db and get your working times.")
                                .WithSwitch("r", () => raw        = true).HavingLongAlias("raw").DescribedBy("Get all logged events")
                                .WithSwitch("i", () => init       = true).HavingLongAlias("init").DescribedBy("Create windows tasks (you need elevated permissions for this one!")
                                .WithSwitch("d", () => deInit     = true).HavingLongAlias("deinit").DescribedBy("Remove windows tasks (you need elevated permissions for this one!")
                                .WithSwitch("b", () => pause      = true).HavingLongAlias("pause").DescribedBy("Manage your breaks")
                                .WithSwitch("h", () => help       = true).HavingLongAlias("help").DescribedBy("Show this usage screen.")
                                .WithSwitch("o", () => htmlReport = true).HavingLongAlias("out").DescribedBy("Show html report.")
                                .WithNamed("j", I => inject       = I).HavingLongAlias("inject").DescribedBy("Time|Direction\"", "Use this for debugging only! You can inject timestamps. 1 for lock, 0 for unlock")
                                .WithNamed("t", t => tags         = t).HavingLongAlias("tags").DescribedBy("timestamp|Tag1,Tag2,...\"", "Tag a timestamp; use ticks for the timestamp (-r shows them)")
                                .WithPositional(d => direction    = d).DescribedBy("lock", "tell me to \"lock\" for \"out\" and keep empty for \"in\"")
                                .BuildConfiguration();
            var parser = new CommandLineParser(configuration);

            var parseResult = parser.Parse(args);

            if (!parseResult.Succeeded || args.Length == 0)
            {
                ShowUsage(configuration, parseResult.Message);
                Environment.Exit((int)ExitCode.ArgumentError);
            }
            else
            {
                if (help)
                {
                    ShowUsage(configuration);
                    Environment.Exit((int)ExitCode.OK);
                }
                if (init)
                {
                    using (TaskService ts = new TaskService())
                    {
                        try
                        {
                            DefineTask(ts, "myLock lock screen", "lock_pc", TriggerType.Lock);
                            DefineTask(ts, "myLock unlock screen", "unlock_pc", TriggerType.Unlock);
                            DefineTask(ts, "myLock login to pc", "login_pc", TriggerType.Logon);
                            DefineTask(ts, "myLock logout from pc", "logout_pc", TriggerType.Logoff);
                            DefineTask(ts, "myLock energysaver from pc", "energysave_pc", TriggerType.Energysave);
                            Console.WriteLine("Initialization complete.");
                            Environment.Exit((int)ExitCode.OK);
                        }
                        catch (UnauthorizedAccessException)
                        {
                            Console.Error.WriteLine("Access denied, please use an elevated prompt.");
                            Environment.Exit((int)ExitCode.Exception);
                        }
                    }
                }
                if (deInit)
                {
                    using (TaskService ts = new TaskService())
                    {
                        try
                        {
                            //Remove tasks
                            foreach (var t in ts.RootFolder.AllTasks)
                            {
                                if (t.Name.StartsWith(taskPrefix))
                                {
                                    ts.RootFolder.DeleteTask(t.Name);
                                }
                            }

                            Console.WriteLine("Deinitialization complete.");
                            Environment.Exit((int)ExitCode.OK);
                        }
                        catch (UnauthorizedAccessException)
                        {
                            Console.Error.WriteLine("Access denied, please use an elevated prompt.");
                            Environment.Exit((int)ExitCode.Exception);
                        }
                    }
                }
                if (!string.IsNullOrEmpty(inject))
                {
                    TimeStampCollection col;
                    try
                    {
                        col = Saver.Load <TimeStampCollection>(dbFile);
                    }
                    catch (FileNotFoundException)
                    {
                        col = new TimeStampCollection();
                    }
                    TimeStamp stamp     = new TimeStamp();
                    string[]  injection = inject.Split('|');
                    stamp.Stamp = DateTime.Parse(injection[0]);
                    if (injection.Length > 1)
                    {
                        stamp.Direction = (Direction)(Convert.ToInt32(injection[1]));
                    }
                    if (injection.Length > 2)
                    {
                        stamp.User = injection[2];
                    }

                    col.TimeStamps.Add(stamp);
                    col.TimeStamps.Sort();
                    Saver.Save <TimeStampCollection>(dbFile, col);

                    Console.WriteLine("Injection successfull.");
                    Console.WriteLine("Values were: {0}", inject);

                    Environment.Exit((int)ExitCode.OK);
                }

                if (raw)
                {
                    TimeStampCollection col = Saver.Load <TimeStampCollection>(dbFile);
                    foreach (var t in col.TimeStamps)
                    {
                        Console.WriteLine("{0,-10} {1} {2} {3} {4}", UnixTimestampFromDateTime(t.Stamp), t.Stamp, t.User, t.Direction, (t.Tags.Count > 0) ? "Tags: " + String.Join(", ", t.Tags) : string.Empty);
                    }

                    Console.WriteLine("EOF");

                    Environment.Exit((int)ExitCode.OK);
                }
                if (pause)
                {
                    interactivebreaktime(0);
                }
                if (!string.IsNullOrEmpty(tags))
                {
                    TimeStampCollection col;
                    try
                    {
                        col = Saver.Load <TimeStampCollection>(dbFile);
                    }
                    catch (FileNotFoundException)
                    {
                        col = new TimeStampCollection();
                    }
                    int iPipe = tags.IndexOf("|");
                    if (iPipe == -1)
                    {
                        Console.Error.WriteLine("Wrong input format, use \"Ticks|foo,bar,zwusch\"!");
                        Environment.Exit(-3);
                    }
                    long          lTicks  = long.Parse(tags.Substring(0, iPipe));
                    List <string> tagList = tags.Substring(iPipe + 1).Split(',').ToList <string>();

                    try
                    {
                        var q = (from c in col.TimeStamps where UnixTimestampFromDateTime(c.Stamp) == lTicks select c).Single();
                        q.Tags.AddRange(tagList);

                        Saver.Save <TimeStampCollection>(dbFile, col);
                    }
                    catch (InvalidOperationException)
                    {
                        Console.Error.WriteLine("Timestamp {0} could not be found. Check with \"-r\".", lTicks);
                        Environment.Exit((int)ExitCode.Exception);
                    }
                }

                if (!query)
                {
                    LogTimeStamp(direction);
                }
                else
                {
                    if (!htmlReport)
                    {
                        QueryWorkingTimes(timeSpan);
                    }
                    else
                    {
                    }
                }
            }
        }