Parse() public method

public Parse ( ) : Boolean
return Boolean
示例#1
0
        public void Should_be_able_to_retrieve_args_by_position()
        {
            var args = new[]
            {
                "one",
                "two",
                "three"
            };

            var arguments = argParser.Parse(args);

            var one         = "";
            var two         = "";
            var three       = "";
            var threeFailed = false;

            arguments.At(0, a => one   = a.Value).FailWith(() => Assert.True(false, "should succeed"));
            arguments.At(1, a => two   = a.Value).FailWith(() => Assert.True(false, "should succeed"));
            arguments.At(2, a => three = a.Value).FailWith(() => Assert.True(false, "should succeed"));
            arguments.At(3, a => Assert.True(false, "Should not be an arg at 3")).FailWith(() => threeFailed = true);

            one.ShouldEqual(args[0]);
            two.ShouldEqual(args[1]);
            three.ShouldEqual(args[2]);
            threeFailed.ShouldBeTrue();
        }
示例#2
0
        public void CanParseParameterWithAbsolutePath()
        {
            var parameter = parser.Parse(new[] { "-path:c:\\temp\\someFile.txt" })
                            .Cast <NamedCommandLineParameter>().Single();

            Assert.AreEqual("path", parameter.Name);
            Assert.AreEqual("c:\\temp\\someFile.txt", parameter.Value);
        }
示例#3
0
        /// <summary>
        /// Carga la lista de email en la lista y prepara el envío
        /// </summary>
        private void LoadMails()
        {
            if (Properties.Settings.Default.MailList != null)
            {
                int i = 0;
                foreach (string mail in Properties.Settings.Default.MailList)
                {
                    ArgParser argumentos = new ArgParser();
                    Sender    sender     = new Sender();
                    if (argumentos.Parse(ref sender, mail.Substring(mail.IndexOf(';') >= 0 ? mail.IndexOf(';') : 0)) == 0)
                    {
                        ListViewItem itm = new ListViewItem();
                        itm.Text = (lst.Items.Count + 1).ToString();
                        itm.SubItems.Add(mail.Substring(0, 1) == "0"? "ENVIADO" : "BANDEJA SALIDA");
                        itm.SubItems.Add(sender.Attachment.Length > 0 ? "🔗" : "-");
                        itm.SubItems.Add(sender.To);
                        itm.SubItems.Add("N/A");
                        itm.Tag = sender;

                        sender.MessageID = i;
                        sender.Sent      = mail.Substring(0, 1) == "0" ? true : false;

                        lst.Items.Add(itm);

                        if (!sender.Sent)
                        {
                            state.AddMessage(sender);
                        }
                        i++;
                    }
                }
            }
        }
示例#4
0
        static void Main(string[] args)
        {
            Console.WriteLine("------------------------------------------------------------------------");
            Console.WriteLine("Utility to rename, set creation date or delete files");
            Console.WriteLine("------------------------------------------------------------------------");

            try
            {
                var(tasks, options) = ArgParser.Parse(args, new TaskValidator());
                if (tasks is null || options is null)
                {
                    PrintUsage();
                    return;
                }

                var processor = new TaskProcessor(options, new FileProcessorFactory());
                processor.Execute(tasks);
            }
            catch (Exception ex)
            {
                ConsoleLog.WriteError(ex.Message);
            }

            Console.WriteLine();
            Console.WriteLine("------------------------------------------------------------------------");
            Console.WriteLine(">> Done. Press ENTER to quit. ");
            Console.ReadLine();
        }
示例#5
0
        public override void SampleCall(string[] args)
        {
            #region Parse Arguments
            ArgParser cmdLineParser = new ArgParser();
            if (!cmdLineParser.Parse(args))
            {
                // Parse failed.
                PrintUsage(INVALID_ARGUMENTS_ERROR);
                return;
            }
            #endregion

            #region Initialize Properties
            ContextProperties contextProps = new ContextProperties();
            SessionProperties sessionProps = SampleUtils.NewSessionPropertiesFromConfig(cmdLineParser.Config);
            #endregion

            InitContext(cmdLineParser.LogLevel);

            using (Requestor requestor = new Requestor(contextProps, sessionProps))
                using (Responder responder = new Responder(contextProps, sessionProps))
                {
                    requestor.SendTo(responder.ReceivingOn);
                    requestor.Commit();

                    Log.Start("Waiting for message");
                    Log.AssertTrue(requestor.WaitForMessage(15000),
                                   "Timeout while waiting for message");
                }
        }
