예제 #1
0
        /// <summary>
        /// Generates client using provided settings.
        /// </summary>
        /// <param name="settings">Code generator settings.</param>
        public static void Generate(Settings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }
            Logger.Entries.Clear();
            Logger.LogInfo(Resources.AutoRestCore, Version);
            CodeGenerator codeGenerator = ExtensionsLoader.GetCodeGenerator(settings);
            Modeler       modeler       = ExtensionsLoader.GetModeler(settings);

            settings.Validate();
            ServiceClient serviceClient;

            try
            {
                serviceClient = modeler.Build();
            }
            catch (Exception exception)
            {
                throw ErrorManager.CreateError(exception, Resources.ErrorGeneratingClientModel, exception.Message);
            }
            try
            {
                codeGenerator.NormalizeClientModel(serviceClient);
                codeGenerator.Generate(serviceClient).GetAwaiter().GetResult();
            }
            catch (Exception exception)
            {
                throw ErrorManager.CreateError(exception, Resources.ErrorSavingGeneratedCode, exception.Message);
            }
        }
예제 #2
0
        public void LanguageLoadsFromJsonFile()
        {
            var settings = new Settings {CodeGenerator = "CSharp", FileSystem = _fileSystem};
            CodeGenerator language = ExtensionsLoader.GetCodeGenerator(settings);

            Assert.Equal("CSharp", language.Name);
        }
예제 #3
0
 public void NoJsonFileThrowsException()
 {
     _fileSystem.DeleteFile("AutoRest.json");
     AssertThrows<CodeGenerationException>(() => ExtensionsLoader.GetCodeGenerator
         (new Settings {CodeGenerator = "JavaScript", FileSystem = _fileSystem}),
         "AutoRest.json was not found in the current directory");
 }
예제 #4
0
        public void LanguageWithoutSettingsLoadsFromJsonFile()
        {
            CodeGenerator language =
                ExtensionsLoader.GetCodeGenerator(new Settings {
                CodeGenerator = "CSharp", FileSystem = _fileSystem
            });

            Assert.Equal("CSharp", language.Name);
        }
예제 #5
0
        public void NullOrEmptyAutoRestSettings()
        {
            Assert.Throws<ArgumentNullException>(() => ExtensionsLoader.GetCodeGenerator(null));
            Assert.Throws<ArgumentException>(() => ExtensionsLoader.GetCodeGenerator(
                new Settings {CodeGenerator = string.Empty, FileSystem = _fileSystem}));

            Assert.Throws<ArgumentNullException>(() => ExtensionsLoader.GetModeler(null));
            Assert.Throws<ArgumentException>(() => ExtensionsLoader.GetModeler(
                new Settings {Modeler = string.Empty, FileSystem = _fileSystem}));
        }
예제 #6
0
        public void InvalidJsonFileThrowsException()
        {
            _fileSystem.WriteFile("AutoRest.json", "{'foo': 'bar'}");
            AssertThrows<CodeGenerationException>(() => ExtensionsLoader.GetCodeGenerator
                (new Settings {CodeGenerator = "JavaScript", FileSystem = _fileSystem}),
                string.Format("Plugin {0} does not have an assembly name in AutoRest.json", "JavaScript"));

            _fileSystem.WriteFile("AutoRest.json", "{'foo': ");
            AssertThrows<CodeGenerationException>(() => ExtensionsLoader.GetCodeGenerator
                (new Settings {CodeGenerator = "JavaScript", FileSystem = _fileSystem}),
                "Error parsing AutoRest.json file");
        }
예제 #7
0
 public void InvalidLanguageNameThrowsException()
 {
     string codeGenerator = "Foo.Bar";
     AssertThrows<CodeGenerationException>(
         () =>
             ExtensionsLoader.GetCodeGenerator(new Settings
             {
                 CodeGenerator = codeGenerator,
                 FileSystem = _fileSystem
             }),
         string.Format("Plugin {0} does not have an assembly name in AutoRest.json", codeGenerator));
 }
예제 #8
0
        public void InvalidTypeThrowsException()
        {
            _fileSystem.WriteFile("AutoRest.json", File.ReadAllText(Path.Combine("Resource", "AutoRestWithInvalidType.json")));

            AssertThrows<CodeGenerationException>(() => ExtensionsLoader.GetCodeGenerator
                (new Settings {CodeGenerator = "CSharp", FileSystem = _fileSystem}),
                string.Format("Error loading {0} assembly", "CSharp"));

            AssertThrows<CodeGenerationException>(() => ExtensionsLoader.GetCodeGenerator
                (new Settings {CodeGenerator = "Java", FileSystem = _fileSystem}),
                string.Format("Error loading {0} assembly", "Java"));
        }
