Example #1
0
        private static void GenerateCodeInto(Action <IEnumerable <LogMessage> > processMessages)
        {
            using (NewContext)
            {
                var plugin   = ExtensionsLoader.GetPlugin();
                var modeler  = ExtensionsLoader.GetModeler();
                var messages = new List <LogMessage>();
                Logger.Instance.AddListener(new SignalingLogListener(Category.Info, message => messages.Add(message)));
                try
                {
                    var codeModel = modeler.Build();

                    using (plugin.Activate())
                    {
                        // load model into language-specific code model
                        codeModel = plugin.Serializer.Load(codeModel);

                        // apply language-specific tranformation (more than just language-specific types)
                        // used to be called "NormalizeClientModel" .
                        codeModel = plugin.Transformer.TransformCodeModel(codeModel);

                        // Generate code from CodeModel.
                        plugin.CodeGenerator.Generate(codeModel).GetAwaiter().GetResult();
                    }
                }
                finally
                {
                    processMessages(messages);
                }
            }
        }
        public void InvalidTypeThrowsException()
        {
            using (NewContext)
            {
                _fileSystem.WriteFile("AutoRest.json",
                                      File.ReadAllText(Path.Combine("Resource", "AutoRestWithInvalidType.json")));

                new Settings {
                    CodeGenerator = "CSharp", FileSystem = _fileSystem
                };

                AssertThrows <CodeGenerationException>(
                    () => ExtensionsLoader.GetPlugin(),
                    "Plugin CSharp does not have an assembly name in AutoRest.json");
            }

            using (NewContext)
            {
                new Settings {
                    CodeGenerator = "Java", FileSystem = _fileSystem
                };
                AssertThrows <CodeGenerationException>(() => ExtensionsLoader.GetPlugin(),
                                                       "Plugin Java does not have an assembly name in AutoRest.json");
            }
        }
Example #3
0
    protected override async Task <bool> ProcessInternal()
    {
        var codeGenerator = await GetValue("codeGenerator");

        // build settings
        new Settings
        {
            Namespace  = await GetValue("namespace"),
            ClientName = await GetValue("clientNameOverride"),
            PayloadFlatteningThreshold = await GetValue <int>("payloadFlatteningThreshold"),
            AddCredentials             = await GetValue <bool>("addCredentials"),
        };
        var header = await GetValue("header");

        if (header != null)
        {
            Settings.Instance.Header = header;
        }
        Settings.Instance.CustomSettings.Add("InternalConstructors", await GetValue <bool>("internalConstructors"));
        Settings.Instance.CustomSettings.Add("SyncMethods", await GetValue <string>("syncMethods"));
        Settings.Instance.CustomSettings.Add("UseDateTimeOffset", await GetValue <bool>("useDateTimeOffset"));
        if (codeGenerator.EndsWith("Ruby"))
        {
            Settings.Instance.PackageName = await GetValue("rubyPackageName");
        }

        // process
        var files = await ListInputs();

        if (files.Length != 1)
        {
            return(false);
        }

        var plugin      = ExtensionsLoader.GetPlugin(codeGenerator);
        var modelAsJson = (await ReadFile(files[0])).EnsureYamlIsJson();

        using (plugin.Activate())
        {
            var codeModel = plugin.Serializer.Load(modelAsJson);
            codeModel = plugin.Transformer.TransformCodeModel(codeModel);
            plugin.CodeGenerator.Generate(codeModel).GetAwaiter().GetResult();
        }

        // write out files
        var outFS    = Settings.Instance.FileSystemOutput;
        var outFiles = outFS.GetFiles("", "*", System.IO.SearchOption.AllDirectories);

        foreach (var outFile in outFiles)
        {
            WriteFile(outFile, outFS.ReadAllText(outFile), null);
        }

        return(true);
    }
