Exemplo n.º 1
0
        public void ArgumentsSpaceSeperator()
        {
            string[] args =
            {
                "/name1 value1",
                "/name2 'value 2'",
                "value3",
                "'value 4'"
            };

            string[] names      = { "/" };
            char[]   seperators = { ' ' };
            var      parsedArgs = new ConsoleArguments(args, names, seperators);

            Assert.False(parsedArgs[""].HasValue(), "Unnamed argument has no value");

            Assert.True(parsedArgs.Get("name1").HasValue());
            Assert.True(parsedArgs["name1"].HasValue());
            Assert.False(parsedArgs["name1"].IsArray());
            Assert.AreEqual(parsedArgs["name1"], "value1");

            Assert.True(parsedArgs.Get("name2").HasValue());
            Assert.True(parsedArgs["name2"].HasValue());
            Assert.True(parsedArgs["name2"].IsArray());
            Assert.AreEqual(parsedArgs["name2"], "value 2");

            Assert.AreEqual(parsedArgs.Default.GetItem(0), "value2");
            Assert.AreEqual(parsedArgs.Default.GetItem(1), "value 3");
            Assert.AreEqual(parsedArgs.Default.GetItem(2), "value4");
            Assert.False(parsedArgs.Default.GetItem(3).HasValue());

            Assert.False(parsedArgs.Get("name3").HasValue());
            Assert.False(parsedArgs["name3"].HasValue());
            Assert.False(parsedArgs["name3"].IsArray());
        }
    static public void MainProtected(string[] args)
    {
        ConsoleArguments commandLineArgs = new ConsoleArguments(args);

        // Usage: cpp_master.exe <control-file> <solution-path>

        string controlFileName = commandLineArgs.ControlFile;

        if (controlFileName.Length == 0)
        {
            Console.WriteLine("CPPMaster: No control file specified");
            return;
        }

        string solutionPath = commandLineArgs.SolutionPath;

        if (solutionPath.Length == 0)
        {
            Console.WriteLine("CPPMaster: No solution specified");
            return;
        }

        CPPMasterContext context = new CPPMasterContext(commandLineArgs);

        context.Generate();
    }
Exemplo n.º 3
0
        public void Parse_ForInvalidCommand_DoesNotParse()
        {
            // Setup
            var console = Substitute.For <IConsoleWrapper>();
            var parser  = new ConsoleArguments(console);

            string[] args =
            {
                "wrong",
                "-solution-path",
                "folder1\\projFile",
                "-data-file",
                "reports\\master.xml",
                "-report",
                "reports\\scanReport.html"
            };

            // Act
            var result = parser.Parse(args);

            // Assert
            Assert.That(result, Is.EqualTo(false));
            Assert.That(parser.CreateDataFile, Is.EqualTo(false));
            Assert.That(parser.SolutionPath, Is.EqualTo(null));
            Assert.That(parser.DataFilePath, Is.EqualTo(null));
            Assert.That(parser.ReportPath, Is.EqualTo(null));

            console.Received(1).WriteLine(Arg.Is <string>(
                                              x => x.Contains(ConsoleOutput.ArgumentInstruction)));

            console.Received(1).WriteLine(Arg.Is <string>(
                                              x => x.Contains(ConsoleOutput.HelpInstruction)));
        }
Exemplo n.º 4
0
        public void Parse_CompareMissingAll_DoesNotParse()
        {
            // Setup
            var console = Substitute.For <IConsoleWrapper>();
            var parser  = new ConsoleArguments(console);

            string[] args =
            {
                "compare"
            };

            // Act
            var result = parser.Parse(args);

            // Assert
            Assert.That(result, Is.EqualTo(false));
            Assert.That(parser.CreateDataFile, Is.EqualTo(false));
            Assert.That(parser.SolutionPath, Is.EqualTo(null));
            Assert.That(parser.DataFilePath, Is.EqualTo(null));
            Assert.That(parser.ReportPath, Is.EqualTo(null));

            console.Received(1).WriteLine(Arg.Is <string>(
                                              x => x.Contains(ConsoleOutput.SolutionPathError)));

            console.Received(1).WriteLine(Arg.Is <string>(
                                              x => x.Contains(ConsoleOutput.DataFileError)));

            console.Received(1).WriteLine(Arg.Is <string>(
                                              x => x.Contains(ConsoleOutput.ReportError)));
        }
Exemplo n.º 5
0
        public void Parse_CompareWithAlternateExtensions_ParsesArguments()
        {
            // Setup
            var parser = new ConsoleArguments();

            string[] args =
            {
                "Compare",
                "-solution-path",
                "folder1\\projFile",
                "-data-file",
                "reports\\master.txt",
                "-report",
                "reports\\scanReport.txt"
            };

            // Act
            var result = parser.Parse(args);

            // Assert
            Assert.That(result, Is.EqualTo(true));
            Assert.That(parser.CreateDataFile, Is.EqualTo(false));
            Assert.That(parser.SolutionPath, Is.EqualTo("folder1\\projFile"));
            Assert.That(parser.DataFilePath, Is.EqualTo("reports\\master.txt"));
            Assert.That(parser.ReportPath, Is.EqualTo("reports\\scanReport.txt"));
        }
