public override async Task RunAsync(CommandLineProcessor processor, IConsoleHost host)
 {
     var schema = JsonSchema4.FromJson(InputJson);
     var generator = new TypeScriptGenerator(schema);
     var code = generator.GenerateFile();
     WriteOutput(host, code);
 }
Beispiel #2
0
 public PrivateData(
     CommandLineProcessor.Delegate commandLineDelegate,
     VisualStudioProcessor.Delegate visualStudioDelegate)
 {
     this.CommandLineDelegate = commandLineDelegate;
     this.VisualStudioProjectDelegate = visualStudioDelegate;
 }
 public override async Task<object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
 {
     var document = await RunAsync();
     if (TryWriteFileOutput(host, () => document.ToJson()) == false)
         return document;
     return null; 
 }
Beispiel #4
0
        static void Main(string[] args)
        {
            var host = new ConsoleHost();
            host.WriteMessage("NSwag command line: v" + typeof(SwaggerInfo).Assembly.GetName().Version + "\n");
            host.WriteMessage("Visit http://NSwag.org for more information.\n");
            host.WriteMessage("Execute the 'help' command to show a list of all the available commands.\n");

            try
            {
                var processor = new CommandLineProcessor(host);

                processor.RegisterCommand<WebApiToSwaggerCommand>("webapi2swagger");

                processor.RegisterCommand<JsonSchemaToCSharpCommand>("jsonschema2csharp");
                processor.RegisterCommand<JsonSchemaToTypeScriptCommand>("jsonschema2typescript");
                
                processor.RegisterCommand<SwaggerToCSharpCommand>("swagger2csharp");
                processor.RegisterCommand<SwaggerToTypeScriptCommand>("swagger2typescript");

                processor.Process(args);
            }
            catch (Exception exception)
            {
                var savedForegroundColor = Console.ForegroundColor; 
                Console.ForegroundColor = ConsoleColor.Red;
                host.WriteMessage(exception.ToString());
                Console.ForegroundColor = savedForegroundColor;
            }

            if (Debugger.IsAttached)
            {
                Console.WriteLine("Press <any> key to exit...");
                Console.ReadKey();
            }
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            var host = new ConsoleHost();
            host.WriteMessage("NSwag command line: v" + typeof(SwaggerInfo).Assembly.GetName().Version + "\n");
            host.WriteMessage("Visit http://NSwag.org for more information.");
            host.WriteMessage("\n");

            try
            {
                var processor = new CommandLineProcessor(host);

                processor.RegisterCommand<CSharpCommand>("csharp");
                processor.RegisterCommand<TypeScriptCommand>("typescript");

                processor.Process(args);
            }
            catch (Exception exception)
            {
                var savedForegroundColor = System.Console.ForegroundColor;
                System.Console.ForegroundColor = ConsoleColor.Red;
                host.WriteMessage(exception.ToString());
                System.Console.ForegroundColor = savedForegroundColor;
            }

            if (Debugger.IsAttached)
                System.Console.ReadKey();
        }
Beispiel #6
0
 static void Main(string[] args)
 {
     var processor = new CommandLineProcessor(new ConsoleHost());
     processor.RegisterCommand<CloneCommand>("clone");
     processor.Process(args);
     Console.ReadKey();
 }