Example #4
0
        internal static MemoryFileSystem GenerateCodeInto(this string testName, MemoryFileSystem fileSystem, Settings settings)
        {
            // copy the whole input directory into the memoryfilesystem.
            fileSystem.CopyFolder("Resource", testName, "");

            // find the appropriately named .yaml or .json file for the swagger.
            foreach (var ext in new[] { ".yaml", ".json", ".md" })
            {
                var name = testName + ext;
                if (fileSystem.FileExists(name))
                {
                    settings.Input = name;
                }
            }

            if (string.IsNullOrWhiteSpace(settings.Input))
            {
                throw new Exception($"Can't find swagger file ${testName} [.yaml] [.json] [.md]");
            }

            var plugin    = ExtensionsLoader.GetPlugin();
            var modeler   = ExtensionsLoader.GetModeler();
            var codeModel = modeler.Build();

            // After swagger Parser
            codeModel = AutoRestController.RunExtensions(Trigger.AfterModelCreation, codeModel);

            // After swagger Parser
            codeModel = AutoRestController.RunExtensions(Trigger.BeforeLoadingLanguageSpecificModel, codeModel);

            using (plugin.Activate())
            {
                // load model into language-specific code model
                codeModel = plugin.Serializer.Load(codeModel);

                // we've loaded the model, run the extensions for after it's loaded
                codeModel = AutoRestController.RunExtensions(Trigger.AfterLoadingLanguageSpecificModel, codeModel);

                // apply language-specific tranformation (more than just language-specific types)
                // used to be called "NormalizeClientModel" .
                codeModel = plugin.Transformer.TransformCodeModel(codeModel);

                // next set of extensions
                codeModel = AutoRestController.RunExtensions(Trigger.AfterLanguageSpecificTransform, codeModel);

                // next set of extensions
                codeModel = AutoRestController.RunExtensions(Trigger.BeforeGeneratingCode, codeModel);

                // Generate code from CodeModel.
                plugin.CodeGenerator.Generate(codeModel).GetAwaiter().GetResult();
            }

            return(fileSystem);
        }
        public void LanguageWithoutSettingsLoadsFromJsonFile()
        {
            using (NewContext)
            {
                var settings = new Settings {
                    CodeGenerator = "CSharp", FileSystem = _fileSystem
                };

                var language = ExtensionsLoader.GetPlugin();
                Assert.Equal("CSharp", language.Settings.Name);
            }
        }
Example #6
0
        internal static MemoryFileSystem GenerateCodeInto(this string inputFile, MemoryFileSystem fileSystem, Settings settings)
        {
            string fileName = Path.GetFileName(inputFile);

            // If inputFile does not contain a path use the local Resource folder
            if (inputFile == fileName)
            {
                fileSystem.Copy(Path.Combine("Resource", inputFile));
            }
            else
            {
                fileSystem.Copy(inputFile);
            }

            settings.Input = fileName;


            var plugin    = ExtensionsLoader.GetPlugin();
            var modeler   = ExtensionsLoader.GetModeler();
            var codeModel = modeler.Build();

            // After swagger Parser
            codeModel = AutoRestController.RunExtensions(Trigger.AfterModelCreation, codeModel);

            // After swagger Parser
            codeModel = AutoRestController.RunExtensions(Trigger.BeforeLoadingLanguageSpecificModel, codeModel);

            using (plugin.Activate())
            {
                // load model into language-specific code model
                codeModel = plugin.Serializer.Load(codeModel);

                // we've loaded the model, run the extensions for after it's loaded
                codeModel = AutoRestController.RunExtensions(Trigger.AfterLoadingLanguageSpecificModel, codeModel);

                // apply language-specific tranformation (more than just language-specific types)
                // used to be called "NormalizeClientModel" .
                codeModel = plugin.Transformer.TransformCodeModel(codeModel);

                // next set of extensions
                codeModel = AutoRestController.RunExtensions(Trigger.AfterLanguageSpecificTransform, codeModel);

                // next set of extensions
                codeModel = AutoRestController.RunExtensions(Trigger.BeforeGeneratingCode, codeModel);

                // Generate code from CodeModel.
                plugin.CodeGenerator.Generate(codeModel).GetAwaiter().GetResult();
            }

            return(fileSystem);
        }
        public void NoJsonFileThrowsException()
        {
            using (NewContext)
            {
                new Settings {
                    CodeGenerator = "JavaScript", FileSystem = _fileSystem
                };
                _fileSystem.DeleteFile("AutoRest.json");

                AssertThrows <CodeGenerationException>(
                    () => ExtensionsLoader.GetPlugin(),
                    "AutoRest.json was not found in the current directory");
            }
        }
        public void InvalidLanguageNameThrowsException()
        {
            using (NewContext)
            {
                string codeGenerator = "Foo.Bar";
                var    settings      = new Settings
                {
                    CodeGenerator = codeGenerator,
                    FileSystem    = _fileSystem
                };


                AssertThrows <CodeGenerationException>(
                    () => ExtensionsLoader.GetPlugin(),
                    $"Plugin {codeGenerator} does not have an assembly name in AutoRest.json");
            }
        }