Exemplo n.º 6
0
        public void Parse_ForValidCompareWithDifferingCase_ParsesArguments()
        {
            // Setup
            var parser = new ConsoleArguments();

            string[] args =
            {
                "compare",
                "-Solution-path",
                "folder1\\projFile",
                "-Data-File",
                "reports\\master.xml",
                "-Report",
                "reports\\scanReport.html"
            };

            // Act
            var result = parser.Parse(args);

            // Assert
            Assert.That(result, Is.EqualTo(true));
            Assert.That(parser.CreateDataFile, Is.EqualTo(false));
            Assert.That(parser.SolutionPath, Is.EqualTo("folder1\\projFile"));
            Assert.That(parser.DataFilePath, Is.EqualTo("reports\\master.xml"));
            Assert.That(parser.ReportPath, Is.EqualTo("reports\\scanReport.html"));
        }
Exemplo n.º 7
0
        public void ArgumentsSingleUnamed()
        {
            string[] args =
            {
                "value1"
            };

            string[] names      = { "/" };
            char[]   seperators = { ':' };
            var      parsedArgs = new ConsoleArguments(args, names, seperators);

            Assert.True(parsedArgs.Get("").HasValue(), "Unnamed argument has value");
            Assert.True(parsedArgs.Get("").Exists, "Unnamed argument exists");
            Assert.AreEqual(parsedArgs.Get("").Value, "value1", "Unnamed argument has value");
            Assert.False(parsedArgs.Default.IsArray(), "Unnamed argument flagged as array");

            Assert.True(parsedArgs[""].HasValue(), "Unnamed argument has value");
            Assert.True(parsedArgs[""].Exists, "Unnamed argument exists");
            Assert.AreEqual(parsedArgs[""].Value, "value1", "Unnamed argument has value");
            Assert.False(parsedArgs.Default.IsArray(), "Unnamed argument flagged as array");

            Assert.True(parsedArgs.Default.HasValue(), "Unnamed argument has value, using .Default");
            Assert.True(parsedArgs.Default.Exists, "Unnamed argument exists");
            Assert.AreEqual(parsedArgs.Default.Value, "value1", "Unnamed argument has value");
            Assert.False(parsedArgs.Default.IsArray(), "Unnamed argument flagged as array");
        }
		public void Parsing_Expected_Arguments()
		{
			var args = new ConsoleArguments("mode1", "mode2");
			args.Parse(null);
			args.Names.Should().BeEmpty();
			args.GetValue("Mode 1").Should().BeNull();
			args.GetValue("Mode 2").Should().BeNull();

			args = new ConsoleArguments("mode1", "mode2");
			args.Parse(new[] { "value1" });
			args.Names.Should().BeEquivalentTo("mode1");
			args.GetValue("Mode 1").Should().Be("value1");
			args.GetValue("Mode 2").Should().BeNull();

			args.Parse(new[] { "value1", "value2" });
			args.Names.Should().BeEquivalentTo("mode1", "mode2");
			args.GetValue("Mode 1").Should().Be("value1");
			args.GetValue("Mode 2").Should().Be("value2");

			args.Invoking(a => a.Parse(new[] { "value1", "value2", "value3" }))
				.ShouldThrow<ArgumentException>()
				.WithMessage("Cannot parse property name from specified value 'value3'.");

			args.Invoking(a => a.Parse(new[] { "value1", "-flag1", "value2" }))
				.ShouldThrow<ArgumentException>()
				.WithMessage("Cannot parse property name from specified value 'value2'.");

			args.Parse(new[] { "value1", "/item1:x", "-flag1" });
			args.Names.Should().BeEquivalentTo("mode1", "item1", "flag1");
			args.GetValue("Mode 1").Should().Be("value1");
			args.GetValue("Mode 2").Should().BeNull();
			args.GetValue("Item 1").Should().Be("x");
			args.GetValue("Flag 1").Should().Be("True");
		}
Exemplo n.º 9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HostOptions"/> class.
 /// </summary>
 /// <param name="consoleArguments">console arguments</param>
 /// <param name="containerOptions">container options</param>
 /// <param name="requestShutdown">injected request shutdown service</param>
 /// <param name="monitorShutdown">injected monitor shutdown service</param>
 public HostOptions(ConsoleArguments consoleArguments, IContainerOptions containerOptions, IRequestShutdown requestShutdown, IMonitorShutdown monitorShutdown)
 {
     this.RequestShutdown  = requestShutdown;
     this.MonitorShutdown  = monitorShutdown;
     this.ConsoleArguments = consoleArguments;
     this.ContainerOptions = containerOptions;
 }