Beispiel #7
0
        public override async Task RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            var clientGenerator = new SwaggerToTypeScriptGenerator(InputSwaggerService);
            clientGenerator.Class = Class;

            var output = clientGenerator.GenerateFile();
            WriteOutput(host, output);
        }
        public override async Task RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            var clientGenerator = new SwaggerToCSharpGenerator(InputSwaggerService);
            clientGenerator.Class = Class;
            clientGenerator.Namespace = Namespace;
            clientGenerator.OperationGenerationMode = OperationGenerationMode;

            var output = clientGenerator.GenerateFile();
            WriteOutput(host, output);
        }
            public void ProcessArgs_NullOptionsAsParameter_ExceptionThrown()
            {
                // arrange
                clp = new CommandLineProcessor();

                // act - not required
                clp.Options = null;

                // assert - not required
            }
        public void When_adding_command_with_same_name_then_exception_is_thrown()
        {
            //// Arrange
            var processor = new CommandLineProcessor(new ConsoleHost(), new MyDependencyResolver());
            processor.RegisterCommand<MyCommand>("Test");

            //// Act
            processor.RegisterCommand<MyCommand>("test"); // exception

            //// Assert
        }
        public void When_adding_a_command_then_the_command_is_in_the_commands_list()
        {
            //// Arrange
            var processor = new CommandLineProcessor(new ConsoleHost(), new MyDependencyResolver());

            //// Act
            processor.RegisterCommand<MyCommand>("test");

            //// Assert
            Assert.IsTrue(processor.Commands.ContainsKey("test"));
        }
        public async Task When_dependency_resolver_is_missing_and_command_without_default_constructor_then_exception_is_thrown()
        {
            //// Arrange
            var processor = new CommandLineProcessor(new ConsoleHost());
            processor.RegisterCommand<MyCommand>("test");

            //// Act
            await processor.ProcessAsync(new string[] { "test" }); // exception

            //// Assert
        }
        public async Task WhenArgumentIsEnumThenItShouldBeLoadedCorrectly()
        {
            //// Arrange
            var processor = new CommandLineProcessor(new ConsoleHost());
            processor.RegisterCommand<MyEnumCommand>("test");

            //// Act
            var command = (MyEnumCommand)await processor.ProcessAsync(new string[] { "test", "/myenum:def" }); 

            //// Assert
            Assert.AreEqual(MyEnum.Def, command.MyEnum);
        }
        public async Task<object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            if (!DynamicApis.FileExists("nswag.json"))
            {
                await CreateDocumentAsync("nswag.json");
                host.WriteMessage("nswag.json file created.");
            }
            else
                host.WriteMessage("nswag.json already exists.");

            return null; 
        }
Beispiel #15
0
        public override bool Execute()
        {
            if (Debug) Debugger.Launch();

            _success = true;
            var commandProcessor = new CommandLineProcessor(new CommandRepository(ReadCommands(Services.Services.GetService<IEnvironment>())));

            foreach (var cmd in commandProcessor.Execute(new[] { Noun, Verb }.Concat(GetArguments()).ToList()))
                ProcessOutput(cmd);

            return _success;
        }
        public void When_adding_command_with_upper_case_then_it_is_converted_to_lower_case()
        {
            //// Arrange
            var processor = new CommandLineProcessor(new ConsoleHost(), new MyDependencyResolver());

            //// Act
            processor.RegisterCommand<MyCommand>("Test");

            //// Assert
            Assert.IsFalse(processor.Commands.ContainsKey("Test"));
            Assert.IsTrue(processor.Commands.ContainsKey("test"));
        }
        public async Task When_running_command_with_int64_parameter_then_they_are_correctly_set()
        {
            //// Arrange
            var processor = new CommandLineProcessor(new ConsoleHost());
            processor.RegisterCommand<MyArgumentCommand>("test");

            //// Act
            var command = (MyArgumentCommand)await processor.ProcessAsync(new string[] { "test", "/int64:123" });

            //// Assert
            Assert.IsTrue(123 == command.Int64);
        }
Beispiel #18
0
        public async Task When_array_has_empty_default_then_property_is_correctly_initialized()
        {
            //// Arrange
            var processor = new CommandLineProcessor(new ConsoleHost());
            processor.RegisterCommand<MyDefaultArrayCommand>("test");

            //// Act
            var result = await processor.ProcessAsync(new string[] { "test" });
            var command = (MyDefaultArrayCommand)result.Last().Command;

            //// Assert
            Assert.AreEqual(0, command.MyStrings.Length);
        }
        public void When_first_argument_is_existing_command_name_then_command_is_executed()
        {
            //// Arrange
            var resolver = new MyDependencyResolver(); 
            var processor = new CommandLineProcessor(new ConsoleHost(), resolver);
            processor.RegisterCommand<MyCommand>("test");

            //// Act
            var command = (MyCommand)processor.Process(new string[] { "test" });

            //// Assert
            Assert.IsNotNull(command);
        }