Example #9
0
        private static void GenerateCodeInto(Action <IEnumerable <LogMessage> > processMessages)
        {
            using (NewContext)
            {
                var plugin   = ExtensionsLoader.GetPlugin();
                var modeler  = ExtensionsLoader.GetModeler();
                var messages = new List <LogMessage>();
                Logger.Instance.AddListener(new SignalingLogListener(Category.Info, message => messages.Add(message)));
                try
                {
                    var codeModel = modeler.Build();

                    // After swagger Parser
                    codeModel = AutoRestController.RunExtensions(Trigger.AfterModelCreation, codeModel);

                    // After swagger Parser
                    codeModel = AutoRestController.RunExtensions(Trigger.BeforeLoadingLanguageSpecificModel, codeModel);

                    using (plugin.Activate())
                    {
                        // load model into language-specific code model
                        codeModel = plugin.Serializer.Load(codeModel);

                        // we've loaded the model, run the extensions for after it's loaded
                        codeModel = AutoRestController.RunExtensions(Trigger.AfterLoadingLanguageSpecificModel, codeModel);

                        // apply language-specific tranformation (more than just language-specific types)
                        // used to be called "NormalizeClientModel" .
                        codeModel = plugin.Transformer.TransformCodeModel(codeModel);

                        // next set of extensions
                        codeModel = AutoRestController.RunExtensions(Trigger.AfterLanguageSpecificTransform, codeModel);

                        // next set of extensions
                        codeModel = AutoRestController.RunExtensions(Trigger.BeforeGeneratingCode, codeModel);

                        // Generate code from CodeModel.
                        plugin.CodeGenerator.Generate(codeModel).GetAwaiter().GetResult();
                    }
                }
                finally
                {
                    processMessages(messages);
                }
            }
        }
 public void NullOrEmptyAutoRestSettings()
 {
     using (NewContext)
     {
         var settings = new Settings {
             CodeGenerator = string.Empty, FileSystem = _fileSystem
         };
         Assert.Throws <ArgumentException>(() => ExtensionsLoader.GetPlugin());
     }
     using (NewContext)
     {
         var settings = new Settings {
             Modeler = string.Empty, FileSystem = _fileSystem
         };
         Assert.Throws <ArgumentException>(() => ExtensionsLoader.GetModeler());
     }
 }
        public void LanguageWithSettingsLoadsFromJsonFile()
        {
            using (NewContext)
            {
                var settings = new Settings
                {
                    CodeGenerator   = "NodeJS",
                    FileSystem      = _fileSystem,
                    Input           = "X:\\RedisResource.json",
                    OutputDirectory = "X:\\Output"
                };

                var language = ExtensionsLoader.GetPlugin();
                settings.Validate();

                Assert.Equal("NodeJS", language.Settings.Name);
            }
        }