示例#6
0
        public void DeleteBySize_NoSourceDir()
        {
            string[] bySizeArgs = new string[] { "ds", "-z:5", "-r", "-f:*Rot*" };

            var(tasks, options) = ArgParser.Parse(bySizeArgs, new TaskValidator());
            Assert.AreEqual(1, tasks.Count);
            Assert.AreEqual(3, options.Count);
        }
示例#7
0
        public void DeleteBySize_Test()
        {
            string[] bySizeArgs = new string[] { "ds", @"-i:e:\@@@test", "-z:5", "-r", "-f:*Rot*" };

            var(tasks, options) = ArgParser.Parse(bySizeArgs, new TaskValidator());
            Assert.AreEqual(1, tasks.Count);
            Assert.AreEqual(4, options.Count);
        }
示例#8
0
        /// <summary>
        /// The DotBook entry point.
        /// </summary>
        /// <param name="args">Command line args</param>
        public static void Main(string[] args)
        {
            var p   = new ArgParser();
            var arg = new ApplicationArguments();

            p.UseOwnOptionPrefix("-", "--");
            p.Setup(v => arg.OutputDirectory = string.Join(" ", v))
            .As('o', "output")
            .SetDefault("docs")
            .WithDescription("Output directory for the generated documentation. " +
                             "If not specified, defaults to 'docs'.");

            p.Setup(v => arg.InputDirectory = string.Join(" ", v))
            .As('s', "src")
            .WithDescription("Directory for C# code search");

            p.Setup(v => arg.Visibility = v.ToEnum <Modifier>())
            .As('v', "visibility")
            .SetDefault("public")
            .WithDescription("Include types and members with the specified " +
                             "visibilities. Defaults to 'public'.");

            p.Setup(v => bool.Parse(v.FirstOrDefault() ?? "true"))
            .As('h', "use-hash")
            .SetDefault("false")
            .WithDescription("Use hashing for documentation filenames to " +
                             "allow deep hierarchies. " +
                             "If false, uses escaped type/member name. " +
                             "Defaults to 'false'.");

            p.Setup(v => arg.Format = v.ToEnum <FileFormat>().First())
            .As('f', "format")
            .SetDefault("Markdown")
            .WithDescription("Sets the output format. Default is Markdown. " +
                             "Available formats: Markdown, Html");

            p.SetupHelp("?", "help")
            .Callback(v =>
            {
                Console.WriteLine(string.Join("\n", p.GetHelp()));
                Environment.Exit(0);
            });

            p.Parse(args);

            try
            {
                Info("Using the following parameters:");
                Log($"{arg}");
                Run(arg);
            }
            catch (PathTooLongException pex)
            {
                Fatal("Hierarchy is too deep to use type/member names " +
                      "as filenames. Try using the --use-hash flag." +
                      $"{pex}");
            }
        }
示例#9
0
        public void ShouldValidateBasicParse()
        {
            var stu  = new ArgParser();
            var args = "-l -p 8080 -d /usr/logs".Split(" ");

            stu.Parse(args, new Schema());

            Assert.Equal(stu.FlagValue("l"), false.ToString());
        }
示例#10
0
        public void IndexIsOneBased()
        {
            var parameters = parser.Parse(new[] { "firstArg", "secondArg" })
                             .Cast <PositionalCommandLineParameter>().ToList();

            Assert.AreEqual(1, parameters[0].Index);
            Assert.AreEqual(2, parameters[1].Index);
        }
示例#11
0
 public void MultiplesNotAllowed()
 {
     int i1 = 0, i2 = 0;
     var ap = new ArgParser(
         new Int32Arg("-n", "<int> sets the integer")
     {
         Command = (n) => { i1 = n; i2 = n * n; }
     });
     var extras = ap.Parse(new string[] { "-n", "5", "-n", "6" });
 }
示例#12
0
        public void ExecuteTasks_Test()
        {
            string[] bySizeArgs = new string[] { "ds", @"-i:e:\@@@test", "-z:5", "-r", "-f:*Rot*", "-force" };

            var(tasks, options) = ArgParser.Parse(bySizeArgs, new TaskValidator());
            Assert.AreEqual(1, tasks.Count);
            Assert.AreEqual(4, options.Count);

            var factory   = new MockFileProcessorFactory();
            var processor = factory.Create(tasks, string.Empty, 0, false, true, true);

            processor.ApplyTasks();
        }