Beispiel #20
0
        /// <summary>Runs the command.</summary>
        /// <param name="processor">The processor.</param>
        /// <param name="host">The host.</param>
        /// <returns>The input object for the next command.</returns>
        public Task<object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            foreach (var pair in processor.Commands)
            {
                if (pair.Key != "help")
                {
                    PrintCommand(host, pair);
                    host.ReadValue("Press <enter> key for next command...");
                }
            }

            return Task.FromResult<object>(null);
        }
Beispiel #21
0
        public void TestAutoLayoutCommand()
        {
            var args = new string[] { "-input", Path.Combine(TestFilesPath, "MicroSecSemicolonSeperated.txt"),
                                      "-format", "Generic",
                                      "-TimeFormat", "yyyy-MM-dd-hh.mm.ss.ffffff",
                                      "-Precision", "Microseconds",
                                      "-splitter", ";",
                                      "-tags", "Server=abcd",
                                      "-ignoreerrors",
                                      "/export",
                                      "/autolayout" };

            Assert.IsFalse(CommandLineProcessor.ProcessArguments(args), "Processing AutoLayout Command failed");
        }
Beispiel #22
0
        public override Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            using (var collection = new ProjectCollection())
            {
                foreach (var projectPath in GetProjectPaths())
                {
                    try
                    {
                        var project = collection.LoadProject(projectPath);

                        var result = false;
                        switch (Action)
                        {
                        case "warnaserror":
                            result = EnableBooleanProperty(project, "WarningsAsErrors");
                            break;

                        case "xmldocs":
                            result = EnableXmlDocs(project);
                            break;

                        default:
                            throw new ArgumentException("The feature " + Action + " is not available.");
                        }

                        if (result)
                        {
                            host.WriteMessage("[x] Enabled feature " + Action + " in project " + System.IO.Path.GetFileName(projectPath) + "\n");

                            if (!Simulate)
                            {
                                project.Save();
                            }
                        }
                        else
                        {
                            host.WriteMessage("[ ] Feature " + Action + " already enabled in project " + System.IO.Path.GetFileName(projectPath) + "\n");
                        }

                        collection.UnloadProject(project);
                    }
                    catch (Exception e)
                    {
                        host.WriteError(e + "\n");
                    }
                }
            }

            return(Task.FromResult <object>(null));
        }
Beispiel #23
0
        public override Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            var schema    = JsonSchema4.FromJson(InputJson);
            var generator = new TypeScriptGenerator(schema);

            var code = generator.GenerateFile(Name);

            if (TryWriteFileOutput(host, () => code) == false)
            {
                return(Task.FromResult <object>(code));
            }

            return(Task.FromResult <object>(null));
        }
        public void CommandLineProcessor_IsThereASiteWhenCommandLineIsSet_SiteLoadedintoProperty()
        {
            // Arrange
            string[] args = new string[] { "-s testsite" };

            // Act   
            CommandLineProcessor p = new CommandLineProcessor(args, logger);

            var results = p.Options.SiteName;
            // Assert  
            Assert.AreEqual(results.Length > 0, true);
            Assert.AreEqual(results, "testsite");

        }
        public override async Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            var inputJson = await GetInputJsonAsync().ConfigureAwait(false);

            var schema = await JsonSchema4.FromJsonAsync(inputJson).ConfigureAwait(false);

            var generator = new CSharpGenerator(schema, Settings);

            var code = generator.GenerateFile(Name);

            await TryWriteFileOutputAsync(host, () => code).ConfigureAwait(false);

            return(code);
        }
Beispiel #26
0
        public void When_no_dependency_resolver_is_present_static_ctor_is_not_used()
        {
            //// Arrange
            var processor = new CommandLineProcessor(new ConsoleHost());

            processor.RegisterCommand <CommandWithStaticCtor>("test");

            //// Act
            var result  = processor.Process(new[] { "test" });
            var command = result.Last().Command as CommandWithStaticCtor;

            //// Assert
            Assert.NotNull(command);
        }
        public void Option_NoArg_1(params string[] args)
        {
            CommandLineProcessor cmdline = new CommandLineProcessor();

            cmdline.RegisterOptionMatchHandler("a", (sender, e) => { });

            cmdline.ProcessCommandLineArgs(args);

            Assert.That(cmdline.ArgCount, Is.EqualTo(1));

            IEnumerable <string> emptylist = new List <string>(0);

            Assert.That(cmdline.InvalidArgs, Is.EquivalentTo(emptylist));
        }