Example #12
0
        public static void RunTests(string resultFolder)
        {
            if (resultFolder == null)
            {
                throw new ArgumentNullException("settings");
            }
            var settings = Settings.Instance;

            settings.FileSystemInput = new MemoryFileSystem();
            settings.FileSystemInput.CreateDirectory(Path.GetDirectoryName(settings.Input));
            settings.FileSystemInput.WriteAllText(settings.Input, File.ReadAllText(settings.Input));

            var expectedWithSeparator = "Expected" + Path.DirectorySeparatorChar;
            var specFileName          = resultFolder.StartsWith(expectedWithSeparator, StringComparison.Ordinal)
                ? resultFolder.Substring(expectedWithSeparator.Length)
                : resultFolder;

            var name = ExtensionsLoader.GetPlugin().Settings.Name;

            settings.Namespace = string.IsNullOrEmpty(settings.Namespace)
                ? "Fixtures." + (name.Contains("Azure") ? "Azure." : "") + specFileName.
                                 Replace(".cs", "").Replace(".Cs", "").Replace(".java", "").
                                 Replace(".js", "").Replace(".", "").
                                 Replace(Path.DirectorySeparatorChar.ToString(), "").Replace("-", "")
                : settings.Namespace;
            settings.DisableSimplifier = true;

            AutoRest.Core.AutoRestController.Generate();
            Assert.NotEmpty(settings.FileSystemOutput.VirtualStore);

            var actualFiles   = settings.FileSystemOutput.GetFiles("", "*.*", SearchOption.AllDirectories).OrderBy(f => f).ToArray();
            var expectedFiles = Directory.Exists(resultFolder) ? Directory.GetFiles(resultFolder, "*.*", SearchOption.AllDirectories).OrderBy(f => f).ToArray() : new string[0];

            Assert.Equal(expectedFiles.Length, actualFiles.Length);

            for (int i = 0; i < expectedFiles.Length; i++)
            {
                var actualFile   = actualFiles[i];
                var expectedFile = expectedFiles[i];
                EnsureFilesMatch(File.ReadAllText(expectedFile), settings.FileSystemOutput.ReadAllText(actualFile));
            }
        }
Example #13
0
        internal static MemoryFileSystem GenerateCodeInto(this string inputDir, MemoryFileSystem fileSystem, Settings settings)
        {
            fileSystem.Copy(Path.Combine("Resource", inputDir));
            var fileExt = (File.Exists(Path.Combine("Resource", Path.Combine(inputDir, inputDir + ".yaml"))) ? ".yaml" : ".json");

            settings.Input = Path.Combine("Resource", Path.Combine(inputDir, inputDir + fileExt));


            var plugin    = ExtensionsLoader.GetPlugin();
            var modeler   = ExtensionsLoader.GetModeler();
            var codeModel = modeler.Build();

            // After swagger Parser
            codeModel = AutoRestController.RunExtensions(Trigger.AfterModelCreation, codeModel);

            // After swagger Parser
            codeModel = AutoRestController.RunExtensions(Trigger.BeforeLoadingLanguageSpecificModel, codeModel);

            using (plugin.Activate())
            {
                // load model into language-specific code model
                codeModel = plugin.Serializer.Load(codeModel);

                // we've loaded the model, run the extensions for after it's loaded
                codeModel = AutoRestController.RunExtensions(Trigger.AfterLoadingLanguageSpecificModel, codeModel);

                // apply language-specific tranformation (more than just language-specific types)
                // used to be called "NormalizeClientModel" .
                codeModel = plugin.Transformer.TransformCodeModel(codeModel);

                // next set of extensions
                codeModel = AutoRestController.RunExtensions(Trigger.AfterLanguageSpecificTransform, codeModel);

                // next set of extensions
                codeModel = AutoRestController.RunExtensions(Trigger.BeforeGeneratingCode, codeModel);

                // Generate code from CodeModel.
                plugin.CodeGenerator.Generate(codeModel).GetAwaiter().GetResult();
            }

            return(fileSystem);
        }