Exemplo n.º 10
0
        public void ArgumentsMultipleNames()
        {
            string[] args =
            {
                "/name1:value1",
                "-name2:value2",
                "?name3:value3"
            };

            string[] names      = { "/", "-" };
            char[]   seperators = { ':' };
            var      parsedArgs = new ConsoleArguments(args, names, seperators);

            Assert.False(parsedArgs[""].HasValue(), "Unnamed argument has no value");

            Assert.True(parsedArgs.Get("name1").HasValue());
            Assert.True(parsedArgs["name1"].HasValue());
            Assert.False(parsedArgs["name1"].IsArray());

            Assert.True(parsedArgs.Get("name2").HasValue());
            Assert.True(parsedArgs["name2"].HasValue());
            Assert.True(parsedArgs["name2"].IsArray(), "Valid name followed by an invalid one makes an array");

            Assert.False(parsedArgs.Get("name3").HasValue());
            Assert.False(parsedArgs["name3"].HasValue());
            Assert.False(parsedArgs["name3"].IsArray());
        }
Exemplo n.º 11
0
            /// <summary>
            /// Runs the program, analogous to System.Windows.Forms.Application.Run.
            /// </summary>
            public void Run()
            {
                //Check that we've got an action corresponding to one the user requested.
                if (!Handlers.ContainsKey(Arguments.Action))
                {
                    throw new ArgumentException(S._("Unknown action {0}", Arguments.Action));
                }

                //Re-parse the command line arguments as arguments for the given action.
                ConsoleActionData data      = Handlers[Arguments.Action];
                ConsoleArguments  arguments = data.Arguments;

                ComLib.BoolMessageItem <Args> parseResult = Args.Parse(CommandLine,
                                                                       CommandLinePrefixes, CommandLineSeparators, arguments);
                if (!parseResult.Success)
                {
                    throw new ArgumentException(parseResult.Message);
                }

                //Remove the action from the positional arguments before sending it to the handler
                System.Diagnostics.Debug.Assert(Arguments.Action == parseResult.Item.Positional[0]);
                parseResult.Item.Positional.RemoveAt(0);
                arguments.PositionalArguments = parseResult.Item.Positional;

                //Then invoke the handler for this action.
                data.Handler(arguments);
            }
        public void Parsing_Expected_Arguments()
        {
            var args = new ConsoleArguments("mode1", "mode2");

            args.Parse(null);
            args.Names.Should().BeEmpty();
            args.GetValue("Mode 1").Should().BeNull();
            args.GetValue("Mode 2").Should().BeNull();

            args = new ConsoleArguments("mode1", "mode2");
            args.Parse(new[] { "value1" });
            args.Names.Should().BeEquivalentTo("mode1");
            args.GetValue("Mode 1").Should().Be("value1");
            args.GetValue("Mode 2").Should().BeNull();

            args.Parse(new[] { "value1", "value2" });
            args.Names.Should().BeEquivalentTo("mode1", "mode2");
            args.GetValue("Mode 1").Should().Be("value1");
            args.GetValue("Mode 2").Should().Be("value2");

            args.Invoking(a => a.Parse(new[] { "value1", "value2", "value3" }))
            .ShouldThrow <ArgumentException>()
            .WithMessage("Cannot parse property name from specified value 'value3'.");

            args.Invoking(a => a.Parse(new[] { "value1", "-flag1", "value2" }))
            .ShouldThrow <ArgumentException>()
            .WithMessage("Cannot parse property name from specified value 'value2'.");

            args.Parse(new[] { "value1", "/item1:x", "-flag1" });
            args.Names.Should().BeEquivalentTo("mode1", "item1", "flag1");
            args.GetValue("Mode 1").Should().Be("value1");
            args.GetValue("Mode 2").Should().BeNull();
            args.GetValue("Item 1").Should().Be("x");
            args.GetValue("Flag 1").Should().Be("True");
        }
        public void Input_Arguments_Can_Be_Null()
        {
            var args = new ConsoleArguments();

            args.Parse(null);
            args.Names.Should().BeEmpty();
        }
Exemplo n.º 14
0
        public void ArgumentsMultipleSeperators()
        {
            string[] args =
            {
                "/name1 value1",
                "/name2:value2",
                "/name3;value3"
            };

            string[] names      = { "/" };
            char[]   seperators = { ':', ' ' };
            var      parsedArgs = new ConsoleArguments(args, names, seperators);

            Assert.False(parsedArgs[""].HasValue(), "Unnamed argument has no value");

            Assert.True(parsedArgs.Get("name1").HasValue());
            Assert.True(parsedArgs["name1"].HasValue());
            Assert.False(parsedArgs["name1"].IsArray());

            Assert.True(parsedArgs.Get("name2").HasValue());
            Assert.True(parsedArgs["name2"].HasValue());
            Assert.False(parsedArgs["name2"].IsArray());

            Assert.False(parsedArgs.Get("name3").HasValue());
            Assert.False(parsedArgs["name3"].HasValue());
            Assert.False(parsedArgs["name3"].IsArray());
        }