示例#13
0
        public void BasicIntArg()
        {
            int i1 = 0, i2 = 0;
            var ap = new ArgParser(
                new Int32Arg("-n", "<int> sets the integer")
            {
                Command = (n) => { i1 = n; i2 = n * n; }
            });
            var extras = ap.Parse(new string[] { "-n", "5" });

            Assert.IsTrue(extras.Count == 0);
            Assert.AreEqual(i1, 5);
            Assert.AreEqual(i2, 25);
        }
示例#14
0
 public void MustHaveRequired()
 {
     int i1 = 0, i2 = 0;
     var ap = new ArgParser(
         new Int32Arg("-n", "<int> sets the integer")
     {
         Command = (n) => { i1 = n; i2 = n * n; }
     },
         new StrArg("-f", "a required flag")
     {
         Required = true
     });
     var extras = ap.Parse(new string[] { "-n", "5" });
 }
示例#15
0
        public void MultiplesAllowed()
        {
            int sum = 0;
            var ap  = new ArgParser(
                new Int32Arg("-n", "<int> accumulates given numbers")
            {
                Command          = (n) => { sum += n; },
                Default          = 100, // make sure it's not applied
                MultiplesAllowed = true
            });
            var extras = ap.Parse(new string[] { "-n", "5", "-n", "6" });

            Assert.IsTrue(extras.Count == 0);
            Assert.AreEqual(sum, 11);
        }
        public void When_VoxelFlagIsGiven_Expect_VoxelSolution()
        {
            string inputStr  = Path.Combine("Input_Files", "input.txt");
            string outputStr = Path.Combine("Output_Files", "output.txt");

            // IO must be either "Input_Files" or "Output_Files".
            // Expected output for test files.
            // Paths contain "Nodegraph_Generator.Tests"
            string relativeInputPath  = Path.Combine(OSString, inputStr);
            string relativeOutputPath = Path.Combine(OSString, outputStr);

            string[]  inputArgs = { relativeInputPath, relativeOutputPath, "-v" };
            FilePaths result    = ArgParser.Parse(inputArgs);

            Assert.True(result.voxelSolution);
        }
示例#17
0
        public bool Parse(List <string> argv)
        {
            int i = ArgParser.Parse(argv, "-fix");

            if (i < 0)
            {
                return(false);
            }

            string     modelname = "";
            string     prefix    = "";
            string     package   = "";
            string     vertxt    = "";
            FixVersion ver       = FixVersion.UniversityReady;

            while (argv.Count > i)
            {
                if (ArgParser.Parse(argv, i, "-package", ref package))
                {
                    continue;
                }
                if (ArgParser.Parse(argv, i, "-modelname", ref modelname))
                {
                    continue;
                }
                if (ArgParser.Parse(argv, i, "-prefix", ref prefix))
                {
                    continue;
                }
                if (ArgParser.Parse(argv, i, "-fixversion", ref vertxt))
                {
                    switch (vertxt.Trim().ToLower())
                    {
                    case "uni1": ver = FixVersion.UniversityReady; break;

                    case "uni2": ver = FixVersion.UniversityReady2; break;
                    }
                    continue;
                }
                SimPe.Message.Show(Help()[0]);
                return(true);
            }

            Fix(package, prefix + modelname, ver);
            return(true);
        }
示例#18
0
        public void CatchExtras()
        {
            int sum = 0;
            var ap  = new ArgParser(
                new Int32Arg("-n", "<int> accumulates given numbers")
            {
                Command          = (n) => { sum += n; },
                Default          = 100,
                MultiplesAllowed = true
            });
            var extras = ap.Parse(new string[] { "-n", "5", "what", "-n", "6", "else" });

            Assert.IsTrue(extras.Count == 2);
            Assert.AreEqual(extras[0], "what");
            Assert.AreEqual(extras[1], "else");
            Assert.AreEqual(sum, 11);
        }