Example #14
0
        internal static MemoryFileSystem GenerateCodeInto(this string testName, MemoryFileSystem inputFileSystem, Settings settings)
        {
            Settings.Instance.FileSystemInput = inputFileSystem;
            // copy the whole input directory into the memoryfilesystem.
            inputFileSystem.CopyFolder("Resource", testName, "");

            // find the appropriately named .yaml or .json file for the swagger.
            foreach (var ext in new[] { ".yaml", ".json", ".md" })
            {
                var name = testName + ext;
                if (inputFileSystem.FileExists(name))
                {
                    settings.Input = name;
                }
            }

            if (string.IsNullOrWhiteSpace(settings.Input))
            {
                throw new Exception($"Can't find swagger file ${testName} [.yaml] [.json] [.md]");
            }

            var plugin    = ExtensionsLoader.GetPlugin();
            var modeler   = ExtensionsLoader.GetModeler();
            var codeModel = modeler.Build();

            using (plugin.Activate())
            {
                // load model into language-specific code model
                codeModel = plugin.Serializer.Load(codeModel);

                // apply language-specific tranformation (more than just language-specific types)
                // used to be called "NormalizeClientModel" .
                codeModel = plugin.Transformer.TransformCodeModel(codeModel);

                // Generate code from CodeModel.
                plugin.CodeGenerator.Generate(codeModel).GetAwaiter().GetResult();

                return(settings.FileSystemOutput);
            }
        }
Example #15
0
        public void TestSettingsFromSwagger()
        {
            using (NewContext)
            {
                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();
                var client  = modeler.Build();
                var plugin  = ExtensionsLoader.GetPlugin() as PluginCs;
                Assert.NotNull(plugin);
                settings.Validate();

                Assert.Equal("MIT", settings.Header);
                Assert.Equal(true, plugin.Settings.InternalConstructors);
            }
        }
Example #16
0
        private static MemoryFileSystem GenerateCodeInto(MemoryFileSystem fileSystem, Settings settings)
        {
            var plugin    = ExtensionsLoader.GetPlugin();
            var modeler   = ExtensionsLoader.GetModeler();
            var codeModel = modeler.Build();

            // After swagger Parser
            codeModel = AutoRestController.RunExtensions(Trigger.AfterModelCreation, codeModel);

            // After swagger Parser
            codeModel = AutoRestController.RunExtensions(Trigger.BeforeLoadingLanguageSpecificModel, codeModel);

            using (plugin.Activate())
            {
                // load model into language-specific code model
                codeModel = plugin.Serializer.Load(codeModel);

                // we've loaded the model, run the extensions for after it's loaded
                codeModel = AutoRestController.RunExtensions(Trigger.AfterLoadingLanguageSpecificModel, codeModel);

                // apply language-specific tranformation (more than just language-specific types)
                // used to be called "NormalizeClientModel" .
                codeModel = plugin.Transformer.TransformCodeModel(codeModel);

                // next set of extensions
                codeModel = AutoRestController.RunExtensions(Trigger.AfterLanguageSpecificTransform, codeModel);

                // next set of extensions
                codeModel = AutoRestController.RunExtensions(Trigger.BeforeGeneratingCode, codeModel);

                // Generate code from CodeModel.
                plugin.CodeGenerator.Generate(codeModel).GetAwaiter().GetResult();
            }

            return(fileSystem);
        }
        public void InvalidJsonFileThrowsException()
        {
            using (NewContext)
            {
                var settings = new Settings {
                    CodeGenerator = "JavaScript", FileSystem = _fileSystem
                };

                _fileSystem.WriteFile("AutoRest.json", "{'foo': 'bar'}");
                AssertThrows <CodeGenerationException>(() => ExtensionsLoader.GetPlugin(),
                                                       $"Plugin {"JavaScript"} does not have an assembly name in AutoRest.json");
            }

            using (NewContext)
            {
                new Settings {
                    CodeGenerator = "JavaScript", FileSystem = _fileSystem
                };
                _fileSystem.WriteFile("AutoRest.json", "{'foo': ");
                AssertThrows <CodeGenerationException>(
                    () => ExtensionsLoader.GetPlugin(),
                    "Error parsing AutoRest.json file");
            }
        }