Beispiel #28
0
        /// <summary>Processes the command line arguments.</summary>
        /// <param name="args">The arguments.</param>
        /// <returns>The result.</returns>
        public int Process(string[] args)
        {
            var architecture = IntPtr.Size == 4 ? " (x86)" : " (x64)";

            _host.WriteMessage("toolchain v" + SwaggerDocument.ToolchainVersion +
                               " (NJsonSchema v" + JsonSchema4.ToolchainVersion + ")" + architecture + "\n");
            _host.WriteMessage("Visit http://NSwag.org for more information.\n");

            WriteBinDirectory();

            if (args.Length == 0)
            {
                _host.WriteMessage("Execute the 'help' command to show a list of all the available commands.\n");
            }

            try
            {
                var processor = new CommandLineProcessor(_host);

                processor.RegisterCommandsFromAssembly(_assemblyLoaderAssembly);
                processor.RegisterCommandsFromAssembly(typeof(SwaggerToCSharpControllerCommand).GetTypeInfo().Assembly);

                var stopwatch = new Stopwatch();
                stopwatch.Start();
                var results = processor.Process(args);
                stopwatch.Stop();

                var output   = results.Last()?.Output;
                var document = output as SwaggerDocument;
                if (document != null)
                {
                    _host.WriteMessage(document.ToJson());
                }
                else if (output != null)
                {
                    _host.WriteMessage(output.ToString());
                }

                _host.WriteMessage("\nDuration: " + stopwatch.Elapsed + "\n");
            }
            catch (Exception exception)
            {
                _host.WriteError(exception.ToString());
                return(-1);
            }

            WaitWhenDebuggerAttached();
            return(0);
        }
Beispiel #29
0
        public async Task When_running_command_with_quoted_string_parameter_then_they_are_correctly_set()
        {
            //// Arrange
            var processor = new CommandLineProcessor(new ConsoleHost());

            processor.RegisterCommand <MyArgumentCommand>("test");

            //// Act
            var result = await processor.ProcessAsync(new string[] { "test", "/string:abc def" });

            var command = (MyArgumentCommand)result.Last().Command;

            //// Assert
            Assert.AreEqual("abc def", command.String);
        }
Beispiel #30
0
        public async Task When_running_command_with_int64_parameter_then_they_are_correctly_set()
        {
            //// Arrange
            var processor = new CommandLineProcessor(new ConsoleHost());

            processor.RegisterCommand <MyArgumentCommand>("test");

            //// Act
            var result = await processor.ProcessAsync(new string[] { "test", "/int64:123" });

            var command = (MyArgumentCommand)result.Last().Command;

            //// Assert
            Assert.IsTrue(123 == command.Int64);
        }
Beispiel #31
0
        public async Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            if (await DynamicApis.FileExistsAsync("nswag.json").ConfigureAwait(false) == false)
            {
                await CreateDocumentAsync("nswag.json");

                host.WriteMessage("nswag.json file created.");
            }
            else
            {
                host.WriteMessage("nswag.json already exists.");
            }

            return(null);
        }
Beispiel #32
0
        public async Task When_running_command_with_boolean_parameter_then_they_are_correctly_set()
        {
            //// Arrange
            var processor = new CommandLineProcessor(new ConsoleHost());

            processor.RegisterCommand <MyArgumentCommand>("test");

            //// Act
            var result = await processor.ProcessAsync(new[] { "test", "/boolean:true" });

            var command = (MyArgumentCommand)result.Last().Command;

            //// Assert
            Assert.True(command.Boolean);
        }
Beispiel #33
0
        static void Main(string[] args)
        {
            Out.Echo(ANSI.RIS);
            Out.ClearScreen();
            var commandLineProcessor = new CommandLineProcessor(
                args,
                new OrbitalShellCommandLineProcessorSettings());
            var commandLineReader = new CommandLineReader(
                commandLineProcessor);

            commandLineProcessor.Initialize();
            var returnCode = commandLineReader.ReadCommandLine();

            Environment.Exit(returnCode);
        }
