Ejemplo n.º 1
0
        public static async Task <bool> TryWriteFileOutputAsync(this IOutputCommand command, string path, IConsoleHost host, Func <string> generator)
        {
            if (!string.IsNullOrEmpty(path))
            {
                var directory = DynamicApis.PathGetDirectoryName(path);
                if (!string.IsNullOrEmpty(directory) && await DynamicApis.DirectoryExistsAsync(directory).ConfigureAwait(false) == false)
                {
                    await DynamicApis.DirectoryCreateDirectoryAsync(directory).ConfigureAwait(false);
                }

                var data = generator();
                if (!await DynamicApis.FileExistsAsync(path) || await DynamicApis.FileReadAllTextAsync(path) != data)
                {
                    await DynamicApis.FileWriteAllTextAsync(path, data).ConfigureAwait(false);

                    host?.WriteMessage("Code has been successfully written to file.\n");
                }
                else
                {
                    host?.WriteMessage("Code has been successfully generated but not written to file (no change detected).\n");
                }
                return(true);
            }
            return(false);
        }
Ejemplo n.º 2
0
        /// <summary>Loads an existing NSwagDocument.</summary>
        /// <typeparam name="TDocument">The type.</typeparam>
        /// <param name="filePath">The file path.</param>
        /// <param name="mappings">The mappings.</param>
        /// <returns>The document.</returns>
        protected static Task <TDocument> LoadAsync <TDocument>(string filePath, IDictionary <Type, Type> mappings)
            where TDocument : NSwagDocumentBase, new()
        {
            return(Task.Run(async() =>
            {
                var saveFile = false;
                var data = await DynamicApis.FileReadAllTextAsync(filePath).ConfigureAwait(false);
                data = TransformLegacyDocument(data, out saveFile); // TODO: Remove this legacy stuff later

                var settings = GetSerializerSettings();
                settings.ContractResolver = new BaseTypeMappingContractResolver(mappings);

                var document = JsonConvert.DeserializeObject <TDocument>(data, settings);
                document.Path = filePath;
                document.ConvertToAbsolutePaths();
                document._latestData = JsonConvert.SerializeObject(document, Formatting.Indented, GetSerializerSettings());

                if (saveFile)
                {
                    await document.SaveAsync();
                }

                return document;
            }));
        }
Ejemplo n.º 3
0
        private async Task TransformAsync(AssemblyLoader.AssemblyLoader assemblyLoader)
        {
            if (!string.IsNullOrEmpty(DocumentTemplate))
            {
                if (await DynamicApis.FileExistsAsync(DocumentTemplate).ConfigureAwait(false))
                {
                    Settings.DocumentTemplate = await DynamicApis.FileReadAllTextAsync(DocumentTemplate).ConfigureAwait(false);
                }
                else
                {
                    Settings.DocumentTemplate = DocumentTemplate;
                }

                if (!string.IsNullOrEmpty(Settings.DocumentTemplate) && !Settings.DocumentTemplate.StartsWith("{"))
                {
                    Settings.DocumentTemplate = (await SwaggerYamlDocument.FromYamlAsync(Settings.DocumentTemplate)).ToJson();
                }
            }
            else
            {
                Settings.DocumentTemplate = null;
            }

            if (DocumentProcessorTypes != null)
            {
                foreach (var p in DocumentProcessorTypes)
                {
                    var processor = (IDocumentProcessor)assemblyLoader.CreateInstance(p);
                    Settings.DocumentProcessors.Add(processor);
                }
            }

            if (OperationProcessorTypes != null)
            {
                foreach (var p in OperationProcessorTypes)
                {
                    var processor = (IOperationProcessor)assemblyLoader.CreateInstance(p);
                    Settings.OperationProcessors.Add(processor);
                }
            }

            if (!string.IsNullOrEmpty(TypeNameGeneratorType))
            {
                Settings.TypeNameGenerator = (ITypeNameGenerator)assemblyLoader.CreateInstance(TypeNameGeneratorType);
            }

            if (!string.IsNullOrEmpty(SchemaNameGeneratorType))
            {
                Settings.SchemaNameGenerator = (ISchemaNameGenerator)assemblyLoader.CreateInstance(SchemaNameGeneratorType);
            }
        }