Example #18
0
    protected override async Task <bool> ProcessInternal()
    {
        // get internal name
        var language = new[] {
            "CSharp",
            "Ruby",
            "NodeJS",
            "Python",
            "Go",
            "Java",
            "AzureResourceSchema"
        }
        .Where(x => x.ToLowerInvariant() == codeGenerator)
        .FirstOrDefault();

        if (language == null)
        {
            throw new Exception($"Language '{codeGenerator}' unknown.");
        }

        // build settings
        new Settings
        {
            Namespace  = await GetValue("namespace") ?? "",
            ClientName = await GetValue("override-client-name"),
            PayloadFlatteningThreshold = await GetValue <int?>("payload-flattening-threshold") ?? 0,
            AddCredentials             = await GetValue <bool?>("add-credentials") ?? false,
        };
        var header = await GetValue("license-header");

        if (header != null)
        {
            Settings.Instance.Header = header;
        }
        Settings.Instance.CustomSettings.Add("InternalConstructors", await GetValue <bool?>("use-internal-constructors") ?? false);
        Settings.Instance.CustomSettings.Add("SyncMethods", await GetValue("sync-methods") ?? "essential");
        Settings.Instance.CustomSettings.Add("UseDateTimeOffset", await GetValue <bool?>("use-datetimeoffset") ?? false);
        if (codeGenerator == "ruby" || codeGenerator == "python")
        {
            // TODO: sort out matters here entirely instead of relying on Input being read somewhere...
            var inputFile = await GetValue <string[]>("input-file");

            Settings.Instance.Input       = (inputFile as string[]).FirstOrDefault();
            Settings.Instance.PackageName = await GetValue("package-name");

            Settings.Instance.PackageVersion = await GetValue("package-version");
        }

        // process
        var files = await ListInputs();

        if (files.Length != 1)
        {
            return(false);
        }

        var plugin = ExtensionsLoader.GetPlugin(
            (await GetValue <bool?>("azure-arm") ?? false ? "Azure." : "") +
            language +
            (await GetValue <bool?>("fluent") ?? false ? ".Fluent" : ""));
        var modelAsJson = (await ReadFile(files[0])).EnsureYamlIsJson();

        using (plugin.Activate())
        {
            var codeModel = plugin.Serializer.Load(modelAsJson);
            codeModel = plugin.Transformer.TransformCodeModel(codeModel);
            plugin.CodeGenerator.Generate(codeModel).GetAwaiter().GetResult();
        }

        // write out files
        var outFS    = Settings.Instance.FileSystemOutput;
        var outFiles = outFS.GetFiles("", "*", System.IO.SearchOption.AllDirectories);

        foreach (var outFile in outFiles)
        {
            WriteFile(outFile, outFS.ReadAllText(outFile), null);
        }

        return(true);
    }