示例#19
0
        public bool Parse(List <string> argv)
        {
            int i = ArgParser.Parse(argv, "-build");

            if (i < 0)
            {
                return(false);
            }

            Splash.Screen.SetMessage("Building Package...");

            string output = "";
            string input  = "";

            while (argv.Count - i > 0 && input.Length == 0 && output.Length == 0)
            {
                if (ArgParser.Parse(argv, i, "-desc", ref input))
                {
                    continue;
                }
                if (ArgParser.Parse(argv, i, "-out", ref output))
                {
                    continue;
                }
                SimPe.Message.Show(Help()[0]);
                return(true);
            }

            if (input.Length == 0 || output.Length == 0)
            {
                SimPe.Message.Show(Help()[0]);
                return(true);
            }
            if (!System.IO.File.Exists(input))
            {
                SimPe.Message.Show(Help()[0]);
                return(true);
            }

            GeneratableFile pkg = GeneratableFile.LoadFromStream(XmlPackageReader.OpenExtractedPackage(null, input));

            pkg.Save(output);

            Splash.Screen.SetMessage("");
            return(true);
        }
示例#20
0
        static void Main(string[] args)
        {
            var parsed = ArgParser.Parse(args);
            var di = new DirectoryInfo(Path.GetDirectoryName(parsed.Input));
            var dlls = di.EnumerateFiles(Path.GetFileName(parsed.Input));
#if PARALLEL
            Parallel.ForEach(dlls, dll =>
#else
            foreach (var dll in dlls)
#endif
            {
                using (var input = File.OpenRead(dll.FullName))
                using (var output = File.OpenWrite(Path.Combine(parsed.Output, dll.Name)))
                {
                    AutoLogProcessor.AddLoggingToAssembly(input, output, dll.DirectoryName);
                }
            }
示例#21
0
        public virtual Tuple <int, int> GetTestTimesAndInterval(string[] args)
        {
            var parsedOK = false;

            Options = ArgParser.Parse <ArgClass>(args, out parsedOK);

            // Add wait checking here as this method is definitely called by all derived classes.
            if (parsedOK && Options.WaitSecondsForAttachDebug > 0)
            {
                var waitBegin  = DateTime.Now;
                var waitEnd    = waitBegin + TimeSpan.FromSeconds(Options.WaitSecondsForAttachDebug);
                var currentPID = Process.GetCurrentProcess().Id;
                Logger.LogWarn($"Will wait {Options.WaitSecondsForAttachDebug} seconds for you to debug this process : please attach PID {currentPID} before {waitEnd}");
                Thread.Sleep(Options.WaitSecondsForAttachDebug * 1000);
            }

            return(parsedOK ? new Tuple <int, int>(Options.TestTimes, Options.TestIntervalSeconds) : new Tuple <int, int>(-1, 0));
        }
示例#22
0
        public static void Main(string[] args)
        {
            // PrintSpecialFolders();
            var argParser = new ArgParser(args);

            if (argParser.Parse())
            {
                var year = argParser.Year;
                var user = argParser.User;

                var budget = CreateBudget(year, user);
                budget.Save();

                var month  = GetMonth();
                var report = DoMonthlyReport(month, year, user);
                report.Save();
            }
        }
        public void When_Correct_ArgumentsIsGiven_Expect_True()
        {
            string inputStr  = Path.Combine("Input_Files", "input.txt");
            string outputStr = Path.Combine("Output_Files", "output.txt");

            // IO must be either "Input_Files" or "Output_Files".
            // Expected output for test files.
            // Paths contain "Nodegraph_Generator.Tests"
            string relativeInputPath  = Path.Combine(OSString, inputStr);
            string relativeOutputPath = Path.Combine(OSString, outputStr);

            string[]  inputArgs = { relativeInputPath, relativeOutputPath };
            FilePaths result    = ArgParser.Parse(inputArgs);

            string expectedInputPath  = Path.Combine("SUM_Nodegraph_Generator", inputStr);
            string expectedOutputPath = Path.Combine("SUM_Nodegraph_Generator", outputStr);

            StringAssert.Contains(expectedInputPath, result.inFile);
            StringAssert.Contains(expectedOutputPath, result.outFile);
            // When no flag is given it should be voxelSoluton by default.
            Assert.True(result.voxelSolution);
        }
示例#24
0
        public static string MainString(string command)
        {
            // Helper that executes an input string command and returns results
            string[] args = command.Split();

            var parsed = ArgParser.Parse(args);

            if (parsed.ParsedOk == false)
            {
                Info.ShowLogo();
                Info.ShowUsage();
                return($"Error parsing arguments: {command}");
            }

            var commandName = args.Length != 0 ? args[0] : "";

            TextWriter realStdOut   = Console.Out;
            TextWriter realStdErr   = Console.Error;
            TextWriter stdOutWriter = new StringWriter();
            TextWriter stdErrWriter = new StringWriter();

            Console.SetOut(stdOutWriter);
            Console.SetError(stdErrWriter);

            MainExecute(commandName, parsed.Arguments);

            Console.Out.Flush();
            Console.Error.Flush();
            Console.SetOut(realStdOut);
            Console.SetError(realStdErr);

            string output = "";

            output += stdOutWriter.ToString();
            output += stdErrWriter.ToString();

            return(output);
        }
示例#25
0
        static void Main(string[] args)
        {
            Logger.Info(EnvironmentInfo);
            var parsedOK = false;
            var options  = ArgParser.Parse <ArgReadWriteKafka>(args, out parsedOK);

            if (!parsedOK)
            {
                return;
            }

            var brokers        = options.BrokerList.Split(";,".ToCharArray());
            var brokersUriList = new List <Uri>(brokers.Select(broker => new Uri(broker)));

            if (options.IsWrite)
            {
                WriteTestData(brokersUriList, options);
            }
            else
            {
                ReadData(brokersUriList, options);
            }
        }
示例#26
0
        public static void Main(string[] args)
        {
            // Parse the command line arguments - Show usage on failure
            var parsed = ArgParser.Parse(args);

            if (parsed.ParsedOk == false)
            {
                Info.ShowLogo();
                Info.ShowUsage();
                return;
            }

            var commandName = args.Length != 0 ? args[0] : "";

            if (parsed.Arguments.ContainsKey("/consoleoutfile"))
            {
                // Redirect output to a file specified
                FileExecute(commandName, parsed.Arguments);
            }
            else
            {
                MainExecute(commandName, parsed.Arguments);
            }
        }
示例#27
0
        /// <summary>
        /// Carga un mensaje a la lista desde la línea de comandos
        /// </summary>
        /// <param name="args">Argumentos de la línea de comandos</param>
        public void NuevoMensaje(string[] args)
        {
            if (args.Length > 0)
            {
                ArgParser argumentos = new ArgParser(args);
                Sender    sender     = new Sender();
                if (argumentos.Parse(ref sender) == 0)
                {
                    ListViewItem itm = new ListViewItem();
                    itm.Text = (lst.Items.Count + 1).ToString();
                    itm.SubItems.Add("BANDEJA SALIDA");
                    itm.SubItems.Add(sender.Attachment.Length > 0 ? "🔗" : "-");
                    itm.SubItems.Add(sender.To);
                    itm.SubItems.Add("N/A");


                    sender.MessageID = lst.Items.Count;
                    sender.Sent      = false;
                    GuardarMail(1, argumentos.RawCompose);

                    itm.Tag = sender;
                    lst.Items.Add(itm);

                    state.AddMessage(sender);
                }

                if (argumentos.State == 1 && state.Estado != 1)
                {
                    IniciarEnvio();
                }
                if (argumentos.State == 2 && state.Estado != 2)
                {
                    PausarEnvio();
                }
            }
        }
示例#28
0
        public static bool IsFunctionCall(string line, out FunctionCallInfo info)
        {
            //test (20);
            //teset(ToDeg(Sin(PI)));
            //Func(RandX(),Rand(20,50));
            //for (int i = 0; i < 20, i++)
            //if (True)
            //int x = Rand(0,100);
            info = null;
            string[] split = line.Split(new[] { '(' }, 2, StringSplitOptions.RemoveEmptyEntries);

            //test  20);
            //teset ToDeg(Sin(PI)));
            //Func RandX(),Rand(20,50));
            //for int i = 0; i < 20, i++)
            //if True)
            //int x = Rand 0,100);

            if (split.Length < 2)
            {
                return(false);
            }

            split[0] = split[0].TrimEnd();

            if (FunctionNames.Fuctions.Contains(split[0]) && !split[1].EndsWith(";"))
            {
                throw new ParsingException("Missing semicolon after a function call!", line);
            }

            split[1] = split[1].TrimEnd(';', ' ');

            //test 20)
            //teset ToDeg(Sin(PI)))
            //Func RandX(),Rand(20,50))
            //for int i = 0; i < 20, i++)
            //if True)
            //int x = Rand 0,100)

            split[1] = split[1].Remove(split[1].Length - 1, 1);

            //test 20
            //teset ToDeg(Sin(PI))
            //Func RandX(),Rand(20,50)
            //for int i = 0; i < 20, i++
            //if True
            //int x = Rand 0,100

            if (IsType(split[1].Split()[0], out _))
            {
                return(false);
            }

            if (split[0].TrimEnd() == "for" || split[0].TrimEnd() == "if")
            {
                return(false);
            }

            if (split[0].Contains("="))
            {
                return(false);
            }

            FunctionCallInfo i = new FunctionCallInfo();

            i.FunctionName = split[0].TrimEnd();

            i.Arguments = ArgParser.Parse(split[1].TrimEnd());

            info = i;
            return(true);
        }
示例#29
0
文件: Program.cs 项目: colombod/xunit
    int Execute(string[] args)
    {
        try
        {
            if (args.Any(HelpArgs.Contains))
            {
                PrintUsage();
                return(2);
            }

            string requestedTargetFramework;

            try
            {
                ParsedArgs = ArgParser.Parse(args);

                if (ParsedArgs.TryGetAndRemoveParameterWithoutValue("-x86"))
                {
                    Force32bit = true;
                }

                if (ParsedArgs.TryGetParameterWithoutValue("-internaldiagnostics"))
                {
                    InternalDiagnostics = true;
                }

                if (ParsedArgs.TryGetParameterWithoutValue("-nocolor"))
                {
                    NoColor = true;
                }

                // The extra versions are unadvertised compatibility flags to match 'dotnet' command line switches
                requestedTargetFramework = ParsedArgs.GetAndRemoveParameterWithValue("-framework")
                                           ?? ParsedArgs.GetAndRemoveParameterWithValue("--framework")
                                           ?? ParsedArgs.GetAndRemoveParameterWithValue("-f");
                Configuration = ParsedArgs.GetAndRemoveParameterWithValue("-configuration")
                                ?? ParsedArgs.GetAndRemoveParameterWithValue("--configuration")
                                ?? ParsedArgs.GetAndRemoveParameterWithValue("-c")
                                ?? "Debug";
                FxVersion = ParsedArgs.GetAndRemoveParameterWithValue("-fxversion")
                            ?? ParsedArgs.GetAndRemoveParameterWithValue("--fx-version");
                NoBuild = ParsedArgs.GetAndRemoveParameterWithoutValue("-nobuild") ||
                          ParsedArgs.GetAndRemoveParameterWithoutValue("--no-build");

                // Need to amend the paths for the report output, since we are always running
                // in the context of the bin folder, not the project folder
                var currentDirectory = Directory.GetCurrentDirectory();
                foreach (var key in OutputFileArgs)
                {
                    if (ParsedArgs.TryGetSingleValue(key, out var fileName))
                    {
                        ParsedArgs[key][0] = Path.GetFullPath(Path.Combine(currentDirectory, fileName));
                    }
                }
            }
            catch (ArgumentException ex)
            {
                WriteLineError(ex.Message);
                return(3);
            }

            var testProjects = Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*.*proj")
                               .Where(f => !f.EndsWith(".xproj"))
                               .ToList();

            if (testProjects.Count == 0)
            {
                WriteLineError("Could not find any project (*.*proj) file in the current directory.");
                return(3);
            }

            if (testProjects.Count > 1)
            {
                WriteLineError($"Multiple project files were found; only a single project file is supported. Found: {string.Join(", ", testProjects.Select(x => Path.GetFileName(x)))}");
                return(3);
            }

            ThisAssemblyPath = Path.GetDirectoryName(typeof(Program).GetTypeInfo().Assembly.Location);
            BuildStdProps    = $"\"/p:_Xunit_ImportTargetsFile={Path.Combine(ThisAssemblyPath, "import.targets")}\" " +
                               $"/p:Configuration={Configuration}";

            var returnValue = 0;
            var testProject = testProjects[0];

            var targetFrameworks = GetTargetFrameworks(testProject);
            if (targetFrameworks == null)
            {
                WriteLineError("Detection failed! Please ensure you're using 'xunit.core' v2.3 beta 2 or later.");
                return(3);
            }

            if (requestedTargetFramework != null)
            {
                if (!targetFrameworks.Contains(requestedTargetFramework, StringComparer.OrdinalIgnoreCase))
                {
                    WriteLineError($"Unknown target framework '{requestedTargetFramework}'; available frameworks: {string.Join(", ", targetFrameworks.Select(f => $"'{f}'"))}");
                    return(3);
                }

                returnValue = RunTargetFramework(testProject, requestedTargetFramework, amendOutputFileNames: false);
            }
            else
            {
                foreach (var targetFramework in targetFrameworks)
                {
                    returnValue = Math.Max(RunTargetFramework(testProject, targetFramework, amendOutputFileNames: targetFrameworks.Length > 1), returnValue);
                }
            }

            return(returnValue);
        }
        catch (Exception ex)
        {
            WriteLineError(ex.ToString());
            return(3);
        }
    }
示例#30
0
        private string[] MapObject(object o, CommandLineArgumentsDefinition effectiveDefinition)
        {
            List <string> newCommandLine = new List <string>();

            newCommandLine.AddRange(CmdLineArgs);

            var preParseResult = ArgParser.Parse(effectiveDefinition, newCommandLine.ToArray());

            var predictedAction = effectiveDefinition.FindMatchingAction(this.CmdLineArgs[0]);

            if (predictedAction == null)
            {
                PowerLogger.LogLine("Could not determine action: " + this.CmdLineArgs[0] + " - Here are the supported action:");
                foreach (var action in effectiveDefinition.Actions)
                {
                    PowerLogger.LogLine("  " + action.DefaultAlias);
                }
                throw new ArgException("TODO - Could not determine action: " + this.CmdLineArgs[0]);
            }

            PowerLogger.LogLine("Predicted action is " + predictedAction.DefaultAlias);


            var argsToInspectForDirectMappingTarget = predictedAction.Arguments.Union(effectiveDefinition.Arguments).ToList();
            var directMappingTarget = (from argument in argsToInspectForDirectMappingTarget
                                       where argument.Metadata.HasMeta <ArgPipelineTarget>()
                                       select argument).SingleOrDefault();

            if (directMappingTarget != null)
            {
                var revivedValue = o;
                if (IsCompatible(o, directMappingTarget) == false)
                {
                    PowerLogger.LogLine("Need to map " + o.GetType().FullName + " to " + directMappingTarget.ArgumentType.FullName);

                    if (TrySimpleConvert(o, directMappingTarget.ArgumentType, out revivedValue))
                    {
                        // we're good
                    }
                    else if (ArgPipelineObjectMapper.CurrentMapper == null)
                    {
                        throw new InvalidArgDefinitionException("Unable to attempt tp map type " + o.GetType().FullName + " to " + directMappingTarget.ArgumentType.FullName + " because no mapper is registered at ArgPipelineObjectMapperProvider.CurrentMapper");
                    }
                    else
                    {
                        revivedValue = ArgPipelineObjectMapper.CurrentMapper.MapIncompatibleDirectTargets(directMappingTarget.ArgumentType, o);
                    }
                }

                effectiveDefinition.Metadata.Add(new ArgumentOverrideHook(directMappingTarget, revivedValue));
            }
            else
            {
                PowerLogger.LogLine("Attempting to shred object: " + o.ToString());
                foreach (var argument in predictedAction.Arguments.Union(effectiveDefinition.Arguments))
                {
                    bool manualOverride = false;

                    foreach (var explicitKey in preParseResult.ExplicitParameters.Keys)
                    {
                        if (argument.IsMatch(explicitKey))
                        {
                            manualOverride = true;
                            break;
                        }
                    }

                    if (preParseResult.ImplicitParameters.ContainsKey(argument.Position))
                    {
                        manualOverride = true;
                    }

                    if (manualOverride)
                    {
                        continue;
                    }

                    var    mapper = argument.Metadata.Meta <ArgPipelineExtractor>() ?? new ArgPipelineExtractor();
                    string mappedKey, mappedValue;
                    if (mapper.TryExtractObjectPropertyIntoCommandLineArgument(o, argument, out mappedKey, out mappedValue))
                    {
                        newCommandLine.Add(mappedKey);
                        newCommandLine.Add(mappedValue);
                    }
                }
            }

            return(newCommandLine.ToArray());
        }