Ejemplo n.º 4
0
        public async Task LoadSwaggerUrlAsync(string url)
        {
            var json = string.Empty;

            await RunTaskAsync(async() =>
            {
                json = url.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase) ||
                       url.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase) ?
                       await DynamicApis.HttpGetAsync(url) : await DynamicApis.FileReadAllTextAsync(url);
                json = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented);
            });

            Command.Swagger = json;
        }
        public async Task <string> RunAsync()
        {
            return(await Task.Run(async() =>
            {
                var additionalCode = ExtensionCode ?? string.Empty;
                if (await DynamicApis.FileExistsAsync(additionalCode).ConfigureAwait(false))
                {
                    additionalCode = await DynamicApis.FileReadAllTextAsync(additionalCode).ConfigureAwait(false);
                }
                Settings.TypeScriptGeneratorSettings.ExtensionCode = additionalCode;

                var document = await GetInputSwaggerDocument().ConfigureAwait(false);
                var clientGenerator = new SwaggerToTypeScriptClientGenerator(document, Settings);
                return clientGenerator.GenerateFile();
            }));
        }
Ejemplo n.º 6
0
        /// <summary>Loads an existing NSwagDocument.</summary>
        /// <typeparam name="TDocument">The type.</typeparam>
        /// <param name="filePath">The file path.</param>
        /// <param name="variables">The variables.</param>
        /// <param name="expandEnvironmentVariables">Specifies whether to expand environment variables.</param>
        /// <param name="mappings">The mappings.</param>
        /// <returns>The document.</returns>
        protected static Task <TDocument> LoadAsync <TDocument>(
            string filePath,
            string variables,
            bool expandEnvironmentVariables,
            IDictionary <Type, Type> mappings)
            where TDocument : NSwagDocumentBase, new()
        {
            return(Task.Run(async() =>
            {
                var saveFile = false;

                var data = await DynamicApis.FileReadAllTextAsync(filePath).ConfigureAwait(false);
                data = TransformLegacyDocument(data, out saveFile); // TODO: Remove this legacy stuff later

                if (expandEnvironmentVariables)
                {
                    data = Regex.Replace(Environment.ExpandEnvironmentVariables(data), "[^\\\\]\\\\[^\\\\]", p => p.Value.Replace("\\", "\\\\"));
                }

                foreach (var p in ConvertVariables(variables))
                {
                    data = data.Replace("$(" + p.Key + ")", p.Value);
                }

                var obj = JObject.Parse(data);
                if (obj["defaultVariables"] != null)
                {
                    var defaultVariables = obj["defaultVariables"].Value <string>();
                    foreach (var p in ConvertVariables(defaultVariables))
                    {
                        data = data.Replace("$(" + p.Key + ")", p.Value);
                    }
                }

                var settings = GetSerializerSettings();
                settings.ContractResolver = new BaseTypeMappingContractResolver(mappings);

                var document = FromJson <TDocument>(filePath, data);

                if (saveFile)
                {
                    await document.SaveAsync();
                }

                return document;
            }));
        }
Ejemplo n.º 7
0
        /// <exception cref="ArgumentException">The argument 'Input' was empty.</exception>
        protected async Task <string> GetInputJsonAsync()
        {
            var input = Input.ToString();

            if (string.IsNullOrEmpty(input))
            {
                throw new ArgumentException("The argument 'Input' was empty.");
            }

            if (IsJson(input))
            {
                return(input);
            }

            if (await DynamicApis.FileExistsAsync(input).ConfigureAwait(false))
            {
                return(await DynamicApis.FileReadAllTextAsync(input).ConfigureAwait(false));
            }

            return(await DynamicApis.HttpGetAsync(input).ConfigureAwait(false));
        }