Beispiel #34
0
        public void When_first_argument_is_existing_command_name_then_command_is_executed()
        {
            //// Arrange
            var resolver  = new MyDependencyResolver();
            var processor = new CommandLineProcessor(new ConsoleHost(), resolver);

            processor.RegisterCommand <MyCommand>("test");

            //// Act
            var result  = processor.Process(new[] { "test" });
            var command = result.Last().Command as MyCommand;

            //// Assert
            Assert.NotNull(command);
        }
Beispiel #35
0
        public async Task When_array_has_empty_default_then_property_is_correctly_initialized()
        {
            //// Arrange
            var processor = new CommandLineProcessor(new ConsoleHost());

            processor.RegisterCommand <MyDefaultArrayCommand>("test");

            //// Act
            var result = await processor.ProcessAsync(new string[] { "test" });

            var command = (MyDefaultArrayCommand)result.Last().Command;

            //// Assert
            Assert.AreEqual(0, command.MyStrings.Length);
        }
Beispiel #36
0
        public async Task When_command_is_chained_and_output_is_ignored_then_first_command_does_not_influence_second_command()
        {
            //// Arrange
            var processor = new CommandLineProcessor(new ConsoleHost());
            processor.RegisterCommand<SumCommand>("sum");
            processor.RegisterCommand<SubtractCommand>("subtract");

            var args = new string[] { "sum", "/a:6", "/b:10", "=", "subtract", "/a: 20", "/b:7" };

            //// Act
            var result = await processor.ProcessAsync(args);

            //// Assert
            Assert.AreEqual(13, result.Last().Output);
        }
        public async Task When_argument_is_string_array_then_it_can_be_defined_as_comma_separated_string()
        {
            //// Arrange
            var processor = new CommandLineProcessor(new ConsoleHost());
            processor.RegisterCommand<MyArrayCommand>("test");

            //// Act
            var command = (MyArrayCommand)await processor.ProcessAsync(new string[] { "test", "/mystrings:a,b,c" }); 

            //// Assert
            Assert.AreEqual(3, command.MyStrings.Length);
            Assert.AreEqual("a", command.MyStrings[0]);
            Assert.AreEqual("b", command.MyStrings[1]);
            Assert.AreEqual("c", command.MyStrings[2]);
        }
        public override async Task RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            var settings = new CSharpGeneratorSettings
            {
                Namespace = Namespace,
                RequiredPropertiesMustBeDefined = RequiredPropertiesMustBeDefined,
                DateTimeType = DateTimeType
            };

            var schema    = JsonSchema4.FromJson(InputJson);
            var generator = new CSharpGenerator(schema, settings);
            var code      = generator.GenerateFile();

            WriteOutput(host, code);
        }
Beispiel #39
0
        public async Task When_positional_argument_starts_with_slash_then_it_is_correctly_read()
        {
            //// Arrange
            var processor = new CommandLineProcessor(new ConsoleHost());

            processor.RegisterCommand <MyCommand>("test");

            //// Act
            var result = await processor.ProcessAsync(new[] { "test", "/foo/bar/test.cs" });

            var command = (MyCommand)result.Last().Command;

            //// Assert
            Assert.Equal("/foo/bar/test.cs", command.First);
        }
Beispiel #40
0
        static void Main(string[] args)
        {
            if (args.ToList().Contains(WindowsServiceUtilities.RUN_AS_SERVICE_TOKEN))
            {
#if DEBUG
                Debugger.Launch();
#endif
                WindowsServiceUtilities.RunService();
            }
            else
            {
                var commandLineProcessor = new CommandLineProcessor();
                commandLineProcessor.EntryPoint(args);
            }
        }
Beispiel #41
0
        public async Task WhenArgumentIsEnumThenItShouldBeLoadedCorrectly()
        {
            //// Arrange
            var processor = new CommandLineProcessor(new ConsoleHost());

            processor.RegisterCommand <MyEnumCommand>("test");

            //// Act
            var result = await processor.ProcessAsync(new[] { "test", "/myenum:def" });

            var command = (MyEnumCommand)result.Last().Command;

            //// Assert
            Assert.Equal(MyEnum.Def, command.MyEnum);
        }