예제 #9
0
        /// <summary>
        /// Generates client using provided settings.
        /// </summary>
        /// <param name="settings">Code generator settings.</param>
        public static void Generate(Settings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }
            Logger.Entries.Clear();
            Logger.LogInfo(Resources.AutoRestCore, Version);
            Modeler       modeler       = ExtensionsLoader.GetModeler(settings);
            ServiceClient serviceClient = null;

            IEnumerable <ValidationMessage> messages = new List <ValidationMessage>();

            try
            {
                serviceClient = modeler.Build(out messages);
            }
            catch (Exception exception)
            {
                throw ErrorManager.CreateError(exception, Resources.ErrorGeneratingClientModel, exception.Message);
            }
            finally
            {
                // Make sure to log any validation messages
                foreach (var message in messages)
                {
                    Logger.Entries.Add(new LogEntry(message.Severity, message.ToString()));
                }
                if (messages.Any(entry => entry.Severity >= settings.ValidationLevel))
                {
                    throw ErrorManager.CreateError(null, Resources.ErrorGeneratingClientModel, Resources.CodeGenerationError);
                }
            }

            CodeGenerator codeGenerator = ExtensionsLoader.GetCodeGenerator(settings);

            Logger.WriteOutput(codeGenerator.UsageInstructions);

            settings.Validate();
            try
            {
                codeGenerator.NormalizeClientModel(serviceClient);
                codeGenerator.Generate(serviceClient).GetAwaiter().GetResult();
            }
            catch (Exception exception)
            {
                throw ErrorManager.CreateError(exception, Resources.ErrorSavingGeneratedCode, exception.Message);
            }
        }
예제 #10
0
        public void LanguageWithSettingsLoadsFromJsonFile()
        {
            var settings = new Settings
            {
                CodeGenerator   = "NodeJS",
                FileSystem      = _fileSystem,
                Input           = "X:\\RedisResource.json",
                OutputDirectory = "X:\\Output"
            };
            CodeGenerator language = ExtensionsLoader.GetCodeGenerator(settings);

            settings.Validate();

            Assert.Equal("NodeJS", language.Name);
        }
예제 #11
0
        public void TestSettingsFromSwagger()
        {
            var settings = new Settings
            {
                Namespace = "Test",
                Modeler = "Swagger",
                CodeGenerator = "CSharp",
                Input = Path.Combine("Swagger", "swagger-x-ms-code-generation-settings.json"),
                Header = "NONE"
            };
            var modeler = ExtensionsLoader.GetModeler(settings);
            var client = modeler.Build();
            var codeGenerator = ExtensionsLoader.GetCodeGenerator(settings) as CSharpCodeGenerator;
            settings.Validate();

            Assert.Equal("MIT", settings.Header);
            Assert.Equal(true, codeGenerator.InternalConstructors);
        }
예제 #12
0
        private static void Main(string[] args)
        {
            try
            {
                if (IsShowMarkdownHelpIncluded(args))
                {
                    Console.WriteLine(HelpGenerator.Generate(Resources.HelpMarkdownTemplate));
                }
                else if (IsShowHelpIncluded(args))
                {
                    Console.WriteLine(HelpGenerator.Generate(Resources.HelpTextTemplate));
                }
                else
                {
                    Settings settings = null;
                    try
                    {
                        settings = Settings.Create(args);
                        AutoRest.Generate(settings);
                        var codeGenerator = ExtensionsLoader.GetCodeGenerator(settings);
                        Console.WriteLine(codeGenerator.UsageInstructions);
                    }
                    catch (CodeGenerationException)
                    {
                        // Do not add the CodeGenerationException again. Will be written in finally block
                    }
                    catch (Exception exception)
                    {
                        Logger.LogError(exception, exception.Message);
                    }
                    finally
                    {
                        if (
                            Logger.Entries.Any(
                                e => e.Severity == LogEntrySeverity.Error || e.Severity == LogEntrySeverity.Fatal))
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                        }
                        else if (Logger.Entries.Any(e => e.Severity == LogEntrySeverity.Warning))
                        {
                            Console.ForegroundColor = ConsoleColor.Yellow;
                        }

                        if (settings != null)
                        {
                            if (Logger.Entries.Any(e => e.Severity == LogEntrySeverity.Error || e.Severity == LogEntrySeverity.Fatal))
                            {
                                Console.WriteLine(Resources.GenerationFailed);
                                Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0} {1}",
                                                                typeof(Program).Assembly.ManifestModule.Name,
                                                                string.Join(" ", args)));
                            }
                            else
                            {
                                Console.WriteLine(Resources.GenerationComplete,
                                                  settings.CodeGenerator, settings.Input);
                            }
                        }

                        Logger.WriteErrors(Console.Error,
                                           args.Any(a => "-Verbose".Equals(a, StringComparison.OrdinalIgnoreCase)));

                        Logger.WriteWarnings(Console.Out);

                        // Include LogEntrySeverity.Infos for verbose logging.
                        if (args.Any(a => "-Verbose".Equals(a, StringComparison.OrdinalIgnoreCase)))
                        {
                            Logger.WriteInfos(Console.Out);
                        }

                        Console.ResetColor();
                    }
                }
            }
            catch (Exception exception)
            {
                Console.Error.WriteLine(Resources.ConsoleErrorMessage, exception.Message);
                Console.Error.WriteLine(Resources.ConsoleErrorStackTrace, exception.StackTrace);
            }
        }