Ejemplo n.º 8
0
        /// <summary>Loads a JSON Schema from a given file path (only available in .NET 4.x).</summary>
        /// <param name="filePath">The file path.</param>
        /// <param name="referenceResolverFactory">The JSON reference resolver factory.</param>
        /// <returns>The JSON Schema.</returns>
        /// <exception cref="NotSupportedException">The System.IO.File API is not available on this platform.</exception>
        public static async Task <JsonSchema4> FromFileAsync(string filePath, Func <JsonSchema4, JsonReferenceResolver> referenceResolverFactory)
        {
            var data = await DynamicApis.FileReadAllTextAsync(filePath);

            return(await FromJsonAsync(data, filePath, referenceResolverFactory).ConfigureAwait(false));
        }
Ejemplo n.º 9
0
        /// <summary>Creates a JSON Schema from a JSON file.</summary>
        /// <param name="filePath">The file path.</param>
        /// <returns>The <see cref="JsonSchema4" />.</returns>
        public static async Task <JsonSchema4> FromFileAsync(string filePath)
        {
            var data = await DynamicApis.FileReadAllTextAsync(filePath).ConfigureAwait(false);

            return(await FromYamlAsync(data, filePath).ConfigureAwait(false));
        }
Ejemplo n.º 10
0
        /// <summary>Creates a Swagger specification from a JSON file.</summary>
        /// <param name="filePath">The file path.</param>
        /// <returns>The <see cref="SwaggerDocument" />.</returns>
        public static async Task <SwaggerDocument> FromFileAsync(string filePath)
        {
            var data = await DynamicApis.FileReadAllTextAsync(filePath).ConfigureAwait(false);

            return(await FromJsonAsync(data, filePath).ConfigureAwait(false));
        }
Ejemplo n.º 11
0
        public async Task <SwaggerDocument> RunAsync()
        {
            return(await Task.Run(async() =>
            {
                if (!string.IsNullOrEmpty(DocumentTemplate))
                {
                    if (await DynamicApis.FileExistsAsync(DocumentTemplate).ConfigureAwait(false))
                    {
                        Settings.DocumentTemplate = await DynamicApis.FileReadAllTextAsync(DocumentTemplate).ConfigureAwait(false);
                    }
                    else
                    {
                        Settings.DocumentTemplate = DocumentTemplate;
                    }
                }
                else
                {
                    Settings.DocumentTemplate = null;
                }

                var generator = CreateGenerator();
                var controllerNames = ControllerNames.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList();
                if (!controllerNames.Any() && Settings.AssemblyPaths?.Length > 0)
                {
                    controllerNames = generator.GetControllerClasses().ToList();
                }

                var document = await generator.GenerateForControllersAsync(controllerNames).ConfigureAwait(false);

                if (ServiceHost == ".")
                {
                    document.Host = string.Empty;
                }
                else if (!string.IsNullOrEmpty(ServiceHost))
                {
                    document.Host = ServiceHost;
                }

                if (!string.IsNullOrEmpty(InfoTitle))
                {
                    document.Info.Title = InfoTitle;
                }
                if (!string.IsNullOrEmpty(InfoVersion))
                {
                    document.Info.Version = InfoVersion;
                }
                if (!string.IsNullOrEmpty(InfoDescription))
                {
                    document.Info.Description = InfoDescription;
                }

                if (ServiceSchemes != null && ServiceSchemes.Any())
                {
                    document.Schemes = ServiceSchemes.Select(s => (SwaggerSchema)Enum.Parse(typeof(SwaggerSchema), s, true)).ToList();
                }

                if (!string.IsNullOrEmpty(ServiceBasePath))
                {
                    document.BasePath = ServiceBasePath;
                }

                return document;
            }));
        }