Ejemplo n.º 1
0
 private static void ArgumentParsingComplete(ParsedArguments arguments)
 {
     if (arguments.Contains("i"))
     {
         interactive = true;
     }
 }
        private ParsedArguments GetSwitchDictionary(
            string[] args)
        {
            var result = new ParsedArguments();

            int indexOfSwitch = 0;

            while (indexOfSwitch < args.Length)
            {
                var switchArg = args[indexOfSwitch];
                var switchType = CommandlineSwitchType.GetTypeForCommandLineSwitch(switchArg);

                var indexOfSwitchValue = indexOfSwitch + 1;

                if (WeHaveMatchingCommandLineSwitch(switchType)
                    && ArgsIsLargeEnoughtToSupportSwitchValue(args, indexOfSwitchValue))

                {
                    var switchValue = args[indexOfSwitchValue];
                    result.SetValue(switchType, switchValue);
                }

                indexOfSwitch += 2;
            }

            return result;
        }
Ejemplo n.º 3
0
        public void TestNoUpdateKeys()
        {
            ParsedArguments args = ArgumentParser.Parse(new string[] { "Stardew Valley", "TestMod", "-u", "" });

            Assert.AreEqual(1, args.ModUpdateKeys.Count());
            Assert.AreEqual("", args.ModUpdateKeys.ElementAt(0));
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Returns this <see cref="ParsedArguments"/> in a human readable format.
        /// </summary>
        /// <param name="detailed">True if the output should be detailed.</param>
        /// <returns>A <see cref="string"/>.</returns>
        public string ToString(bool detailed)
        {
            StringBuilder      returnValue      = new StringBuilder();
            ArgumentDictionary invalidArguments = ParsedArguments.GetInvalidArguments();
            ArgumentDictionary validArguments   = ParsedArguments.GetValidArguments();

            if (validArguments.Count > 0)
            {
                returnValue.AppendLine("Valid Arguments:");
                returnValue.AppendLine();

                foreach (Argument validArgument in validArguments.Values)
                {
                    returnValue.AppendLine(" " + validArgument.ToString(detailed));
                }
            }

            if (invalidArguments.Count > 0)
            {
                returnValue.AppendLine();
                returnValue.AppendLine("Invalid Arguments:");
                returnValue.AppendLine();

                foreach (Argument invalidArgument in invalidArguments.Values)
                {
                    returnValue.AppendLine(" " + invalidArgument.ToString(detailed));
                }
            }

            return(returnValue.ToString());
        }
Ejemplo n.º 5
0
        private ParsedArguments GetSwitchDictionary(
            string[] args)
        {
            var result = new ParsedArguments();

            int indexOfSwitch = 0;

            while (indexOfSwitch < args.Length)
            {
                var switchArg  = args[indexOfSwitch];
                var switchType = CommandlineSwitchType.GetTypeForCommandLineSwitch(switchArg);

                var indexOfSwitchValue = indexOfSwitch + 1;

                if (WeHaveMatchingCommandLineSwitch(switchType) &&
                    ArgsIsLargeEnoughtToSupportSwitchValue(args, indexOfSwitchValue))

                {
                    var switchValue = args[indexOfSwitchValue];
                    result.SetValue(switchType, switchValue);
                }

                indexOfSwitch += 2;
            }

            return(result);
        }
Ejemplo n.º 6
0
        public static void Main(string[] args)
        {
            try
            {
                var parsedArguments = new ParsedArguments(args);
                var stopwatch       = new System.Diagnostics.Stopwatch();
                stopwatch.Start();

                string transcodedFilePath = Path.ChangeExtension(parsedArguments.inputFilePath, ".Transcoded.fit");
                string finalOriginalPath  = Path.ChangeExtension(parsedArguments.inputFilePath, ".Original.fit");

                TranscodeFile(parsedArguments.inputFilePath, transcodedFilePath, parsedArguments.resultantSport);

                stopwatch.Stop();
                Console.WriteLine("");
                Console.WriteLine("Time elapsed: {0:0.#}s", stopwatch.Elapsed.TotalSeconds);

                Console.WriteLine("Transcode successful. Moving files..");

                File.Move(parsedArguments.inputFilePath, finalOriginalPath);
                Console.WriteLine("Moved original to {0}.", finalOriginalPath);

                File.Move(transcodedFilePath, parsedArguments.inputFilePath);
                Console.WriteLine("Moved transcoded to {0}.", parsedArguments.inputFilePath);

                Console.WriteLine("Done.");
            }
            catch (Exception caught)
            {
                Console.WriteLine("Execution failed with exception:\n{0}", caught.ToString());
            }

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
        public MainWindow()
        {
            var parsedArguments = new ParsedArguments(new string[] { });
            var server          = new Server(parsedArguments);

            _server = server;

            server.TempAddSink(new GraphDataSink(this));

            server.Run();

            InitializeComponent();

            var plt = TheGraph.plt;

            Random rand       = new Random(0);
            int    pointCount = (int)1e6;
            int    lineCount  = 5;

            plt.Title("Signal Plot Quickstart (5 million points)");
            plt.YLabel("Vertical Units");
            plt.XLabel("Horizontal Units");

            plt.Resize();
            TheGraph.Render();
        }
Ejemplo n.º 8
0
        public void TestMultipleUpdateKeys()
        {
            ParsedArguments args = ArgumentParser.Parse(new string[] { "Stardew Valley", "TestMod", "-u", "Nexus:1234,Nexus:4321" });

            Assert.AreEqual(2, args.ModUpdateKeys.Count());
            Assert.AreEqual("Nexus:1234", args.ModUpdateKeys.ElementAt(0));
            Assert.AreEqual("Nexus:4321", args.ModUpdateKeys.ElementAt(1));
        }
Ejemplo n.º 9
0
        public void HasUndoScriptFileShouldReturnTrueWhenUndoScriptFilePopulated()
        {
            var parsedArguments = new ParsedArguments();

            parsedArguments.SetValue(CommandlineSwitchType.UndoFile, "sdf");

            Assert.That(parsedArguments.HasValue(CommandlineSwitchType.UndoFile), Is.True);
        }
Ejemplo n.º 10
0
        public void GetScriptsFilesFolderShouldReturnDefaultWhenScriptFilesFolderIsNotSet()
        {
            var parsedArguments = new ParsedArguments();

            var r = parsedArguments.GetScriptFilesFolderOrDefaultFolder();

            Assert.That(r, Is.EqualTo(ParsedArguments.ScriptFilesFolderDefault));
        }
Ejemplo n.º 11
0
        private IViolationReporter CreateViolationReporter(ParsedArguments arguments)
        {
            if (arguments.ReportOutputFile != null)
            {
                return(_violationReporterFactory.CreateFileReporter(arguments.ReportFormat, arguments.ReportOutputFile));
            }

            return(_violationReporterFactory.CreateConsoleReporter(arguments.ReportFormat));
        }
Ejemplo n.º 12
0
        private ParsedArguments GetResultsForArgs(
            string[] args)
        {
            var parser = new CommandLineArgumentsParser();

            ParsedArguments result = parser.ParseArgs(args);

            return(result);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Execute any ArgZero arguments specified on the command line.  Has no effect if no relevant arguments
        /// are detected.
        /// </summary>
        public static void ExecuteArgZero(string[] arguments, Action onArgZeroExecuted = null)
        {
            if (arguments.Length == 0)
            {
                return;
            }

            if (Environment.GetCommandLineArgs().Any(a => a.Equals("/pause")))
            {
                Pause("Press enter to continue");
            }

            onArgZeroExecuted ??= (() => { });

            if (Targets.ContainsKey(arguments[0]))
            {
                List <string>       targetArguments = new List <string>();
                List <ArgumentInfo> argumentInfos   = new List <ArgumentInfo>();
                arguments.Rest(2, (val) =>
                {
                    targetArguments.Add(val);
                    if (val.StartsWith("/"))
                    {
                        string argName = val.TruncateFront(1).ReadUntil(':', out string argVal);
                        argumentInfos.Add(new ArgumentInfo(argName, true));
                    }
                });
                Arguments = new ParsedArguments(targetArguments.ToArray(), argumentInfos.ToArray());
                MethodInfo method = Targets[arguments[0]];
                if (method.HasCustomAttributeOfType <ArgZeroAttribute>(out ArgZeroAttribute argZeroAttribute))
                {
                    if (argZeroAttribute.BaseType != null)
                    {
                        RegisterArgZeroProviderTypes(argZeroAttribute.BaseType, arguments, argZeroAttribute.BaseType.Assembly);
                    }
                }

                object instance = null;
                if (!method.IsStatic)
                {
                    instance = method.DeclaringType.Construct();
                }

                try
                {
                    ArgZeroDelegator.CommandLineArguments = arguments;
                    method.Invoke(instance, null);
                }
                catch (Exception ex)
                {
                    Message.PrintLine("Exception executing ArgZero: {0}", ConsoleColor.Magenta, ex.Message);
                }

                onArgZeroExecuted();
            }
        }
Ejemplo n.º 14
0
        public void TestOptionsDontAffectEachOther()
        {
            ParsedArguments args = ArgumentParser.Parse(new string[] { "Stardew Valley", "TestMod", "-a", "John Doe" });

            Assert.AreEqual("John Doe", args.AuthorName);
            Assert.AreEqual("", args.ModName);
            Assert.AreEqual("1.0.0", args.ModVersion);
            Assert.AreEqual("", args.ModDescription);
            Assert.AreEqual("", args.ModUpdateKeys);
        }
Ejemplo n.º 15
0
        public void GetScriptsFilesFolderShouldReturnScriptFolderWhenScriptFolderPopulated()
        {
            var parsedArguments = new ParsedArguments();

            parsedArguments.SetValue(CommandlineSwitchType.ScriptFiles, "c:\\foo");

            var r = parsedArguments.GetScriptFilesFolderOrDefaultFolder();

            Assert.That(r, Is.EqualTo("c:\\foo"));
        }
Ejemplo n.º 16
0
        public TextWriter GetDoPrintStream(
            ParsedArguments p)
        {
            if (p.HasValue(CommandlineSwitchType.DoFile))
            {
                return(new StreamWriter(p.GetValue(CommandlineSwitchType.DoFile)));
            }

            return(Console.Out);
        }
        public void GetAll_Named_Empty()
        {
            var target = new ParsedArguments(new[]
            {
                new ParsedNamedArgument("a", "1"),
                new ParsedNamedArgument("a", "2")
            });
            var result = target.GetAll("XXX").ToList();

            result.Count.Should().Be(0);
        }
        public void GetDoPrintStreamShouldReturnConsoleWhenNotGivenFinalScriptFile()
        {
            var printScreenFactory = new PrintScreenFactory();

            var parsedArguments = new ParsedArguments();

            TextWriter results = printScreenFactory.GetDoPrintStream(parsedArguments);

            Assert.That(results, Is.EqualTo(System.Console.Out));

            printScreenFactory.ClosePrintStream(results);
        }
        public void VerifyAllAreConsumed_NotConsumed()
        {
            var target = new ParsedArguments(new IParsedArgument[]
            {
                new ParsedPositionalArgument("test1"),
                new ParsedNamedArgument("b", "test2"),
                new ParsedFlagArgument("c")
            });
            Action act = () => target.VerifyAllAreConsumed();

            act.Should().Throw <CommandArgumentException>();
        }
Ejemplo n.º 20
0
        private IEnumerable <string> ArgsToForwardToRestore()
        {
            var restoreArguments = ParsedArguments.Where(a =>
                                                         !a.StartsWith("/p:TargetFramework"));

            if (!restoreArguments.Any(a => a.StartsWith("/verbosity:")))
            {
                restoreArguments = restoreArguments.Concat(new string[] { "/verbosity:q" });
            }

            return(restoreArguments.Concat(TrailingArguments));
        }
        public void Shift_Test()
        {
            var target = new ParsedArguments(new[]
            {
                new ParsedPositionalArgument("a"),
                new ParsedPositionalArgument("b")
            });

            target.Shift().Value.Should().Be("a");
            target.Shift().Value.Should().Be("b");
            target.Shift().Should().BeOfType <MissingArgument>();
        }
Ejemplo n.º 22
0
        internal string Pluralize(string locale, ParsedArguments arguments, double n, double offset)
        {
            Pluralizer pluralizer;

            if (this.Pluralizers.TryGetValue(locale, out pluralizer) == false)
            {
                pluralizer = this.Pluralizers["en"];
            }

            var        pluralForm = pluralizer(n - offset);
            KeyedBlock other      = null;

            foreach (var keyedBlock in arguments.KeyedBlocks)
            {
                if (keyedBlock.Key == OtherKey)
                {
                    other = keyedBlock;
                }

                if (keyedBlock.Key.StartsWith("="))
                {
                    var numberLiteral = Convert.ToDouble(keyedBlock.Key.Substring(1));

                    // ReSharper disable once CompareOfFloatsByEqualityOperator
                    if (numberLiteral == n)
                    {
                        return(keyedBlock.BlockText);
                    }
                }

                if (keyedBlock.Key.StartsWith("%"))
                {
                    var numberLiteral = Convert.ToInt32(keyedBlock.Key.Substring(1));

                    if (n % numberLiteral == 0)
                    {
                        return(keyedBlock.BlockText);
                    }
                }

                if (keyedBlock.Key == pluralForm)
                {
                    return(keyedBlock.BlockText);
                }
            }

            if (other == null)
            {
                throw new MessageFormatterException("'other' option not found in pattern.");
            }

            return(other.BlockText);
        }
        public void GetAll_Named_Test()
        {
            var target = new ParsedArguments(new[]
            {
                new ParsedNamedArgument("a", "1"),
                new ParsedNamedArgument("a", "2")
            });
            var result = target.GetAll("a").Cast <INamedArgument>().ToList();

            result.Count.Should().Be(2);
            result[0].Value.Should().Be("1");
            result[1].Value.Should().Be("2");
        }
Ejemplo n.º 24
0
        public void ParseArgsShouldSetScriptFilesPathWhenGivenArgs()
        {
            var args = new[]
            {
                CommandlineSwitchType.ScriptFiles.GetSwitch()
                , SourcePath
            };

            ParsedArguments result = GetResultsForArgs(
                args);

            Assert.That(result.GetValue(CommandlineSwitchType.ScriptFiles), Is.EqualTo(SourcePath));
        }
        public void GetUndoPrintStreamShouldReturnFileWriterWhenGivenFinalScriptFile()
        {
            var printScreenFactory = new PrintScreenFactory();

            var parsedArguments = new ParsedArguments();

            parsedArguments.SetValue(CommandlineSwitchType.UndoFile, "c:\\temp\\foo2.sql");

            TextWriter results = printScreenFactory.GetUndoPrintStream(parsedArguments);

            Assert.That(results, Is.TypeOf <StreamWriter>());

            printScreenFactory.ClosePrintStream(results);
        }
Ejemplo n.º 26
0
        static int Main(string[] args)
        {
            ParsedArguments parsedArgs = null;

            try
            {
                parsedArgs = ArgumentParser.Parse(args);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("An error occured when trying to parse command line arguments: ");
                Console.Error.WriteLine(e.ToString());
                return(-1);
            }

            if (Path.GetFileName(parsedArgs.SDVContentRootDirectory) != "Content")
            {
                Console.Error.WriteLine($"\"{parsedArgs.SDVContentRootDirectory}\" doesn't look like a valid SDV Content Directory: ");
                Console.Error.WriteLine($"It doesn't point to a Content folder.");
                return(-1);
            }

            MappedDirectory mapping = DirectoryMapper.TryMapDirectories(parsedArgs.SDVContentRootDirectory, parsedArgs.ModRootDirectory, out IDictionary <string, string> errors);

            if (mapping == null)
            {
                Console.Error.WriteLine($"An error occured when trying to map the mod to the game's Content folder: ");
                foreach (KeyValuePair <string, string> errorinfo in errors)
                {
                    Console.Error.WriteLine($"{errorinfo.Key} is invalid because: ${errorinfo.Value}");
                }
                return(-1);
            }

            ContentPack p = new ContentPack(Path.Combine(Directory.GetCurrentDirectory(), "CP"));

            if (Directory.Exists(p.RootDirectory))
            {
                Directory.Delete(p.RootDirectory, true);
            }
            Directory.CreateDirectory(p.RootDirectory);
            Console.WriteLine(p.RootDirectory);

            p.GenerateManifest(parsedArgs);

            ContentGenerator.GenerateContent(p.RootDirectory, mapping);

            return(0);
        }
        /// <summary>
        ///     Validates the <paramref name="arguments" /> against model.
        /// </summary>
        /// <param name="arguments">The arguments.</param>
        /// <exception cref="ConsoleExtensions.Commandline.Exceptions.UnknownOptionException">
        ///     Thrown when a requested options is unknown.
        /// </exception>
        /// <exception cref="ConsoleExtensions.Commandline.Exceptions.UnknownCommandException">
        ///     Thrown when a requested command is unknown.
        /// </exception>
        private void ValidateArgumentsAgainstModel(ParsedArguments arguments)
        {
            foreach (var argument in arguments.Properties)
            {
                if (!this.ModelMap.Options.TryGetValue(argument.Key, out _))
                {
                    throw new UnknownOptionException(argument.Key, this.ModelMap.Options.Values);
                }
            }

            if (!this.ModelMap.Commands.TryGetValue(arguments.Command, out _))
            {
                throw new UnknownCommandException(arguments.Command, this.ModelMap.Commands.Values);
            }
        }
Ejemplo n.º 28
0
        public void ParseArgsShouldUndoScriptFileWhenGivenArgs()
        {
            ParsedArguments result = GetResultsForArgs(
                new[]
            {
                CommandlineSwitchType.ScriptFiles.GetSwitch()
                , SourcePath
                , CommandlineSwitchType.DoFile.GetSwitch()
                , DoScriptFile
                , CommandlineSwitchType.UndoFile.GetSwitch()
                , UndoScriptFile
            });

            Assert.That(result.GetValue(CommandlineSwitchType.UndoFile), Is.EqualTo(UndoScriptFile));
        }
        public void MapTo_Test()
        {
            var target = new ParsedArguments(new IParsedArgument[]
            {
                new ParsedPositionalArgument("test1"),
                new ParsedNamedArgument("b", "test2"),
                new ParsedFlagArgument("c")
            });
            var result = target.MapTo <TestArgs1>();

            result.A.Should().Be("test1");
            result.B.Should().Be("test2");
            result.C.Should().BeTrue();
            result.D.Should().BeFalse();
        }
        public void VerifyAllAreConsumed_Consumed()
        {
            var target = new ParsedArguments(new IParsedArgument[]
            {
                new ParsedPositionalArgument("test1"),
                new ParsedNamedArgument("b", "test2"),
                new ParsedFlagArgument("c")
            });

            target.Consume(0);
            target.Consume("b");
            target.ConsumeFlag("c");
            Action act = () => target.VerifyAllAreConsumed();

            act.Should().NotThrow();
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Parse the array of command line arguments.
        /// </summary>
        /// <param name="args">The array of command line arguments.</param>
        public void Parse(string[] args)
        {
            _ParsedArguments.Clear();
            List <string> arguments = args.ToList();

            Argument lastArgumentWithPrefix = null;

            for (int i = 0; i < arguments.Count; i++)
            {
                string currentValue = arguments[i];
                string parameter;

                if (GetArgumentNameWithoutPrefix(ref currentValue, out parameter))
                {
                    if (!string.IsNullOrEmpty(parameter))
                    {
                        arguments.Insert(i + 1, parameter);
                    }

                    lastArgumentWithPrefix = BuildArgument(currentValue, true);

                    ParsedArguments.Add(lastArgumentWithPrefix);
                }
                else
                {
                    bool addArgument = !string.IsNullOrEmpty(currentValue);

                    if (lastArgumentWithPrefix != null)
                    {
                        if (lastArgumentWithPrefix.ArgumentValue != ArgumentValue.None)
                        {
                            addArgument = false;
                            lastArgumentWithPrefix.Value = currentValue;

                            SetArgumentIsValid(lastArgumentWithPrefix);
                        }

                        lastArgumentWithPrefix = null;
                    }

                    if (addArgument)
                    {
                        ParsedArguments.Add(BuildArgument(currentValue, false));
                    }
                }
            }
        }
        static void Main(string[] arguments)
        {
            var args = new ParsedArguments(arguments);

            if (args.Params.Count > 0)
            {
                string inputFile = args.Params.FirstOrDefault();
                var util = new XmlDocumentSweeper(inputFile);

                string outputFile = args.GetNamedParam("output");
                if (string.IsNullOrWhiteSpace(outputFile) && args.HasSwitch("replace"))
                    outputFile = inputFile;

                if (!string.IsNullOrWhiteSpace(outputFile))
                    util.Transform(outputFile);
                else
                    Console.WriteLine(util.Transform());
            }
            else
                usage();
        }
 private static void ArgumentParsingComplete(ParsedArguments arguments)
 {
     if (arguments.Contains("i"))
         interactive = true;
 }
Ejemplo n.º 34
0
 public ParsedArguments ParseArgumentsAndMerge(IEnumerable<string> arg, ParsedArguments parsedArguments)
 {
     var parsedMethod = Parse(arg);
     // Inferred ordinal arguments should not be recognized twice
     parsedArguments.RecognizedArguments = parsedArguments.RecognizedArguments
         .Where(argopts =>
             !parsedMethod.RecognizedArguments.Any(pargopt => pargopt.Index == argopts.Index && argopts.InferredOrdinal));
     var merged = parsedArguments.Merge(parsedMethod);
     if (!_controller.IgnoreGlobalUnMatchedParameters)
         merged.AssertFailOnUnMatched();
     return merged;
 }
Ejemplo n.º 35
0
        internal string Pluralize(string locale, ParsedArguments arguments, double n, double offset)
        {
            Pluralizer pluralizer;
            if (this.Pluralizers.TryGetValue(locale, out pluralizer) == false)
            {
                pluralizer = this.Pluralizers["en"];
            }

            var pluralForm = pluralizer(n - offset);
            KeyedBlock other = null;
            foreach (var keyedBlock in arguments.KeyedBlocks)
            {
                if (keyedBlock.Key == OtherKey)
                {
                    other = keyedBlock;
                }

                if (keyedBlock.Key.StartsWith("="))
                {
                    var numberLiteral = Convert.ToDouble(keyedBlock.Key.Substring(1));
                    if (Math.Abs(numberLiteral - n) < double.Epsilon)
                    {
                        return keyedBlock.BlockText;
                    }
                }

                if (keyedBlock.Key == pluralForm)
                {
                    return keyedBlock.BlockText;
                }
            }

            if (other == null)
            {
                throw new MessageFormatterException("'other' option not found in pattern.");
            }

            return other.BlockText;
        }
Ejemplo n.º 36
0
        public ParsedMethod Parse(Method methodInfo, ParsedArguments parsedArguments)
        {
            var unMatchedRequiredArguments = parsedArguments.UnMatchedRequiredArguments();
            if (unMatchedRequiredArguments.Any())
            {
                throw new MissingArgumentException("Missing arguments")
                          {
                              Arguments = unMatchedRequiredArguments
                                .Select(unmatched => unmatched.Name).ToArray()
                          };
            }
            var convertArgument = new ConvertArgumentsToParameterValue(_configuration.CultureInfo, _configuration.TypeConverter);
            var recognizedActionParameters = convertArgument.GetParametersForMethod(methodInfo,
                parsedArguments.RecognizedArgumentsAsKeyValuePairs());

            return new ParsedMethod( parsedArguments, _typeContainer, _configuration)
                       {
                           RecognizedAction = methodInfo,
                           RecognizedActionParameters = recognizedActionParameters,
                           RecognizedClass = _controller.Type
                       };
        }
Ejemplo n.º 37
0
        public ParsedArguments ParseArgumentsAndMerge(string actionName, Dictionary<string, string> arg, ParsedArguments parsedArguments)
        {
            var methodInfo = _controller.GetMethod(actionName);
            var argumentRecognizers = methodInfo.GetArguments()
                .ToList();

            var parser = new ArgumentParser(argumentRecognizers, _allowInferParameter, Culture);
            var parsedMethodArguments = parser.Parse(arg);
            var parsedMethod = Parse(methodInfo, parsedMethodArguments);
            var merged = parsedArguments.Merge(parsedMethod);
            if (!_controller.IgnoreGlobalUnMatchedParameters)
                merged.AssertFailOnUnMatched();
            return merged;
        }