Beispiel #42
0
        public async Task When_command_is_chained_and_output_is_ignored_then_first_command_does_not_influence_second_command()
        {
            //// Arrange
            var processor = new CommandLineProcessor(new ConsoleHost());

            processor.RegisterCommand <SumCommand>("sum");
            processor.RegisterCommand <SubtractCommand>("subtract");

            var args = new string[] { "sum", "/a:6", "/b:10", "=", "subtract", "/a: 20", "/b:7" };

            //// Act
            var result = await processor.ProcessAsync(args);

            //// Assert
            Assert.AreEqual(13, result.Last().Output);
        }
        private void BasicWellFormedCheck(string option)
        {
            var originalValue = _options[option];

            Assert.DoesNotThrow(() => CommandLineProcessor.ValidateCommandLineArgs(_options), "legal value should not throw");

            _options[option] = string.Empty;
            Assert.Throws <CommandLineException>(() => CommandLineProcessor.ValidateCommandLineArgs(_options),
                                                 "empty string should have thrown");

            _options[option] = null;
            Assert.Throws <CommandLineException>(() => CommandLineProcessor.ValidateCommandLineArgs(_options),
                                                 "null string should have thrown");
            // Restore original value.
            _options[option] = originalValue;
        }
        public static int Main(string[] args)
        {
            _logger = new ConsoleLogger(
                ConsoleLoggerOptions.DisplayBanner
                | ConsoleLoggerOptions.UseLabels
                | ConsoleLoggerOptions.ShowTime);

            using (var processor = new CommandLineProcessor(args))
            {
                processor.WithErrorAction(ShowErrors)
                .WithHelpAction(ShowHelp);

                return(processor.Parse <ProgramOptions>()
                       .Execute(MainCore));
            }
        }
Beispiel #45
0
        public async Task When_command_is_chained_then_output_is_passed_as_input_to_second_command()
        {
            //// Arrange
            var processor = new CommandLineProcessor(new ConsoleHost());

            processor.RegisterCommand <SumCommand>("sum");
            processor.RegisterCommand <SubtractCommand>("subtract");

            var args = new [] { "sum", "/a:6", "/b:10", "=", "subtract", "/b:7" };

            //// Act
            var result = await processor.ProcessAsync(args);

            //// Assert
            Assert.Equal(9, result.Last().Output);
        }
        public override async Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            var packages = new List <PackageReferenceInfo>();

            LoadProjects(host, packages);
            await LoadAllDependenciesAsync(packages, host);
            await LoadLicensesAsync(packages, host);

            host.WriteMessage($"{"Package",-85} {"Version",-22} {"Type",-5} {"#",-3} {"License",-15} {"License URL"}\n");
            foreach (var entry in packages.OrderBy(p => p.Name).ThenBy(p => p.Version))
            {
                host.WriteMessage($"{entry.Name,-85} {entry.Version,-22} {entry.Type,-5} {entry.Count,-3} {entry.License,-15} {entry.LicenseUri,-10}\n");
            }

            return(Task.FromResult <object>(null));
        }
Beispiel #47
0
    public static void Main(string[] args)
    {
        bool listener_flag = false;             // Listen to network requests
        bool reader_flag   = false;             // Read the dictionary file

        string readerHandle = null;

        CommandLineProcessor argsProcessor = new CommandLineProcessor();

        argsProcessor.RegisterOptionMatchHandler("L", requiresArgument: false, (sender, o) => {
            listener_flag = true;
        });
        argsProcessor.RegisterOptionMatchHandler("R", requiresArgument: false, (sender, o) => {
            reader_flag = true;
        });
        argsProcessor.RegisterOptionMatchHandler("H", requiresArgument: true, (sender, o) => {
            readerHandle = o.Argument;
        });
        argsProcessor.RegisterOptionMatchHandler(CommandLineProcessor.InvalidOptionIdentifier, (sender, o) => {
            //Usage();
            Environment.Exit(1);
        });
        argsProcessor.ProcessCommandLineArgs(args);

        if (listener_flag && reader_flag)
        {
            // Error!
            Environment.Exit(1);
        }

        if (listener_flag)
        {
            // run as the network Listener
            Listener();
        }

        if (reader_flag)
        {
            // run as the dictionary reader
            Reader(readerHandle);
        }

        // This is what the main app does
        ForkListener();
        ForkReader();
    }
        public override async Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            var configuration = ReferenceSwitcherConfiguration.Load(Configuration, host);

            if (configuration == null)
            {
                return(null);
            }

            await AddProjectsToSolutionAsync(configuration, host);

            SwitchToProjects(configuration, host);

            configuration.Save();

            return(null);
        }