Exemplo n.º 15
0
        public void ArgumentsMultipleUnamed()
        {
            string[] args =
            {
                "value1",
                "value2",
                "value3"
            };

            string[] names      = { "/" };
            char[]   seperators = { ':' };
            var      parsedArgs = new ConsoleArguments(args, names, seperators);

            Assert.True(parsedArgs.Get("").HasValue(), "Unnamed argument has value");
            Assert.True(parsedArgs.Get("").Exists, "Unnamed argument exists");
            Assert.AreEqual(parsedArgs.Get("").Value, "value1", "Unnamed argument has value");
            Assert.True(parsedArgs.Default.IsArray(), "Unnamed argument flagged as array");

            Assert.True(parsedArgs[""].HasValue(), "Unnamed argument has value");
            Assert.True(parsedArgs[""].Exists, "Unnamed argument exists");
            Assert.AreEqual(parsedArgs[""].Value, "value1", "Unnamed argument has value");
            Assert.True(parsedArgs.Default.IsArray(), "Unnamed argument flagged as array");

            Assert.True(parsedArgs.Default.HasValue(), "Unnamed argument has value, using .Default");
            Assert.True(parsedArgs.Default.Exists, "Unnamed argument exists");
            Assert.AreEqual(parsedArgs.Default.Value, "value1", "Unnamed argument has value");
            Assert.True(parsedArgs.Default.IsArray(), "Unnamed argument flagged as array");

            Assert.AreEqual(parsedArgs.Default.GetItem(0).Value, "value1", "Unnamed argument (1) accessed with indexer.value has value");
            Assert.AreEqual(parsedArgs.Default.GetItem(1).Value, "value2", "Unnamed argument (2) accessed with indexer.value has value");
            Assert.AreEqual(parsedArgs.Default.GetItem(2).Value, "value3", "Unnamed argument (3) accessed with indexer.value has value");
            Assert.False(parsedArgs.Default.GetItem(3).HasValue());
        }
        public void ConsoleArgumentsTestsCaseSensitive()
        {
            const string param0 = "test";
            const string param1 = "/verbose:on";
            const string param2 = "/recursive=yes";
            const string param3 = "value1";
            const string param4 = "/value2";

            var consoleArgs = new ConsoleArguments(new[] { param0, param1, param2, param3, param4 }, true);

            Assert.Equal("on", consoleArgs["verbose"]);
            Assert.Empty(consoleArgs["Verbose"]);
            Assert.Equal("yes", consoleArgs["recursive"]);
            Assert.Empty(consoleArgs["Recursive"]);
            Assert.Equal(2, consoleArgs.Params.Count());
            Assert.Equal(3, consoleArgs.Values.Count());

            var param0Found = consoleArgs.Params.Contains(param0);
            var param3Found = consoleArgs.Params.Contains(param3);

            Assert.True(param0Found, "param0 not found");
            Assert.True(param3Found, "param3 not found");

            Assert.True(consoleArgs.IsSet(param0));
            Assert.False(consoleArgs.IsSet("test1"));
        }
Exemplo n.º 17
0
        // The Default Functions is invoked if no command is passed to the executable.
        // Like all other functions that are fired by the Commandmanager, it needs to
        // return an integer (0 = success, any other number equals failure), and accepts
        // the ConsoleArguments object as a parameter
        private static int DefaultCommand(ConsoleArguments args)
        {
            string name = args["n"];

            ConsoleLogger.PrintLine(string.Format("Hello {0}", name));
            return(0);
        }
 public void ConsoleArgumentsTestsCtor()
 {
     Assert.Throws <ArgumentNullException>(() => new ConsoleArguments(null, false));
     var consoleArgs0 = new ConsoleArguments(new[] { "test" }, false);
     var consoleArgs1 = new ConsoleArguments(new[] { "test" }, true);
     var consoleArgs2 = new ConsoleArguments(Array.Empty <string>(), false);
     var consoleArgs3 = new ConsoleArguments(Array.Empty <string>(), true);
 }
Exemplo n.º 19
0
        public void ConsoleArguments_ToString1()
        {
            var o = new ConsoleArguments(new List <string> {
                "test"
            });

            Assert.AreEqual("[test]", o.ToString());
        }
Exemplo n.º 20
0
        public void NullArguments_Should_ParseCorrectly()
        {
            // Arrange & Act
            var param = new ConsoleArguments(null);

            // Assert
            Assert.Empty(param);
        }
        public void Input_Arguments_Cannot_Contain_Null_Items()
        {
            var args = new ConsoleArguments();

            args.Invoking(a => a.Parse(new[] { "item", null }))
            .ShouldThrow <ArgumentException>()
            .WithMessage("Input arguments should not contain null elements.");
        }