Example #19
0
    protected override async Task <bool> ProcessInternal()
    {
        var files = await ListInputs();

        if (files.Length != 2)
        {
            throw new Exception($"Generator received incorrect number of inputs: ${files.Length} : {files.Aggregate("", (c,e)=> c+=","+e)}");
        }

        var sd = Singleton <ServiceDefinition> .Instance = SwaggerParser.Parse("", await ReadFile(files[0]));

        // get internal name
        var language = new[] {
            "CSharp",
            "Ruby",
            "NodeJS",
            "Python",
            "Go",
            "Java",
            "AzureResourceSchema",
            "JsonRpcClient"
        }
        .Where(x => x.ToLowerInvariant() == codeGenerator)
        .FirstOrDefault();

        if (language == null)
        {
            throw new Exception($"Language '{codeGenerator}' unknown.");
        }

        // build settings
        var altNamespace = (await GetValue <string[]>("input-file") ?? new[] { "" }).FirstOrDefault()?.Split('/').Last().Split('\\').Last().Split('.').First();

        new Settings
        {
            Namespace  = await GetValue("namespace"),
            ClientName = GetXmsCodeGenSetting <string>(sd, "name") ?? await GetValue("override-client-name"),
            PayloadFlatteningThreshold = GetXmsCodeGenSetting <int?>(sd, "ft") ?? await GetValue <int?>("payload-flattening-threshold") ?? 0,
            AddCredentials             = await GetValue <bool?>("add-credentials") ?? false,
        };
        var header = await GetValue("license-header");

        if (header != null)
        {
            Settings.Instance.Header = header;
        }
        Settings.Instance.CustomSettings.Add("InternalConstructors", GetXmsCodeGenSetting <bool?>(sd, "internalConstructors") ?? await GetValue <bool?>("use-internal-constructors") ?? false);
        Settings.Instance.CustomSettings.Add("SyncMethods", GetXmsCodeGenSetting <string>(sd, "syncMethods") ?? await GetValue("sync-methods") ?? "essential");
        Settings.Instance.CustomSettings.Add("UseDateTimeOffset", GetXmsCodeGenSetting <bool?>(sd, "useDateTimeOffset") ?? await GetValue <bool?>("use-datetimeoffset") ?? false);
        Settings.Instance.CustomSettings["ClientSideValidation"] = await GetValue <bool?>("client-side-validation") ?? false;

        if (codeGenerator == "ruby" || codeGenerator == "python")
        {
            // TODO: sort out matters here entirely instead of relying on Input being read somewhere...
            var inputFile = await GetValue <string[]>("input-file");

            Settings.Instance.Input       = inputFile.FirstOrDefault();
            Settings.Instance.PackageName = await GetValue("package-name");

            Settings.Instance.PackageVersion = await GetValue("package-version");
        }

        // process
        var plugin = ExtensionsLoader.GetPlugin(
            (await GetValue <bool?>("azure-arm") ?? false ? "Azure." : "") +
            language +
            (await GetValue <bool?>("fluent") ?? false ? ".Fluent" : "") +
            (await GetValue <bool?>("testgen") ?? false ? ".TestGen" : ""));
        var modelAsJson = (await ReadFile(files[1])).EnsureYamlIsJson();

        using (plugin.Activate())
        {
            Settings.Instance.Namespace = Settings.Instance.Namespace ?? CodeNamer.Instance.GetNamespaceName(altNamespace);
            var codeModel = plugin.Serializer.Load(modelAsJson);
            codeModel = plugin.Transformer.TransformCodeModel(codeModel);
            plugin.CodeGenerator.Generate(codeModel).GetAwaiter().GetResult();
        }

        // write out files
        var outFS    = Settings.Instance.FileSystemOutput;
        var outFiles = outFS.GetFiles("", "*", System.IO.SearchOption.AllDirectories);

        foreach (var outFile in outFiles)
        {
            WriteFile(outFile, outFS.ReadAllText(outFile), null);
        }

        return(true);
    }
        /// <summary>
        /// Generates client using provided settings.
        /// </summary>
        public static void Generate()
        {
            if (Settings.Instance == null)
            {
                throw new ArgumentNullException("settings");
            }
            Logger.Entries.Clear();
            Logger.LogInfo(Resources.AutoRestCore, Version);

            CodeModel codeModel = null;

            var modeler = ExtensionsLoader.GetModeler();

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

                // generate model from swagger
                codeModel = modeler.Build(out messages);

                // After swagger Parser
                codeModel = RunExtensions(Trigger.AfterModelCreation, codeModel);

                // After swagger Parser
                codeModel = RunExtensions(Trigger.BeforeLoadingLanguageSpecificModel, codeModel);

                foreach (var message in messages)
                {
                    Logger.Entries.Add(new LogEntry(message.Severity, message.ToString()));
                }

                if (messages.Any(entry => entry.Severity >= Settings.Instance.ValidationLevel))
                {
                    throw ErrorManager.CreateError(null, Resources.ErrorGeneratingClientModel, "Errors found during Swagger validation");
                }
            }
            catch (Exception exception)
            {
                throw ErrorManager.CreateError(exception, Resources.ErrorGeneratingClientModel, exception.Message);
            }

            var plugin = ExtensionsLoader.GetPlugin();

            Logger.WriteOutput(plugin.CodeGenerator.UsageInstructions);

            Settings.Instance.Validate();
            try
            {
                var genericSerializer = new ModelSerializer <CodeModel>();
                var modelAsJson       = genericSerializer.ToJson(codeModel);

                // ensure once we're doing language-specific work, that we're working
                // in context provided by the language-specific transformer.
                using (plugin.Activate())
                {
                    // load model into language-specific code model
                    codeModel = plugin.Serializer.Load(modelAsJson);

                    // we've loaded the model, run the extensions for after it's loaded
                    codeModel = RunExtensions(Trigger.AfterLoadingLanguageSpecificModel, codeModel);

                    // apply language-specific tranformation (more than just language-specific types)
                    // used to be called "NormalizeClientModel" .
                    codeModel = plugin.Transformer.TransformCodeModel(codeModel);

                    // next set of extensions
                    codeModel = RunExtensions(Trigger.AfterLanguageSpecificTransform, codeModel);


                    // next set of extensions
                    codeModel = RunExtensions(Trigger.BeforeGeneratingCode, codeModel);

                    // Generate code from CodeModel.
                    plugin.CodeGenerator.Generate(codeModel).GetAwaiter().GetResult();
                }
            }
            catch (Exception exception)
            {
                throw ErrorManager.CreateError(exception, Resources.ErrorSavingGeneratedCode, exception.Message);
            }
        }