Beispiel #49
0
        public static void Main(string[] args)
        {
            logger.Info("IIS Log Muncher (" + Assembly.GetExecutingAssembly().GetName().Version.ToString() + ")" + " starting.");

            var clp = new CommandLineProcessor("achis:t:");
            var clo = clp.ProcessArgs(args);

            if (clo.IsOptionSet('h'))
            {
                ShowHelpText();
            }

            var fhe = new FileHelperEngine(clo);
            fhe.ProcessFileList();

            logger.Info("IIS Log Muncher finished.");
        }
Beispiel #50
0
        public override async Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            var configuration = ReferenceSwitcherConfiguration.Load(Configuration, host);

            if (configuration == null)
            {
                return(null);
            }

            SwitchToPackages(host, configuration);
            await RemoveProjectsFromSolutionAsync(configuration, host);

            configuration.Restore = null; // restore information no longer needed
            configuration.Save();

            return(null);
        }
Beispiel #51
0
        public async Task When_running_command_with_datetime_parameter_then_they_are_correctly_set()
        {
            //// Arrange
            var processor = new CommandLineProcessor(new ConsoleHost());

            processor.RegisterCommand <MyArgumentCommand>("test");

            //// Act
            var result = await processor.ProcessAsync(new string[] { "test", "/datetime:2014-5-3" });

            var command = (MyArgumentCommand)result.Last().Command;

            //// Assert
            Assert.AreEqual(3, command.DateTime.Day);
            Assert.AreEqual(5, command.DateTime.Month);
            Assert.AreEqual(2014, command.DateTime.Year);
        }
Beispiel #52
0
        public override async Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            return(await Task.Run(async() =>
            {
                var generator = await CreateGeneratorAsync();
                var classNames = generator.GetExportedClassNames();

                host.WriteMessage("\r\n");
                foreach (var className in classNames)
                {
                    host.WriteMessage(className + "\r\n");
                }
                host.WriteMessage("\r\n");

                return classNames;
            }));
        }
        public void ValidatesFilesRelativeToAppContext()
        {
            var exists = Path.Combine(AppContext.BaseDirectory, "exists.txt");

            if (!File.Exists(exists))
            {
                File.WriteAllText(exists, "");
            }

            var appInBaseDir = new CommandLineApplication(
                new TestConsole(_output),
                AppContext.BaseDirectory,
                false);
            var notFoundDir     = Path.Combine(AppContext.BaseDirectory, "notfound");
            var appNotInBaseDir = new CommandLineApplication(
                new TestConsole(_output),
                notFoundDir,
                false);

            appInBaseDir.Argument("Files", "Files")
            .Accepts(v => v.ExistingFileOrDirectory());
            appNotInBaseDir.Argument("Files", "Files")
            .Accepts(v => v.ExistingFileOrDirectory());

            var success = new CommandLineProcessor(appInBaseDir, new[] { "exists.txt" })
                          .Process()
                          .GetValidationResult();

            var fails = new CommandLineProcessor(appNotInBaseDir, new[] { "exists.txt" })
                        .Process()
                        .GetValidationResult();

            Assert.Equal(ValidationResult.Success, success);

            Assert.NotEqual(ValidationResult.Success, fails);
            Assert.Equal("The file path 'exists.txt' does not exist.", fails.ErrorMessage);

            var console = new TestConsole(_output);
            var context = new DefaultCommandLineContext(console, appNotInBaseDir.WorkingDirectory, new[] { "exists.txt" });

            Assert.NotEqual(0, CommandLineApplication.Execute <App>(context));

            context = new DefaultCommandLineContext(console, appInBaseDir.WorkingDirectory, new[] { "exists.txt" });
            Assert.Equal(0, CommandLineApplication.Execute <App>(context));
        }