Exemplo n.º 22
0
        public void ConsoleArguments_ToString2()
        {
            var o = new ConsoleArguments(new List <string> {
                string.Empty, "first", "second"
            });

            Assert.AreEqual("[first second]", o.ToString());
        }
Exemplo n.º 23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LambdaHostOptions"/> class.
        /// </summary>
        /// <param name="commandLineOptions">command line Options</param>
        /// <param name="consoleArguments">console arguments</param>
        /// <param name="requestShutdown">injected request shutdown service</param>
        /// <param name="monitorShutdown">injected monitor shutdown service</param>
        public LambdaHostOptions(LambdaCommandLineOptions commandLineOptions, ConsoleArguments consoleArguments, IRequestShutdown requestShutdown, IMonitorShutdown monitorShutdown)
            : base(commandLineOptions, consoleArguments, requestShutdown, monitorShutdown)
        {
            commandLineOptions = Arguments.EnsureNotNull(commandLineOptions, nameof(commandLineOptions));

            this.SpoolAws     = commandLineOptions.SpoolAws;
            this.RunAsConsole = commandLineOptions.RunAsConsole;
        }
Exemplo n.º 24
0
        /// <summary>
        /// Parses the command line for tasks and adds them using the
        /// <see cref="RemoteExecutor"/> class.
        /// </summary>
        /// <param name="arg">The command line parameters passed to the program.</param>
        private static void CommandAddTask(ConsoleArguments arg)
        {
            TaskArguments arguments = (TaskArguments)arg;
            Task          task      = TaskFromCommandLine(arguments);

            //Send the task out.
            using (eraserClient = CommandConnect())
                eraserClient.Tasks.Add(task);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Prints the help text for Eraser (with copyright)
        /// </summary>
        /// <param name="arguments">Not used.</param>
        private static void CommandHelp(ConsoleArguments arguments)
        {
            Console.WriteLine(S._(@"Eraser {0}
(c) 2008-2015 The Eraser Project
Eraser is Open-Source Software: see http://eraser.heidi.ie/ for details.
", BuildInfo.AssemblyFileVersion));

            PrintCommandHelp();
        }
        public void Expected_Arguments_Can_Be_Null()
        {
            var args = new ConsoleArguments();

            args.Names.Should().BeEmpty();

            args = new ConsoleArguments(null);
            args.Names.Should().BeEmpty();
        }
Exemplo n.º 27
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            App.Setup("sirGustav", "Builder 0.1", "builder");
            ConsoleArguments args = new ConsoleArguments();

            Application.Run(new MainWindow());
        }
Exemplo n.º 28
0
        /// <summary>
        /// Parses the command line for tasks and adds them to run immediately
        /// using the <see cref="RemoveExecutor"/> class.
        /// </summary>
        /// <param name="arg">The command line parameters passed to the program.</param>
        private static void CommandErase(ConsoleArguments arg)
        {
            TaskArguments arguments = new TaskArguments((EraseArguments)arg)
            {
                Schedule = "NOW"
            };

            CommandAddTask(arguments);
        }
Exemplo n.º 29
0
 public ConsoleProgram(string[] commandLine)
 {
     CommandLine = commandLine;
     Handlers = new Dictionary<string, ConsoleActionData>();
     Arguments = new ConsoleArguments();
     Args.Parse(commandLine, CommandLinePrefixes, CommandLineSeparators, Arguments);
     if (!Arguments.Quiet)
      ConsoleWindow = new ConsoleWindow();
 }
Exemplo n.º 30
0
        public void ConsoleArguments_Create()
        {
            var o = new ConsoleArguments(new List <string> {
                "test"
            });
            var a = o.Arguments;

            Assert.IsNotNull(a);
        }
        public void Invalid_Parsing_Examples()
        {
            var args = new ConsoleArguments();

            args.Parse(new[] { "/a:b" });
            args.GetValue("a").Should().Be("b");

            args.Invoking(a => a.Parse(new[] { " /a:b" }))
            .ShouldThrow <ArgumentException>()
            .WithMessage("Cannot parse property name from specified value ' /a:b'.");

            args.Invoking(a => a.Parse(new[] { "a:b" }))
            .ShouldThrow <ArgumentException>()
            .WithMessage("Cannot parse property name from specified value 'a:b'.");

            args.Invoking(a => a.Parse(new[] { "/:b" }))
            .ShouldThrow <ArgumentException>()
            .WithMessage("Specified value '' cannot be used as property name.");

            args.Invoking(a => a.Parse(new[] { "/:" }))
            .ShouldThrow <ArgumentException>()
            .WithMessage("Specified value '' cannot be used as property name.");

            args.Invoking(a => a.Parse(new[] { "/ :" }))
            .ShouldThrow <ArgumentException>()
            .WithMessage("Specified value ' ' cannot be used as property name.");

            args.Invoking(a => a.Parse(new[] { "/::" }))
            .ShouldThrow <ArgumentException>()
            .WithMessage("Specified value '' cannot be used as property name.");

            args.Parse(new[] { "/a:" });
            args.GetValue("a").Should().Be(String.Empty);

            args.Parse(new[] { "//:b" });
            args.GetValue("/").Should().Be("b");

            args.Parse(new[] { "//::" });
            args.GetValue("/").Should().Be(":");

            args = new ConsoleArguments();
            args.Parse(new[] { "-a:b" });
            args.GetValue("a:b").Should().Be("True");

            args.Invoking(a => a.Parse(new[] { " -a" }))
            .ShouldThrow <ArgumentException>()
            .WithMessage("Cannot parse property name from specified value ' -a'.");

            args.Invoking(a => a.Parse(new[] { "-" }))
            .ShouldThrow <ArgumentException>()
            .WithMessage("Specified value '' cannot be used as property name.");

            args.Invoking(a => a.Parse(new[] { "- " }))
            .ShouldThrow <ArgumentException>()
            .WithMessage("Specified value ' ' cannot be used as property name.");
        }
Exemplo n.º 32
0
 /// <summary>
 /// Imports the given tasklists and adds them to the global Eraser instance.
 /// </summary>
 /// <param name="args">The list of files specified on the command line.</param>
 private static void CommandImportTaskList(ConsoleArguments args)
 {
     //Import the task list
     using (eraserClient = CommandConnect())
         foreach (string path in args.PositionalArguments)
         {
             using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
                 eraserClient.Tasks.LoadFromStream(stream);
         }
 }
		public void Parsing_Properties_And_Flags()
		{
			var args = new ConsoleArguments();
			args.Parse(new[]
			{
				"/item1:value1",
				"-flag1",
				"/item 2:value2",
				"-flag 2",
				"/ ITEM 3 :value3",
				"- FLAG 3"
			});

			args.Names.Should().BeEquivalentTo("item1", "flag1", "item2", "flag2", "ITEM3", "FLAG3");
			args.GetValue("Item 1").Should().Be("value1");
			args.GetValue("Item 2").Should().Be("value2");
			args.GetValue("Item 3").Should().Be("value3");
			args.GetValue("Item 4").Should().BeNull();
			args.GetValue("Flag 1").Should().Be("True");
			args.GetValue("Flag 2").Should().Be("True");
			args.GetValue("Flag 3").Should().Be("True");
			args.GetValue("Flag 4").Should().BeNull();

			args.Parse(new[]
			{
				"/myname:Oleg",
				"/myAge:33",
				"- DEBUG"
			});

			args.Get<string>("MyName").Should().Be("Oleg");
			args.IsNull("MyName").Should().BeFalse();
			args.Get<int>("MyAge").Should().Be(33);
			args.IsNull("MyAge").Should().BeFalse();
			args.Get("MyTimeout", TimeSpan.Zero).Should().Be(TimeSpan.Zero);
			args.IsNull("MyTimeout").Should().BeTrue();
			args.Get<bool>("Debug").Should().BeTrue();
			args.IsNull("Debug").Should().BeFalse();
			args.Get("Release", false).Should().BeFalse();
			args.IsNull("Release").Should().BeTrue();
		}
Exemplo n.º 34
0
        public void Start(string[] args)
        {
            _arguments = new ConsoleArguments(args);

            if (_arguments["config"] != null)
            {
                _configController.Load(_arguments["config"]);
                _buildController = _builderFactory();

                _buildMessenger.OnBuildMessage += System.Console.WriteLine;

                _buildController.StartBuild(_configController.GetConfigSection<SharpDoxConfig>(), false);
            }
            else
            {
                System.Console.WriteLine(_strings.ConfigMissing + " -config " + _strings.Path);
            }

            System.Console.WriteLine(_strings.PressToEnd);
            System.Console.ReadLine();
        }
		public void Input_Arguments_Can_Be_Null()
		{
			var args = new ConsoleArguments();
			args.Parse(null);
			args.Names.Should().BeEmpty();
		}
		public void Input_Arguments_Cannot_Contain_Null_Items()
		{
			var args = new ConsoleArguments();
			args.Invoking(a => a.Parse(new[] { "item", null }))
				.ShouldThrow<ArgumentException>()
				.WithMessage("Input arguments should not contain null elements.");
		}
Exemplo n.º 37
0
        private static void CommandAddTask(ConsoleArguments arg)
        {
            AddTaskArguments arguments = (AddTaskArguments)arg;

               Task task = new Task();
               ErasureMethod method = arguments.ErasureMethod == Guid.Empty ?
            ErasureMethodManager.Default :
            ErasureMethodManager.GetInstance(arguments.ErasureMethod);
               switch (arguments.Schedule.ToUpperInvariant())
               {
            case "NOW":
             task.Schedule = Schedule.RunNow;
             break;
            case "MANUALLY":
             task.Schedule = Schedule.RunManually;
             break;
            case "RESTART":
             task.Schedule = Schedule.RunOnRestart;
             break;
            default:
             throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
              "Unknown schedule type: {0}", arguments.Schedule), "--schedule");
               }

               List<string> trueValues = new List<string>(new string[] { "yes", "true" });
               string[] strings = new string[] {

            "(?<recycleBin>recyclebin)",

            "unused=(?<unusedVolume>.*)(?<unusedTips>,clusterTips(=(?<unusedTipsValue>true|false))?)?",

            "dir=(?<directoryName>.*)(?<directoryParams>(?<directoryExcludeMask>,-[^,]+)|(?<directoryIncludeMask>,\\+[^,]+)|(?<directoryDeleteIfEmpty>,deleteIfEmpty(=(?<directoryDeleteIfEmptyValue>true|false))?))*",

            "file=(?<fileName>.*)"
               };

               Regex regex = new Regex(string.Join("|", strings),
            RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.RightToLeft);
               foreach (string argument in arguments.PositionalArguments)
               {
            Match match = regex.Match(argument);
            if (match.Captures.Count == 0)
            {
             Console.WriteLine("Unknown argument: {0}, skipped.", argument);
             continue;
            }

            ErasureTarget target = null;
            if (match.Groups["recycleBin"].Success)
            {
             target = new RecycleBinTarget();
            }
            else if (match.Groups["unusedVolume"].Success)
            {
             UnusedSpaceTarget unusedSpaceTarget = new UnusedSpaceTarget();
             target = unusedSpaceTarget;
             unusedSpaceTarget.Drive = match.Groups["unusedVolume"].Value;

             if (!match.Groups["unusedTips"].Success)
              unusedSpaceTarget.EraseClusterTips = false;
             else if (!match.Groups["unusedTipsValue"].Success)
              unusedSpaceTarget.EraseClusterTips = true;
             else
              unusedSpaceTarget.EraseClusterTips =
               trueValues.IndexOf(match.Groups["unusedTipsValue"].Value) != -1;
            }
            else if (match.Groups["directoryName"].Success)
            {
             FolderTarget folderTarget = new FolderTarget();
             target = folderTarget;

             folderTarget.Path = match.Groups["directoryName"].Value;
             if (!match.Groups["directoryDeleteIfEmpty"].Success)
              folderTarget.DeleteIfEmpty = false;
             else if (!match.Groups["directoryDeleteIfEmptyValue"].Success)
              folderTarget.DeleteIfEmpty = true;
             else
              folderTarget.DeleteIfEmpty =
               trueValues.IndexOf(match.Groups["directoryDeleteIfEmptyValue"].Value) != -1;
             if (match.Groups["directoryExcludeMask"].Success)
              folderTarget.ExcludeMask += match.Groups["directoryExcludeMask"].Value.Remove(0, 2) + ' ';
             if (match.Groups["directoryIncludeMask"].Success)
              folderTarget.IncludeMask += match.Groups["directoryIncludeMask"].Value.Remove(0, 2) + ' ';
            }
            else if (match.Groups["fileName"].Success)
            {
             FileTarget fileTarget = new FileTarget();
             target = fileTarget;
             fileTarget.Path = match.Groups["fileName"].Value;
            }

            if (target == null)
             continue;

            target.Method = method;
            task.Targets.Add(target);
               }

               if (task.Targets.Count == 0)
            throw new ArgumentException("Tasks must contain at least one erasure target.");

               try
               {
            using (RemoteExecutorClient client = new RemoteExecutorClient())
            {
             client.Run();
             if (!client.IsConnected)
             {

              Process eraserInstance = Process.Start(
               Assembly.GetExecutingAssembly().Location, "--quiet");
              eraserInstance.WaitForInputIdle();

              client.Run();
              if (!client.IsConnected)
               throw new IOException("Eraser cannot connect to the running " +
            "instance for erasures.");
             }

             client.Tasks.Add(task);
            }
               }
               catch (UnauthorizedAccessException e)
               {

            throw new UnauthorizedAccessException("Another instance of Eraser " +
             "is already running but it is running with higher privileges than " +
             "this instance of Eraser. Tasks cannot be added in this manner.\n\n" +
             "Close the running instance of Eraser and start it again without " +
             "administrator privileges, or run the command again as an " +
             "administrator.", e);
               }
        }