Example #21
0
        /// <summary>
        /// Generates client using provided settings.
        /// </summary>
        public static void Generate()
        {
            if (Settings.Instance == null)
            {
                throw new ArgumentNullException("settings");
            }
            Logger.Instance.Log(Category.Info, Resources.AutoRestCore, Version);

            CodeModel codeModel = null;

            var modeler = ExtensionsLoader.GetModeler();

            try
            {
                using (NewContext)
                {
                    bool validationErrorFound = false;
                    Logger.Instance.AddListener(new SignalingLogListener(Settings.Instance.ValidationLevel, _ => validationErrorFound = true));

                    // generate model from swagger
                    codeModel = modeler.Build();

                    if (validationErrorFound)
                    {
                        Logger.Instance.Log(Category.Error, "Errors found during Swagger validation");
                    }
                }
            }
            catch (Exception exception)
            {
                throw ErrorManager.CreateError(Resources.ErrorGeneratingClientModel, exception);
            }

            if (Settings.Instance.JsonValidationMessages)
            {
                return; // no code gen in Json validation mode
            }

            var plugin = ExtensionsLoader.GetPlugin();

            Console.ResetColor();

            try
            {
                var genericSerializer = new ModelSerializer <CodeModel>();
                var modelAsJson       = genericSerializer.ToJson(codeModel);

                // ensure once we're doing language-specific work, that we're working
                // in context provided by the language-specific transformer.
                using (plugin.Activate())
                {
                    // load model into language-specific code model
                    codeModel = plugin.Serializer.Load(modelAsJson);

                    // apply language-specific tranformation (more than just language-specific types)
                    // used to be called "NormalizeClientModel" .
                    codeModel = plugin.Transformer.TransformCodeModel(codeModel);

                    // Generate code from CodeModel.
                    plugin.CodeGenerator.Generate(codeModel).GetAwaiter().GetResult();
                }
            }
            catch (Exception exception)
            {
                throw ErrorManager.CreateError(Resources.ErrorSavingGeneratedCode, exception);
            }
        }