Beispiel #54
0
        /// <summary>Processes the command line arguments.</summary>
        /// <param name="args">The arguments.</param>
        /// <returns>The result.</returns>
        public int Process(string[] args)
        {
            var architecture = IntPtr.Size == 4 ? " (x86)" : " (x64)";
            _host.WriteMessage("toolchain v" + SwaggerDocument.ToolchainVersion + " (NJsonSchema v" + JsonSchema4.ToolchainVersion + ")" + architecture + "\n");
            _host.WriteMessage("Visit http://NSwag.org for more information.\n");

            var binDirectory = DynamicApis.PathGetDirectoryName(((dynamic)typeof(NSwagCommandProcessor).GetTypeInfo().Assembly).CodeBase.Replace("file:///", string.Empty));
            _host.WriteMessage("NSwag bin directory: " + binDirectory + "\n");

            if (args.Length == 0)
                _host.WriteMessage("Execute the 'help' command to show a list of all the available commands.\n");

            try
            {
                var processor = new CommandLineProcessor(_host);

                processor.RegisterCommandsFromAssembly(_assemblyLoaderAssembly);
                processor.RegisterCommandsFromAssembly(typeof(SwaggerToCSharpControllerCommand).GetTypeInfo().Assembly);

                var stopwatch = new Stopwatch();
                stopwatch.Start();
                var results = processor.Process(args);
                stopwatch.Stop();

                var output = results.Last()?.Output;
                var document = output as SwaggerDocument;
                if (document != null)
                    _host.WriteMessage(document.ToJson());
                else if (output != null)
                    _host.WriteMessage(output.ToString());

                _host.WriteMessage("\nDuration: " + stopwatch.Elapsed);
            }
            catch (Exception exception)
            {
                _host.WriteError(exception.ToString());
                return -1;
            }

            WaitWhenDebuggerAttached();
            return 0;
        }
        public async Task<object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            if (!string.IsNullOrEmpty(Input))
                await ExecuteDocumentAsync(host, Input);
            else
            {
                if (DynamicApis.FileExists("nswag.json"))
                    await ExecuteDocumentAsync(host, "nswag.json");

                var files = DynamicApis.DirectoryGetFiles(DynamicApis.DirectoryGetCurrentDirectory(), "*.nswag");
                if (files.Any())
                {
                    foreach (var file in files)
                        await ExecuteDocumentAsync(host, file);
                }
                else
                    host.WriteMessage("Current directory does not contain any .nswag files.");
            }
            return null; 
        }
Beispiel #56
0
 /// <summary>Runs the command.</summary>
 /// <param name="processor">The processor.</param>
 /// <param name="host">The host.</param>
 /// <returns>The output.</returns>
 public Task<object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
 {
     host.WriteMessage("\nNSwag version: " + SwaggerDocument.ToolchainVersion + "\n");
     host.WriteMessage("NJsonSchema version: " + JsonSchema4.ToolchainVersion + "\n");
     return Task.FromResult<object>(null);
 }
Beispiel #57
0
 public PrivateData(
     CommandLineProcessor.Delegate commandLineDelegate)
 {
     this.CommandLineDelegate = commandLineDelegate;
 }
Beispiel #58
0
 public async Task<object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
 {
     host.WriteMessage(string.Format("Clone {{ Repository={0}, Quiet={1} }}", Repository, Quiet));
     return null; 
 }
Beispiel #59
-1
        public override Task<object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            var schema = JsonSchema4.FromJson(InputJson);
            var generator = new CSharpGenerator(schema, Settings);

            var code = generator.GenerateFile(Name); 
            if (TryWriteFileOutput(host, () => code) == false)
                return Task.FromResult<object>(code);

            return Task.FromResult<object>(null);
        }
 public override async Task RunAsync(CommandLineProcessor processor, IConsoleHost host)
 {
     var settings = new CSharpGeneratorSettings
     {
         Namespace = Namespace,
         RequiredPropertiesMustBeDefined = RequiredPropertiesMustBeDefined,
         DateTimeType = DateTimeType
     };
     
     var schema = JsonSchema4.FromJson(InputJson);
     var generator = new CSharpGenerator(schema, settings);
     var code = generator.GenerateFile();
     WriteOutput(host, code);
 }