Exemplo n.º 38
0
        private static void CommandQueryMethods(ConsoleArguments arguments)
        {
            const string methodFormat = "{0,-2} {1,-39} {2}";
               Console.WriteLine(methodFormat, "", "Method", "GUID");
               Console.WriteLine(new string('-', 79));

               Dictionary<Guid, ErasureMethod> methods = ErasureMethodManager.Items;
               foreach (ErasureMethod method in methods.Values)
               {
            Console.WriteLine(methodFormat, (method is UnusedSpaceErasureMethod) ?
             "U" : "", method.Name, method.Guid.ToString());
               }
        }
		public void Invalid_Parsing_Examples()
		{
			var args = new ConsoleArguments();
			args.Parse(new[] { "/a:b" });
			args.GetValue("a").Should().Be("b");

			args.Invoking(a => a.Parse(new[] { " /a:b" }))
				.ShouldThrow<ArgumentException>()
				.WithMessage("Cannot parse property name from specified value ' /a:b'.");

			args.Invoking(a => a.Parse(new[] { "a:b" }))
				.ShouldThrow<ArgumentException>()
				.WithMessage("Cannot parse property name from specified value 'a:b'.");

			args.Invoking(a => a.Parse(new[] { "/:b" }))
				.ShouldThrow<ArgumentException>()
				.WithMessage("Specified value '' cannot be used as property name.");

			args.Invoking(a => a.Parse(new[] { "/:" }))
				.ShouldThrow<ArgumentException>()
				.WithMessage("Specified value '' cannot be used as property name.");

			args.Invoking(a => a.Parse(new[] { "/ :" }))
				.ShouldThrow<ArgumentException>()
				.WithMessage("Specified value ' ' cannot be used as property name.");

			args.Invoking(a => a.Parse(new[] { "/::" }))
				.ShouldThrow<ArgumentException>()
				.WithMessage("Specified value '' cannot be used as property name.");

			args.Parse(new[] { "/a:" });
			args.GetValue("a").Should().Be(String.Empty);

			args.Parse(new[] { "//:b" });
			args.GetValue("/").Should().Be("b");

			args.Parse(new[] { "//::" });
			args.GetValue("/").Should().Be(":");

			args = new ConsoleArguments();
			args.Parse(new[] { "-a:b" });
			args.GetValue("a:b").Should().Be("True");

			args.Invoking(a => a.Parse(new[] { " -a" }))
				.ShouldThrow<ArgumentException>()
				.WithMessage("Cannot parse property name from specified value ' -a'.");

			args.Invoking(a => a.Parse(new[] { "-" }))
				.ShouldThrow<ArgumentException>()
				.WithMessage("Specified value '' cannot be used as property name.");

			args.Invoking(a => a.Parse(new[] { "- " }))
				.ShouldThrow<ArgumentException>()
				.WithMessage("Specified value ' ' cannot be used as property name.");
		}
Exemplo n.º 40
0
         public ConsoleActionData(ConsoleProgram.ActionHandler handler,
 ConsoleArguments arguments)
         {
             Handler = handler;
             Arguments = arguments;
         }
Exemplo n.º 41
0
        private static void CommandHelp(ConsoleArguments arguments)
        {
            Console.WriteLine(@"Eraser {0}
            (c) 2008-2010 The Eraser Project
            Eraser is Open-Source Software: see http:
            ", Assembly.GetExecutingAssembly().GetName().Version);

               PrintCommandHelp();
        }
		public void Expected_Arguments_Can_Be_Null()
		{
			var args = new ConsoleArguments();
			args.Names.Should().BeEmpty();

			args = new ConsoleArguments(null);
			args.Names.Should().BeEmpty();
		}
Exemplo n.º 43
0
        private static void CommandImportTaskList(ConsoleArguments args)
        {
            try
               {
            using (RemoteExecutorClient client = new RemoteExecutorClient())
            {
             client.Run();
             if (!client.IsConnected)
             {

              Process eraserInstance = Process.Start(
               Assembly.GetExecutingAssembly().Location, "--quiet");
              eraserInstance.WaitForInputIdle();

              client.Run();
              if (!client.IsConnected)
               throw new IOException("Eraser cannot connect to the running " +
            "instance for erasures.");
             }

             foreach (string path in args.PositionalArguments)
              using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
               client.Tasks.LoadFromStream(stream);
            }
               }
               catch (UnauthorizedAccessException e)
               {

            throw new UnauthorizedAccessException("Another instance of Eraser " +
             "is already running but it is running with higher privileges than " +
             "this instance of Eraser. Tasks cannot be added in this manner.\n\n" +
             "Close the running instance of Eraser and start it again without " +
             "administrator privileges, or run the command again as an " +
             "administrator.", e);
               }
        }
Exemplo n.º 44
0
 private static void CommandQueryMethods(ConsoleArguments arguments)
 {
     const string methodFormat = "{0,-2} {1,-39} {2}";
        Console.WriteLine(methodFormat, "", "Method", "GUID");
        Console.WriteLine(new string('-', 79));
        foreach (ErasureMethod method in ManagerLibrary.Instance.ErasureMethodRegistrar)
        {
     Console.WriteLine(methodFormat, (method is UnusedSpaceErasureMethod) ?
      "U" : "", method.Name, method.Guid.ToString());
        }
 }