From bb21002cedc374181edb36e769f82da73943bc3f Mon Sep 17 00:00:00 2001 From: Joe Feser Date: Wed, 7 Aug 2024 20:18:22 -0500 Subject: [PATCH] feat(): dotnet format using overrides Signed-off-by: Joe Feser --- src/ApiGenerator/CodeTemplatePage.cs | 8 +- .../Configuration/CodeConfiguration.cs | 80 ++++---- .../Configuration/GeneratorLocations.cs | 52 ++--- .../Overrides/EndpointOverridesBase.cs | 2 +- .../Overrides/GlobalOverrides.cs | 14 +- .../Overrides/IEndpointOverrides.cs | 8 +- .../Domain/ApiRequestParametersPatcher.cs | 44 ++--- src/ApiGenerator/Domain/Code/CsharpNames.cs | 16 +- .../HighLevel/Methods/FluentSyntaxBase.cs | 4 +- .../HighLevel/Methods/FluentSyntaxView.cs | 4 +- .../Code/HighLevel/Methods/HighLevelModel.cs | 2 +- .../HighLevel/Methods/InitializerMethod.cs | 4 +- .../Methods/InitializerSyntaxView.cs | 2 +- .../HighLevel/Methods/MethodSyntaxBase.cs | 8 +- .../Code/HighLevel/Requests/Constructor.cs | 50 ++--- .../HighLevel/Requests/RequestInterface.cs | 6 +- .../RequestParameterImplementation.cs | 2 +- src/ApiGenerator/Domain/Code/HttpMethod.cs | 42 ++-- .../Code/LowLevel/LowLevelClientMethod.cs | 18 +- src/ApiGenerator/Domain/RestApiSpec.cs | 6 +- .../Domain/Specification/ApiEndpoint.cs | 52 ++--- src/ApiGenerator/Domain/Specification/Body.cs | 2 +- .../Domain/Specification/Deprecation.cs | 20 +- .../Domain/Specification/QueryParameters.cs | 8 +- .../Domain/Specification/UrlInformation.cs | 14 +- .../Domain/Specification/UrlPart.cs | 20 +- .../Domain/Specification/UrlPath.cs | 16 +- src/ApiGenerator/Extensions.cs | 10 +- .../Generator/ApiEndpointFactory.cs | 6 +- src/ApiGenerator/Generator/ApiGenerator.cs | 187 +++++++++--------- src/ApiGenerator/Generator/CodeGenerator.cs | 2 +- .../Generator/Razor/DescriptorsGenerator.cs | 34 ++-- .../HighLevelClientImplementationGenerator.cs | 34 ++-- .../LowLevelClientImplementationGenerator.cs | 36 ++-- .../Razor/RequestParametersGenerator.cs | 32 +-- .../Generator/Razor/RequestsGenerator.cs | 24 +-- src/ApiGenerator/Program.cs | 6 - src/ApiGenerator/RestSpecDownloader.cs | 16 +- 38 files changed, 445 insertions(+), 446 deletions(-) diff --git a/src/ApiGenerator/CodeTemplatePage.cs b/src/ApiGenerator/CodeTemplatePage.cs index 62e88b6de3..221f3a3d90 100644 --- a/src/ApiGenerator/CodeTemplatePage.cs +++ b/src/ApiGenerator/CodeTemplatePage.cs @@ -33,10 +33,10 @@ namespace ApiGenerator; public abstract class CodeTemplatePage : TemplatePage { - protected new Task IncludeAsync(string key, object model = null) - => base.IncludeAsync(key.Replace('/', '.'), model); + protected new Task IncludeAsync(string key, object model = null) + => base.IncludeAsync(key.Replace('/', '.'), model); - protected async Task IncludeLegacyGeneratorNotice() => await IncludeAsync("GeneratorNotice", true); + protected async Task IncludeLegacyGeneratorNotice() => await IncludeAsync("GeneratorNotice", true); - protected async Task IncludeGeneratorNotice() => await IncludeAsync("GeneratorNotice", false); + protected async Task IncludeGeneratorNotice() => await IncludeAsync("GeneratorNotice", false); } diff --git a/src/ApiGenerator/Configuration/CodeConfiguration.cs b/src/ApiGenerator/Configuration/CodeConfiguration.cs index 00cd565c42..814b3c211b 100644 --- a/src/ApiGenerator/Configuration/CodeConfiguration.cs +++ b/src/ApiGenerator/Configuration/CodeConfiguration.cs @@ -36,31 +36,31 @@ namespace ApiGenerator.Configuration { public static class CodeConfiguration - { - private static readonly Glob[] OperationsToInclude = - { - new("{create,delete}_pit"), - new("{delete,get}_all_pits"), + { + private static readonly Glob[] OperationsToInclude = + { + new("{create,delete}_pit"), + new("{delete,get}_all_pits"), - new("cat.*"), - new("cluster.*"), - new("dangling_indices.*"), + new("cat.*"), + new("cluster.*"), + new("dangling_indices.*"), - new("indices.{delete,exists,get,put}_index_template"), + new("indices.{delete,exists,get,put}_index_template"), - new("ingest.*"), + new("ingest.*"), new("nodes.*"), - new("snapshot.*"), - new("tasks.*") - }; + new("snapshot.*"), + new("tasks.*") + }; - public static bool IncludeOperation(string name) => OperationsToInclude.Any(g => g.IsMatch(name)); + public static bool IncludeOperation(string name) => OperationsToInclude.Any(g => g.IsMatch(name)); - /// + /// /// Map API default names for API's we are only supporting on the low level client first /// private static readonly Dictionary LowLevelApiNameMapping = new() - { + { }; /// @@ -69,10 +69,10 @@ public static class CodeConfiguration /// public static readonly Dictionary HighLevelApiNameMapping = (from f in new DirectoryInfo(GeneratorLocations.OpenSearchClientFolder).GetFiles("*.cs", SearchOption.AllDirectories) - let contents = File.ReadAllText(f.FullName) - let c = Regex.Replace(contents, @"^.+\[MapsApi\(""([^ \r\n]+)""\)\].*$", "$1", RegexOptions.Singleline) - where !c.Contains(" ") //filter results that did not match - select new { Value = f.Name.Replace("Request", ""), Key = c.Replace(".json", "") }) + let contents = File.ReadAllText(f.FullName) + let c = Regex.Replace(contents, @"^.+\[MapsApi\(""([^ \r\n]+)""\)\].*$", "$1", RegexOptions.Singleline) + where !c.Contains(" ") //filter results that did not match + select new { Value = f.Name.Replace("Request", ""), Key = c.Replace(".json", "") }) .DistinctBy(v => v.Key) .ToDictionary(k => k.Key, v => v.Value.Replace(".cs", "")); @@ -84,7 +84,7 @@ public static bool IsNewHighLevelApi(string apiFileName) => public static bool IgnoreHighLevelApi(string apiFileName) { - //always generate already mapped requests + //always generate already mapped requests if (HighLevelApiNameMapping.ContainsKey(apiFileName.Replace(".json", ""))) return false; @@ -119,20 +119,20 @@ public static Dictionary ApiNameMapping /// public static readonly Dictionary ResponseBuilderInClientCalls = (from f in new DirectoryInfo(GeneratorLocations.OpenSearchClientFolder).GetFiles("*.cs", SearchOption.AllDirectories) - from l in File.ReadLines(f.FullName) - where Regex.IsMatch(l, ResponseBuilderAttributeRegex) - let c = Regex.Replace(l, @"^.+\[ResponseBuilderWithGeneric\(""([^ \r\n]+)""\)\].*$", "$1", RegexOptions.Singleline) - select new { Key = f.Name.Replace(".cs", ""), Value = c }) + from l in File.ReadLines(f.FullName) + where Regex.IsMatch(l, ResponseBuilderAttributeRegex) + let c = Regex.Replace(l, @"^.+\[ResponseBuilderWithGeneric\(""([^ \r\n]+)""\)\].*$", "$1", RegexOptions.Singleline) + select new { Key = f.Name.Replace(".cs", ""), Value = c }) .DistinctBy(v => v.Key) .ToDictionary(k => k.Key, v => v.Value); public static readonly Dictionary DescriptorGenericsLookup = (from f in new DirectoryInfo(GeneratorLocations.OpenSearchClientFolder).GetFiles("*Request.cs", SearchOption.AllDirectories) - let name = Path.GetFileNameWithoutExtension(f.Name).Replace("Request", "") - let contents = File.ReadAllText(f.FullName) - let c = Regex.Replace(contents, $@"^.+class ({name}Descriptor(?:<[^>\r\n]+>)?[^ \r\n]*).*$", "$1", RegexOptions.Singleline) - let key = $"{name}Descriptor" - select new { Key = key, Value = Regex.Replace(c, @"^.*?(?:(\<.+>).*?)?$", "$1") }) + let name = Path.GetFileNameWithoutExtension(f.Name).Replace("Request", "") + let contents = File.ReadAllText(f.FullName) + let c = Regex.Replace(contents, $@"^.+class ({name}Descriptor(?:<[^>\r\n]+>)?[^ \r\n]*).*$", "$1", RegexOptions.Singleline) + let key = $"{name}Descriptor" + select new { Key = key, Value = Regex.Replace(c, @"^.*?(?:(\<.+>).*?)?$", "$1") }) .DistinctBy(v => v.Key) .OrderBy(v => v.Key) .ToDictionary(k => k.Key, v => v.Value); @@ -142,16 +142,16 @@ where Regex.IsMatch(l, ResponseBuilderAttributeRegex) // find all files in OSC ending with Request.cs from f in new DirectoryInfo(GeneratorLocations.OpenSearchClientFolder).GetFiles("*Request.cs", SearchOption.AllDirectories) from l in File.ReadLines(f.FullName) - // attempt to locate all Request interfaces lines + // attempt to locate all Request interfaces lines where Regex.IsMatch(l, @"^.+interface [^ \r\n]+Request") //grab the interface name including any generics declared on it let c = Regex.Replace(l, @"^.+interface ([^ \r\n]+Request(?:<[^>\r\n]+>)?[^ \r\n]*).*$", "$1", RegexOptions.Singleline) where c.StartsWith("I") && c.Contains("Request") let request = Regex.Replace(c, "<.*$", "") let generics = Regex.Replace(c, @"^.*?(?:(\<.+>).*?)?$", "$1") - select Tuple.Create(request, generics) + select Tuple.Create(request, generics) ) - .OrderBy(v=>v.Item1) + .OrderBy(v => v.Item1) .ToList(); public static readonly HashSet GenericOnlyInterfaces = new HashSet(AllKnownRequestInterfaces @@ -164,7 +164,7 @@ select Tuple.Create(request, generics) // find all files in OSC ending with Request.cs from f in new DirectoryInfo(GeneratorLocations.OpenSearchClientFolder).GetFiles("*Request.cs", SearchOption.AllDirectories) from l in File.ReadLines(f.FullName) - // attempt to locate all Request interfaces lines + // attempt to locate all Request interfaces lines where Regex.IsMatch(l, @"^.+interface [^ \r\n]+Request") where l.Contains("IDocumentRequest") let c = Regex.Replace(l, @"^.+interface ([^ \r\n]+Request(?:<[^>\r\n]+>)?[^ \r\n]*).*$", "$1", RegexOptions.Singleline) @@ -189,8 +189,8 @@ where Regex.IsMatch(l, re) public static readonly Dictionary RequestInterfaceGenericsLookup = AllKnownRequestInterfaces - .GroupBy(v=>v.Item1) - .Select(g=>g.Last()) + .GroupBy(v => v.Item1) + .Select(g => g.Last()) .ToDictionary(k => k.Item1, v => v.Item2); /// @@ -213,17 +213,17 @@ where Regex.IsMatch(l, re) // find all files in OSC ending with Request.cs from f in new DirectoryInfo(GeneratorLocations.OpenSearchClientFolder).GetFiles("*Response.cs", SearchOption.AllDirectories) from l in File.ReadLines(f.FullName) - // attempt to locate all Response class lines + // attempt to locate all Response class lines where Regex.IsMatch(l, @"^.+public class [^ \r\n]+Response") //grab the response name including any generics declared on it let c = Regex.Replace(l, @"^.+public class ([^ \r\n]+Response(?:<[^>\r\n]+>)?[^ \r\n]*).*$", "$1", RegexOptions.Singleline) where c.Contains("Response") let response = Regex.Replace(c, "<.*$", "") let generics = Regex.Replace(c, @"^.*?(?:(\<.+>).*?)?$", "$1") - select (response, (response, generics)) + select (response, (response, generics)) ) - .Concat(ResponseReroute.Select(kv=>(kv.Key, (kv.Value.Item1, kv.Value.Item2)))) - .ToDictionary(t=>t.Item1, t=>t.Item2)); + .Concat(ResponseReroute.Select(kv => (kv.Key, (kv.Value.Item1, kv.Value.Item2)))) + .ToDictionary(t => t.Item1, t => t.Item2)); } } diff --git a/src/ApiGenerator/Configuration/GeneratorLocations.cs b/src/ApiGenerator/Configuration/GeneratorLocations.cs index 8032c3df93..21e7b3ab0c 100644 --- a/src/ApiGenerator/Configuration/GeneratorLocations.cs +++ b/src/ApiGenerator/Configuration/GeneratorLocations.cs @@ -31,42 +31,42 @@ namespace ApiGenerator.Configuration { - public static class GeneratorLocations - { - public static string OpenApiSpecFile { get; } = $"{Root}opensearch-openapi.yaml"; + public static class GeneratorLocations + { + public static string OpenApiSpecFile { get; } = $"{Root}opensearch-openapi.yaml"; - public static string OpenSearchNetFolder { get; } = $"{Root}../../src/OpenSearch.Net/"; + public static string OpenSearchNetFolder { get; } = $"{Root}../../src/OpenSearch.Net/"; - public static string OpenSearchClientFolder { get; } = $"{Root}../../src/OpenSearch.Client/"; + public static string OpenSearchClientFolder { get; } = $"{Root}../../src/OpenSearch.Client/"; - public static string LowLevelGeneratedFolder { get; } = $"{OpenSearchNetFolder}_Generated/"; + public static string LowLevelGeneratedFolder { get; } = $"{OpenSearchNetFolder}_Generated/"; - public static string HighLevelGeneratedFolder { get; } = $"{OpenSearchClientFolder}_Generated/"; + public static string HighLevelGeneratedFolder { get; } = $"{OpenSearchClientFolder}_Generated/"; - public static string HighLevel(params string[] paths) => HighLevelGeneratedFolder + string.Join("/", paths); + public static string HighLevel(params string[] paths) => HighLevelGeneratedFolder + string.Join("/", paths); - public static string LowLevel(params string[] paths) => LowLevelGeneratedFolder + string.Join("/", paths); + public static string LowLevel(params string[] paths) => LowLevelGeneratedFolder + string.Join("/", paths); - public static readonly Assembly Assembly = typeof(Generator.ApiGenerator).Assembly; + public static readonly Assembly Assembly = typeof(Generator.ApiGenerator).Assembly; - private static string _root; + private static string _root; - public static string Root - { - get - { - if (_root != null) return _root; + public static string Root + { + get + { + if (_root != null) return _root; - var directoryInfo = new DirectoryInfo(Directory.GetCurrentDirectory()); + var directoryInfo = new DirectoryInfo(Directory.GetCurrentDirectory()); - var dotnetRun = - directoryInfo.Name == "ApiGenerator" && - directoryInfo.Parent != null && - directoryInfo.Parent.Name == "src"; + var dotnetRun = + directoryInfo.Name == "ApiGenerator" && + directoryInfo.Parent != null && + directoryInfo.Parent.Name == "src"; - _root = dotnetRun ? "" : "../../../"; - return _root; - } - } - } + _root = dotnetRun ? "" : "../../../"; + return _root; + } + } + } } diff --git a/src/ApiGenerator/Configuration/Overrides/EndpointOverridesBase.cs b/src/ApiGenerator/Configuration/Overrides/EndpointOverridesBase.cs index db2f891293..ff40eba40c 100644 --- a/src/ApiGenerator/Configuration/Overrides/EndpointOverridesBase.cs +++ b/src/ApiGenerator/Configuration/Overrides/EndpointOverridesBase.cs @@ -33,7 +33,7 @@ namespace ApiGenerator.Configuration.Overrides { public abstract class EndpointOverridesBase : IEndpointOverrides { - public virtual IDictionary RenameUrlParts { get; } = new SortedDictionary(); + public virtual IDictionary RenameUrlParts { get; } = new SortedDictionary(); public virtual IDictionary ObsoleteQueryStringParams { get; set; } = new SortedDictionary(); diff --git a/src/ApiGenerator/Configuration/Overrides/GlobalOverrides.cs b/src/ApiGenerator/Configuration/Overrides/GlobalOverrides.cs index f543df3231..bb13018f27 100644 --- a/src/ApiGenerator/Configuration/Overrides/GlobalOverrides.cs +++ b/src/ApiGenerator/Configuration/Overrides/GlobalOverrides.cs @@ -31,15 +31,15 @@ namespace ApiGenerator.Configuration.Overrides { public class GlobalOverrides : EndpointOverridesBase - { - public static readonly GlobalOverrides Instance = new(); + { + public static readonly GlobalOverrides Instance = new(); - private GlobalOverrides() { } + private GlobalOverrides() { } - public IDictionary RenameEnums { get; } = new Dictionary - { - { "ExpandWildcard", "ExpandWildcards" } - }; + public IDictionary RenameEnums { get; } = new Dictionary + { + { "ExpandWildcard", "ExpandWildcards" } + }; public override IDictionary ObsoleteQueryStringParams { get; set; } = new Dictionary { diff --git a/src/ApiGenerator/Configuration/Overrides/IEndpointOverrides.cs b/src/ApiGenerator/Configuration/Overrides/IEndpointOverrides.cs index 82946907db..f4a54b9ffb 100644 --- a/src/ApiGenerator/Configuration/Overrides/IEndpointOverrides.cs +++ b/src/ApiGenerator/Configuration/Overrides/IEndpointOverrides.cs @@ -35,10 +35,10 @@ namespace ApiGenerator.Configuration.Overrides /// public interface IEndpointOverrides { - /// - /// Override how the url part is exposed to the client. - /// - IDictionary RenameUrlParts { get; } + /// + /// Override how the url part is exposed to the client. + /// + IDictionary RenameUrlParts { get; } /// /// A map of key -> obsolete message for properties in the spec that should not be used any longer diff --git a/src/ApiGenerator/Domain/ApiRequestParametersPatcher.cs b/src/ApiGenerator/Domain/ApiRequestParametersPatcher.cs index 94eba43012..b368d56add 100644 --- a/src/ApiGenerator/Domain/ApiRequestParametersPatcher.cs +++ b/src/ApiGenerator/Domain/ApiRequestParametersPatcher.cs @@ -36,22 +36,22 @@ namespace ApiGenerator.Domain { public static class ApiRequestParametersPatcher { - public static void PatchUrlPaths(string endpointName, IList source, IEndpointOverrides overrides) - { - var declaredKeys = source.SelectMany(p => p.Parts).Select(p => p.Name).ToHashSet(); - var renameLookup = CreateUrlPartRenameLookup(overrides, declaredKeys); - - foreach (var path in source) - { - foreach (var part in path.Parts) - { - if (!renameLookup.TryGetValue(part.Name, out var newName)) continue; - - path.Path = path.Path.Replace($"{{{part.Name}}}", $"{{{newName}}}"); - part.Name = newName; - } - } - } + public static void PatchUrlPaths(string endpointName, IList source, IEndpointOverrides overrides) + { + var declaredKeys = source.SelectMany(p => p.Parts).Select(p => p.Name).ToHashSet(); + var renameLookup = CreateUrlPartRenameLookup(overrides, declaredKeys); + + foreach (var path in source) + { + foreach (var part in path.Parts) + { + if (!renameLookup.TryGetValue(part.Name, out var newName)) continue; + + path.Path = path.Path.Replace($"{{{part.Name}}}", $"{{{newName}}}"); + part.Name = newName; + } + } + } public static SortedDictionary PatchQueryParameters( string endpointName, @@ -69,7 +69,7 @@ IEndpointOverrides overrides var patchedParams = new SortedDictionary(); foreach (var (queryStringKey, value) in source) { - value.QueryStringKey = queryStringKey; + value.QueryStringKey = queryStringKey; if (!renameLookup.TryGetValue(queryStringKey, out var preferredName)) preferredName = queryStringKey; @@ -84,7 +84,7 @@ IEndpointOverrides overrides //make sure source_enabled takes a boolean only if (preferredName == "source_enabled") value.Type = "boolean"; - patchedParams[preferredName] = value; + patchedParams[preferredName] = value; } return patchedParams; @@ -97,8 +97,8 @@ private static string CreateCSharpName(string queryStringKey, string endpointNam if (queryStringKey == "format" && endpointName == "text_structure.find_structure") return "TextStructureFindStructureFormat"; - return queryStringKey.ToPascalCase(); - } + return queryStringKey.ToPascalCase(); + } private static IList CreateSkipList(IEndpointOverrides local, ICollection declaredKeys) => CreateList(local, "skip", e => e.SkipQueryStringParams, declaredKeys); @@ -142,8 +142,8 @@ Func> @from, ICollection declare return list.Distinct().ToList(); } - private static IDictionary CreateUrlPartRenameLookup(IEndpointOverrides local, ICollection declaredKeys) => - CreateLookup(local, "url_part_rename", e => e.RenameUrlParts, declaredKeys); + private static IDictionary CreateUrlPartRenameLookup(IEndpointOverrides local, ICollection declaredKeys) => + CreateLookup(local, "url_part_rename", e => e.RenameUrlParts, declaredKeys); private static IDictionary CreateRenameLookup(IEndpointOverrides local, ICollection declaredKeys) => CreateLookup(local, "rename", e => e.RenameQueryStringParams, declaredKeys); diff --git a/src/ApiGenerator/Domain/Code/CsharpNames.cs b/src/ApiGenerator/Domain/Code/CsharpNames.cs index ea9b23d2ea..2e7a405d1b 100644 --- a/src/ApiGenerator/Domain/Code/CsharpNames.cs +++ b/src/ApiGenerator/Domain/Code/CsharpNames.cs @@ -158,7 +158,7 @@ public string PerPathMethodName(string path) //&& ResponseGenerics.FirstOrDefault() == DescriptorBoundDocumentGeneric ; public string DescriptorBoundDocumentGeneric => - HighLevelDescriptorMethodGenerics.FirstOrDefault(g=>g == "TDocument") ?? HighLevelDescriptorMethodGenerics.Last(); + HighLevelDescriptorMethodGenerics.FirstOrDefault(g => g == "TDocument") ?? HighLevelDescriptorMethodGenerics.Last(); public List HighLevelDescriptorMethodGenerics => DescriptorGenerics .Concat(ResponseGenerics) @@ -182,7 +182,7 @@ public static List SplitGeneric(string generic) => (generic ?? string.Em public string GenericResponseName => GenericsDeclaredOnResponse.IsNullOrEmpty() ? null : $"{ResponseName}{GenericsDeclaredOnResponse}"; public string GenericOrNonGenericDescriptorName => GenericDescriptorName ?? DescriptorName; - public string GenericOrNonGenericInterfaceName => GenericInterfaceName ?? RequestInterfaceName; + public string GenericOrNonGenericInterfaceName => GenericInterfaceName ?? RequestInterfaceName; public string GenericOrNonGenericResponseName { get @@ -206,11 +206,11 @@ public string GenericOrNonGenericResponseName public bool CustomResponseBuilderPerRequestOverride(out string call) => CodeConfiguration.ResponseBuilderInClientCalls.TryGetValue(RequestName, out call); - public static string GetEnumName(string schemaKey) - { - var enumName = schemaKey.Replace("_common", "").SplitPascalCase().ToPascalCase(); - if (GlobalOverrides.Instance.RenameEnums.TryGetValue(enumName, out var renamed)) enumName = renamed; - return enumName; - } + public static string GetEnumName(string schemaKey) + { + var enumName = schemaKey.Replace("_common", "").SplitPascalCase().ToPascalCase(); + if (GlobalOverrides.Instance.RenameEnums.TryGetValue(enumName, out var renamed)) enumName = renamed; + return enumName; + } } } diff --git a/src/ApiGenerator/Domain/Code/HighLevel/Methods/FluentSyntaxBase.cs b/src/ApiGenerator/Domain/Code/HighLevel/Methods/FluentSyntaxBase.cs index e3f9d02765..14cfd1a9d4 100644 --- a/src/ApiGenerator/Domain/Code/HighLevel/Methods/FluentSyntaxBase.cs +++ b/src/ApiGenerator/Domain/Code/HighLevel/Methods/FluentSyntaxBase.cs @@ -89,7 +89,7 @@ private List CreateDescriptorArgs(IReadOnlyCollection parts) parts.FirstOrDefault(p => p.Type == "list" && (p.Name == "index" || p.Name == "indices") && !willInferFromDocument), parts.FirstOrDefault(p => p.Name == "name"), }; - requiredParts = candidates.Where(p=>p!= null).Take(1).ToList(); + requiredParts = candidates.Where(p => p != null).Take(1).ToList(); } if (!willInferFromDocument) return requiredParts; @@ -134,7 +134,7 @@ public string SelectorArguments() string codeArgs = null; if (CodeConfiguration.DescriptorConstructors.TryGetValue(CsharpNames.DescriptorName, out codeArgs)) { - codeArgs = string.Join(", ", codeArgs.Split(',').Select(a=>a.Split(' ').Last())); + codeArgs = string.Join(", ", codeArgs.Split(',').Select(a => a.Split(' ').Last())); return codeArgs; } diff --git a/src/ApiGenerator/Domain/Code/HighLevel/Methods/FluentSyntaxView.cs b/src/ApiGenerator/Domain/Code/HighLevel/Methods/FluentSyntaxView.cs index 8d25af9807..1b79b6177d 100644 --- a/src/ApiGenerator/Domain/Code/HighLevel/Methods/FluentSyntaxView.cs +++ b/src/ApiGenerator/Domain/Code/HighLevel/Methods/FluentSyntaxView.cs @@ -26,11 +26,11 @@ * under the License. */ -namespace ApiGenerator.Domain.Code.HighLevel.Methods +namespace ApiGenerator.Domain.Code.HighLevel.Methods { public class FluentSyntaxView { - public FluentSyntaxView(FluentSyntaxBase syntax, bool async) => (Syntax , Async) = (syntax, async); + public FluentSyntaxView(FluentSyntaxBase syntax, bool async) => (Syntax, Async) = (syntax, async); public FluentSyntaxBase Syntax { get; } diff --git a/src/ApiGenerator/Domain/Code/HighLevel/Methods/HighLevelModel.cs b/src/ApiGenerator/Domain/Code/HighLevel/Methods/HighLevelModel.cs index 30693dbfd3..71e43b934b 100644 --- a/src/ApiGenerator/Domain/Code/HighLevel/Methods/HighLevelModel.cs +++ b/src/ApiGenerator/Domain/Code/HighLevel/Methods/HighLevelModel.cs @@ -26,7 +26,7 @@ * under the License. */ -namespace ApiGenerator.Domain.Code.HighLevel.Methods +namespace ApiGenerator.Domain.Code.HighLevel.Methods { public class HighLevelModel { diff --git a/src/ApiGenerator/Domain/Code/HighLevel/Methods/InitializerMethod.cs b/src/ApiGenerator/Domain/Code/HighLevel/Methods/InitializerMethod.cs index f0f048e494..761b81e624 100644 --- a/src/ApiGenerator/Domain/Code/HighLevel/Methods/InitializerMethod.cs +++ b/src/ApiGenerator/Domain/Code/HighLevel/Methods/InitializerMethod.cs @@ -48,8 +48,8 @@ public InitializerMethod(CsharpNames names, string link, string summary, Depreca public override string GenericWhereClause => string.Join(" ", CsharpNames.SplitGeneric(MethodGenerics) - .Where(g=>g.Contains("Document")) - .Select(g=>$"where {g} : class") + .Where(g => g.Contains("Document")) + .Select(g => $"where {g} : class") ); private bool IsCatMethod => CsharpNames.Namespace == "Cat"; diff --git a/src/ApiGenerator/Domain/Code/HighLevel/Methods/InitializerSyntaxView.cs b/src/ApiGenerator/Domain/Code/HighLevel/Methods/InitializerSyntaxView.cs index 8469d23544..5daa98a4c0 100644 --- a/src/ApiGenerator/Domain/Code/HighLevel/Methods/InitializerSyntaxView.cs +++ b/src/ApiGenerator/Domain/Code/HighLevel/Methods/InitializerSyntaxView.cs @@ -30,7 +30,7 @@ namespace ApiGenerator.Domain.Code.HighLevel.Methods { public class InitializerSyntaxView { - public InitializerSyntaxView(InitializerMethod syntax, bool async) => (Syntax , Async) = (syntax, async); + public InitializerSyntaxView(InitializerMethod syntax, bool async) => (Syntax, Async) = (syntax, async); public InitializerMethod Syntax { get; } diff --git a/src/ApiGenerator/Domain/Code/HighLevel/Methods/MethodSyntaxBase.cs b/src/ApiGenerator/Domain/Code/HighLevel/Methods/MethodSyntaxBase.cs index a0b1f329df..7ed6a61cb6 100644 --- a/src/ApiGenerator/Domain/Code/HighLevel/Methods/MethodSyntaxBase.cs +++ b/src/ApiGenerator/Domain/Code/HighLevel/Methods/MethodSyntaxBase.cs @@ -36,13 +36,13 @@ public abstract class MethodSyntaxBase protected MethodSyntaxBase(CsharpNames names, string link, string summary, Deprecation deprecated, Version versionAdded) => (CsharpNames, DocumentationLink, XmlDocSummary, Deprecated, VersionAdded) = (names, link, summary, deprecated, versionAdded); - public string DocumentationLink { get; } + public string DocumentationLink { get; } - public string XmlDocSummary { get; } + public string XmlDocSummary { get; } - public Deprecation Deprecated { get; } + public Deprecation Deprecated { get; } - public Version VersionAdded { get; set; } + public Version VersionAdded { get; set; } protected CsharpNames CsharpNames { get; } diff --git a/src/ApiGenerator/Domain/Code/HighLevel/Requests/Constructor.cs b/src/ApiGenerator/Domain/Code/HighLevel/Requests/Constructor.cs index fcf1562b36..7d9620bdd9 100644 --- a/src/ApiGenerator/Domain/Code/HighLevel/Requests/Constructor.cs +++ b/src/ApiGenerator/Domain/Code/HighLevel/Requests/Constructor.cs @@ -76,34 +76,34 @@ string generic if (url.IsPartless) return ctors; ctors.AddRange(from path in paths - let baseArgs = inheritsFromPlainRequestBase ? path.RequestBaseArguments : path.TypedSubClassBaseArguments - let constParams = path.ConstructorArguments - let generated = $"public {typeName}({constParams}) : base({baseArgs})" - select new Constructor - { - Parameterless = string.IsNullOrEmpty(constParams), - Generated = generated, - Description = path.GetXmlDocs(Indent), - //Body = isDocumentApi ? $" => Q(\"routing\", new Routing(() => AutoRouteDocument()));" : string.Empty - Body = string.Empty - }); + let baseArgs = inheritsFromPlainRequestBase ? path.RequestBaseArguments : path.TypedSubClassBaseArguments + let constParams = path.ConstructorArguments + let generated = $"public {typeName}({constParams}) : base({baseArgs})" + select new Constructor + { + Parameterless = string.IsNullOrEmpty(constParams), + Generated = generated, + Description = path.GetXmlDocs(Indent), + //Body = isDocumentApi ? $" => Q(\"routing\", new Routing(() => AutoRouteDocument()));" : string.Empty + Body = string.Empty + }); if (generateGeneric && !string.IsNullOrWhiteSpace(generic)) { ctors.AddRange(from path in paths.Where(path => path.HasResolvableArguments) - let baseArgs = path.AutoResolveBaseArguments(generic) - let constructorArgs = path.AutoResolveConstructorArguments - let baseOrThis = inheritsFromPlainRequestBase - ? "this" - : "base" - let generated = $"public {typeName}({constructorArgs}) : {baseOrThis}({baseArgs})" - select new Constructor - { - Parameterless = string.IsNullOrEmpty(constructorArgs), - Generated = generated, - Description = path.GetXmlDocs(Indent, skipResolvable: true), - Body = string.Empty - }); + let baseArgs = path.AutoResolveBaseArguments(generic) + let constructorArgs = path.AutoResolveConstructorArguments + let baseOrThis = inheritsFromPlainRequestBase + ? "this" + : "base" + let generated = $"public {typeName}({constructorArgs}) : {baseOrThis}({baseArgs})" + select new Constructor + { + Parameterless = string.IsNullOrEmpty(constructorArgs), + Generated = generated, + Description = path.GetXmlDocs(Indent, skipResolvable: true), + Body = string.Empty + }); if (url.TryGetDocumentApiPath(out var docPath)) { @@ -121,7 +121,7 @@ string generic } } var constructors = ctors.GroupBy(c => c.Generated.Split(new[] { ':' }, 2)[0]).Select(g => g.Last()).ToList(); - if (!constructors.Any(c=>c.Parameterless)) + if (!constructors.Any(c => c.Parameterless)) constructors.Add(new Constructor { Parameterless = true, diff --git a/src/ApiGenerator/Domain/Code/HighLevel/Requests/RequestInterface.cs b/src/ApiGenerator/Domain/Code/HighLevel/Requests/RequestInterface.cs index cd07352c91..20fdbc61d7 100644 --- a/src/ApiGenerator/Domain/Code/HighLevel/Requests/RequestInterface.cs +++ b/src/ApiGenerator/Domain/Code/HighLevel/Requests/RequestInterface.cs @@ -30,7 +30,7 @@ using ApiGenerator.Configuration; using ApiGenerator.Domain.Specification; -namespace ApiGenerator.Domain.Code.HighLevel.Requests +namespace ApiGenerator.Domain.Code.HighLevel.Requests { public class RequestInterface { @@ -42,9 +42,9 @@ public class RequestInterface /// implementations /// public IReadOnlyCollection PartialParameters { get; set; } - + public string OfficialDocumentationLink { get; set; } - + public CsharpNames CsharpNames { get; set; } private bool GenerateOnlyGenericInterface => CodeConfiguration.GenericOnlyInterfaces.Contains(CsharpNames.RequestInterfaceName); diff --git a/src/ApiGenerator/Domain/Code/HighLevel/Requests/RequestParameterImplementation.cs b/src/ApiGenerator/Domain/Code/HighLevel/Requests/RequestParameterImplementation.cs index e39ca7586d..2d4288a827 100644 --- a/src/ApiGenerator/Domain/Code/HighLevel/Requests/RequestParameterImplementation.cs +++ b/src/ApiGenerator/Domain/Code/HighLevel/Requests/RequestParameterImplementation.cs @@ -29,7 +29,7 @@ using System.Collections.Generic; using ApiGenerator.Domain.Specification; -namespace ApiGenerator.Domain.Code.HighLevel.Requests +namespace ApiGenerator.Domain.Code.HighLevel.Requests { public class RequestParameterImplementation { diff --git a/src/ApiGenerator/Domain/Code/HttpMethod.cs b/src/ApiGenerator/Domain/Code/HttpMethod.cs index 390aa1e7e1..1116f289db 100644 --- a/src/ApiGenerator/Domain/Code/HttpMethod.cs +++ b/src/ApiGenerator/Domain/Code/HttpMethod.cs @@ -9,34 +9,34 @@ namespace ApiGenerator.Domain.Code; public class HttpMethod { - public static readonly HttpMethod Delete = new("Delete", false); - public static readonly HttpMethod Get = new("Get", false); - public static readonly HttpMethod Head = new("Head", false); - public static readonly HttpMethod Patch = new("Patch", true); - public static readonly HttpMethod Post = new("Post", true); - public static readonly HttpMethod Put = new("Put", true); - public static readonly HttpMethod[] All = { Delete, Get, Head, Patch, Post, Put }; + public static readonly HttpMethod Delete = new("Delete", false); + public static readonly HttpMethod Get = new("Get", false); + public static readonly HttpMethod Head = new("Head", false); + public static readonly HttpMethod Patch = new("Patch", true); + public static readonly HttpMethod Post = new("Post", true); + public static readonly HttpMethod Put = new("Put", true); + public static readonly HttpMethod[] All = { Delete, Get, Head, Patch, Post, Put }; - private readonly string _method; + private readonly string _method; - private HttpMethod(string method, bool takesBody) - { - _method = method; - TakesBody = takesBody; - } + private HttpMethod(string method, bool takesBody) + { + _method = method; + TakesBody = takesBody; + } - public bool TakesBody { get; private set; } + public bool TakesBody { get; private set; } - // ReSharper disable once InconsistentNaming - public string IRequest => $"I{Request}"; + // ReSharper disable once InconsistentNaming + public string IRequest => $"I{Request}"; - public string Request => $"Http{_method}Request"; + public string Request => $"Http{_method}Request"; - public string RequestParameters => $"Http{_method}RequestParameters"; + public string RequestParameters => $"Http{_method}RequestParameters"; - public string Descriptor => $"Http{_method}Descriptor"; + public string Descriptor => $"Http{_method}Descriptor"; - public string MethodEnum => $"HttpMethod.{_method.ToUpperInvariant()}"; + public string MethodEnum => $"HttpMethod.{_method.ToUpperInvariant()}"; - public override string ToString() => _method; + public override string ToString() => _method; } diff --git a/src/ApiGenerator/Domain/Code/LowLevel/LowLevelClientMethod.cs b/src/ApiGenerator/Domain/Code/LowLevel/LowLevelClientMethod.cs index a81e269163..f0cb0f06b8 100644 --- a/src/ApiGenerator/Domain/Code/LowLevel/LowLevelClientMethod.cs +++ b/src/ApiGenerator/Domain/Code/LowLevel/LowLevelClientMethod.cs @@ -51,25 +51,25 @@ public class LowLevelClientMethod public IEnumerable Parts { get; set; } public string Path { get; set; } - public Version VersionAdded { get; set; } + public Version VersionAdded { get; set; } public string UrlInCode { get { - var url = Path.TrimStart('/'); + var url = Path.TrimStart('/'); var options = Url.AllPaths.SelectMany(p => p.Parts).Select(p => p.Name).Distinct(); var pattern = string.Join("|", options); var urlCode = $"\"{url}\""; - if (!Path.Contains('{')) return urlCode; + if (!Path.Contains('{')) return urlCode; - var patchedUrl = Regex.Replace(url, "{(" + pattern + ")}", m => - { - var arg = m.Groups[^1].Value.ToCamelCase(); - return $"{{{arg}:{arg}}}"; - }); - return $"Url($\"{patchedUrl}\")"; + var patchedUrl = Regex.Replace(url, "{(" + pattern + ")}", m => + { + var arg = m.Groups[^1].Value.ToCamelCase(); + return $"{{{arg}:{arg}}}"; + }); + return $"Url($\"{patchedUrl}\")"; } } diff --git a/src/ApiGenerator/Domain/RestApiSpec.cs b/src/ApiGenerator/Domain/RestApiSpec.cs index 47568fa6a2..6148cb6357 100644 --- a/src/ApiGenerator/Domain/RestApiSpec.cs +++ b/src/ApiGenerator/Domain/RestApiSpec.cs @@ -38,16 +38,16 @@ namespace ApiGenerator.Domain public class EnumDescription { public string Name { get; set; } - public bool IsFlag { get; set; } + public bool IsFlag { get; set; } public IEnumerable Options { get; set; } } public class RestApiSpec { - public ImmutableSortedDictionary Endpoints { get; set; } + public ImmutableSortedDictionary Endpoints { get; set; } public ImmutableSortedDictionary> EndpointsPerNamespaceLowLevel => - Endpoints.Values.GroupBy(e=>e.CsharpNames.Namespace) + Endpoints.Values.GroupBy(e => e.CsharpNames.Namespace) .ToImmutableSortedDictionary(kv => kv.Key, kv => kv.ToList().AsReadOnly()); public ImmutableSortedDictionary> EndpointsPerNamespaceHighLevel => diff --git a/src/ApiGenerator/Domain/Specification/ApiEndpoint.cs b/src/ApiGenerator/Domain/Specification/ApiEndpoint.cs index f22c15731f..778b029d3a 100644 --- a/src/ApiGenerator/Domain/Specification/ApiEndpoint.cs +++ b/src/ApiGenerator/Domain/Specification/ApiEndpoint.cs @@ -39,7 +39,7 @@ namespace ApiGenerator.Domain.Specification { public class ApiEndpoint { - /// The original name as declared in the spec + /// The original name as declared in the spec public string Name { get; set; } /// The original namespace as declared in the spec @@ -63,10 +63,10 @@ public class ApiEndpoint public IEndpointOverrides Overrides { get; internal set; } - private IEnumerable ParamsToGenerate => Url.Params.Values.Where(p => !p.Skip).OrderBy(p => p.ClsName); + private IEnumerable ParamsToGenerate => Url.Params.Values.Where(p => !p.Skip).OrderBy(p => p.ClsName); public RequestInterface RequestInterface => new() - { + { CsharpNames = CsharpNames, UrlParts = Url.Parts, PartialParameters = @@ -75,7 +75,7 @@ public class ApiEndpoint }; public RequestPartialImplementation RequestPartialImplementation => new() - { + { CsharpNames = CsharpNames, OfficialDocumentationLink = OfficialDocumentationLink?.Url, Stability = Stability, @@ -88,7 +88,7 @@ public class ApiEndpoint }; public DescriptorPartialImplementation DescriptorPartialImplementation => new() - { + { CsharpNames = CsharpNames, OfficialDocumentationLink = OfficialDocumentationLink?.Url, Constructors = Constructor.DescriptorConstructors(CsharpNames, Url).ToList(), @@ -99,7 +99,7 @@ public class ApiEndpoint }; public RequestParameterImplementation RequestParameterImplementation => new() - { + { CsharpNames = CsharpNames, OfficialDocumentationLink = OfficialDocumentationLink?.Url, Params = ParamsToGenerate.ToList(), @@ -118,30 +118,30 @@ public class ApiEndpoint public string HighLevelMethodXmlDocDescription => $"{PreferredHttpMethod} request to the {Name} API, read more about this API online:"; - private bool BodyIsOptional => Body is not { Required: true } || HttpMethods.Contains("GET"); + private bool BodyIsOptional => Body is not { Required: true } || HttpMethods.Contains("GET"); - private Deprecation Deprecated => - !Url.Paths.Any() && Url.AllPaths.Count > 0 - ? Url.DeprecatedPaths - .Select(p => p.Deprecation) - .MaxBy(d => d.Version) - : null; + private Deprecation Deprecated => + !Url.Paths.Any() && Url.AllPaths.Count > 0 + ? Url.DeprecatedPaths + .Select(p => p.Deprecation) + .MaxBy(d => d.Version) + : null; - private Version VersionAdded => - Url.AllPaths - .Select(p => p.VersionAdded) - .Where(v => v != null) - .Min(); + private Version VersionAdded => + Url.AllPaths + .Select(p => p.VersionAdded) + .Where(v => v != null) + .Min(); public HighLevelModel HighLevelModel => new() - { + { CsharpNames = CsharpNames, Fluent = new FluentMethod(CsharpNames, Url.Parts, selectorIsOptional: BodyIsOptional, link: OfficialDocumentationLink?.Url, summary: HighLevelMethodXmlDocDescription, - deprecated: Deprecated, - versionAdded: VersionAdded + deprecated: Deprecated, + versionAdded: VersionAdded ), FluentBound = !CsharpNames.DescriptorBindsOverMultipleDocuments ? null @@ -149,14 +149,14 @@ public class ApiEndpoint selectorIsOptional: BodyIsOptional, link: OfficialDocumentationLink?.Url, summary: HighLevelMethodXmlDocDescription, - deprecated: Deprecated, - versionAdded: VersionAdded + deprecated: Deprecated, + versionAdded: VersionAdded ), Initializer = new InitializerMethod(CsharpNames, link: OfficialDocumentationLink?.Url, summary: HighLevelMethodXmlDocDescription, - deprecated: Deprecated, - versionAdded: VersionAdded + deprecated: Deprecated, + versionAdded: VersionAdded ) }; @@ -210,7 +210,7 @@ public IReadOnlyCollection LowLevelClientMethods Parts = parts, Url = Url, HasBody = Body != null, - VersionAdded = path.VersionAdded, + VersionAdded = path.VersionAdded, }; _lowLevelClientMethods.Add(apiMethod); } diff --git a/src/ApiGenerator/Domain/Specification/Body.cs b/src/ApiGenerator/Domain/Specification/Body.cs index 02ed3081c3..c827857003 100644 --- a/src/ApiGenerator/Domain/Specification/Body.cs +++ b/src/ApiGenerator/Domain/Specification/Body.cs @@ -26,7 +26,7 @@ * under the License. */ -namespace ApiGenerator.Domain.Specification +namespace ApiGenerator.Domain.Specification { public class Body { diff --git a/src/ApiGenerator/Domain/Specification/Deprecation.cs b/src/ApiGenerator/Domain/Specification/Deprecation.cs index 96ac03c7d7..f2ee3828bf 100644 --- a/src/ApiGenerator/Domain/Specification/Deprecation.cs +++ b/src/ApiGenerator/Domain/Specification/Deprecation.cs @@ -30,16 +30,16 @@ namespace ApiGenerator.Domain.Specification; public class Deprecation { - public string Version { get; set; } + public string Version { get; set; } - public string Description { get; set; } + public string Description { get; set; } - public override string ToString() => - (!string.IsNullOrEmpty(Version), !string.IsNullOrEmpty(Description)) switch - { - (true, true) => $"Deprecated as of: {Version}, reason: {Description}", - (true, false) => $"Deprecated as of: {Version}", - (false, true) => $"reason: {Description}", - _ => "deprecated" - }; + public override string ToString() => + (!string.IsNullOrEmpty(Version), !string.IsNullOrEmpty(Description)) switch + { + (true, true) => $"Deprecated as of: {Version}, reason: {Description}", + (true, false) => $"Deprecated as of: {Version}", + (false, true) => $"reason: {Description}", + _ => "deprecated" + }; } diff --git a/src/ApiGenerator/Domain/Specification/QueryParameters.cs b/src/ApiGenerator/Domain/Specification/QueryParameters.cs index e0a11b35ea..1f3d24485a 100644 --- a/src/ApiGenerator/Domain/Specification/QueryParameters.cs +++ b/src/ApiGenerator/Domain/Specification/QueryParameters.cs @@ -46,7 +46,7 @@ public class QueryParameters public string Description { get; set; } - public Version VersionAdded { get; set; } + public Version VersionAdded { get; set; } public IEnumerable DescriptionHighLevel { @@ -99,9 +99,9 @@ public IEnumerable DescriptionHighLevel public string Obsolete { get => !string.IsNullOrEmpty(_obsolete) - ? _obsolete - : Deprecated?.ToString(); - set => _obsolete = value; + ? _obsolete + : Deprecated?.ToString(); + set => _obsolete = value; } public Deprecation Deprecated { get; set; } diff --git a/src/ApiGenerator/Domain/Specification/UrlInformation.cs b/src/ApiGenerator/Domain/Specification/UrlInformation.cs index 34f7c55591..284e7bdffd 100644 --- a/src/ApiGenerator/Domain/Specification/UrlInformation.cs +++ b/src/ApiGenerator/Domain/Specification/UrlInformation.cs @@ -37,16 +37,16 @@ public class UrlInformation { public IDictionary Params { get; set; } = new SortedDictionary(); - public IEnumerable Paths => AllPaths.Where(p => p.Deprecation == null); - public IEnumerable DeprecatedPaths => AllPaths.Where(p => p.Deprecation != null); + public IEnumerable Paths => AllPaths.Where(p => p.Deprecation == null); + public IEnumerable DeprecatedPaths => AllPaths.Where(p => p.Deprecation != null); - public IList AllPaths = new List(); + public IList AllPaths = new List(); public IReadOnlyCollection Parts => Paths - .SelectMany(p => p.Parts) - .DistinctBy(p => p.Name) - .OrderBy(p => p.Name) - .ToList(); + .SelectMany(p => p.Parts) + .DistinctBy(p => p.Name) + .OrderBy(p => p.Name) + .ToList(); public bool IsPartless => !Parts.Any(); diff --git a/src/ApiGenerator/Domain/Specification/UrlPart.cs b/src/ApiGenerator/Domain/Specification/UrlPart.cs index 4f3450af85..bb0ba5ffce 100644 --- a/src/ApiGenerator/Domain/Specification/UrlPart.cs +++ b/src/ApiGenerator/Domain/Specification/UrlPart.cs @@ -137,21 +137,21 @@ public string Description } public string InterfaceName => - Name switch - { - "repository" => "RepositoryName", - _ => Name.ToPascalCase() - }; + Name switch + { + "repository" => "RepositoryName", + _ => Name.ToPascalCase() + }; - public string Name { get; set; } + public string Name { get; set; } public string NameAsArgument => Name.ToCamelCase(); public bool Required { get; set; } public bool Deprecated { get; set; } public string Type { get; set; } private static string CleanUpDescription(string value) => - string.IsNullOrWhiteSpace(value) - ? value - : value.Replace("use `_all` or empty string", "use the special string `_all` or Indices.All"); - } + string.IsNullOrWhiteSpace(value) + ? value + : value.Replace("use `_all` or empty string", "use the special string `_all` or Indices.All"); + } } diff --git a/src/ApiGenerator/Domain/Specification/UrlPath.cs b/src/ApiGenerator/Domain/Specification/UrlPath.cs index 7d77290b07..d0dec6e968 100644 --- a/src/ApiGenerator/Domain/Specification/UrlPath.cs +++ b/src/ApiGenerator/Domain/Specification/UrlPath.cs @@ -37,7 +37,7 @@ public class UrlPath private readonly IList _additionalPartsForConstructor; public string Path { get; set; } public Deprecation Deprecation { get; } - public Version VersionAdded { get; } + public Version VersionAdded { get; } public IList Parts { get; } public UrlPath(string path, IList parts, Deprecation deprecation, Version versionAdded, IList additionalPartsForConstructor = null) @@ -45,9 +45,9 @@ public UrlPath(string path, IList parts, Deprecation deprecation, Versi _additionalPartsForConstructor = additionalPartsForConstructor ?? new List(); Path = LeadingBackslash(path); Parts = parts; - Deprecation = deprecation; - VersionAdded = versionAdded; - } + Deprecation = deprecation; + VersionAdded = versionAdded; + } public string ConstructorArguments => string.Join(", ", Parts.Select(p => $"{p.HighLevelTypeName} {p.NameAsArgument}")); public string RequestBaseArguments => @@ -56,20 +56,20 @@ public UrlPath(string path, IList parts, Deprecation deprecation, Versi public string TypedSubClassBaseArguments => string.Join(", ", Parts.Select(p => p.NameAsArgument)); - private static string[] ResolvabeFromT = { "index"}; + private static string[] ResolvabeFromT = { "index" }; public bool HasResolvableArguments => Parts.Any(p => ResolvabeFromT.Contains(p.Name)); - public string AutoResolveConstructorArguments => string.Join(", ", Parts.Where(p => !ResolvabeFromT.Contains(p.Name)).Select(p => $"{p.HighLevelTypeName} {p.NameAsArgument}")); + public string AutoResolveConstructorArguments => string.Join(", ", Parts.Where(p => !ResolvabeFromT.Contains(p.Name)).Select(p => $"{p.HighLevelTypeName} {p.NameAsArgument}")); public string AutoResolveBaseArguments(string generic) => string.Join(", ", Parts.Select(p => !ResolvabeFromT.Contains(p.Name) ? p.Name : $"typeof({generic})")); public string DocumentPathBaseArgument(string generic) => string.Join(", ", - _additionalPartsForConstructor.Select(p => p.Name =="id" ? $"id ?? OpenSearch.Client.Id.From(documentWithId)" + _additionalPartsForConstructor.Select(p => p.Name == "id" ? $"id ?? OpenSearch.Client.Id.From(documentWithId)" : ResolvabeFromT.Contains(p.Name) ? $"{p.Name} ?? typeof({generic})" : p.Name)); public string DocumentPathConstructorArgument(string generic) => string.Join(", ", - new [] { $"{generic} documentWithId" }.Concat(_additionalPartsForConstructor.Select(p => $"{p.HighLevelTypeName} {p.NameAsArgument} = null"))); + new[] { $"{generic} documentWithId" }.Concat(_additionalPartsForConstructor.Select(p => $"{p.HighLevelTypeName} {p.NameAsArgument} = null"))); public string GetXmlDocs(string indent, bool skipResolvable = false, bool documentConstructor = false) { diff --git a/src/ApiGenerator/Extensions.cs b/src/ApiGenerator/Extensions.cs index 9062eeb15a..6cb71ec5ec 100644 --- a/src/ApiGenerator/Extensions.cs +++ b/src/ApiGenerator/Extensions.cs @@ -69,10 +69,10 @@ public static string ToCamelCase(this string s) public static string SplitPascalCase(this string s) => Regex.Replace(s, "([A-Z]+[a-z]*)", " $1").Trim(); - public static bool IsNullOrEmpty(this string s) => - string.IsNullOrEmpty(s); + public static bool IsNullOrEmpty(this string s) => + string.IsNullOrEmpty(s); - public static void SortBy(this List list, Func selector) => - list.Sort((a, b) => Comparer.Default.Compare(selector(a), selector(b))); - } + public static void SortBy(this List list, Func selector) => + list.Sort((a, b) => Comparer.Default.Compare(selector(a), selector(b))); + } } diff --git a/src/ApiGenerator/Generator/ApiEndpointFactory.cs b/src/ApiGenerator/Generator/ApiEndpointFactory.cs index 13d3b4887d..c51a61c0e9 100644 --- a/src/ApiGenerator/Generator/ApiEndpointFactory.cs +++ b/src/ApiGenerator/Generator/ApiEndpointFactory.cs @@ -195,10 +195,12 @@ List paramCombo private record PathParameter(string Name, JsonSchema Schema, string Description, bool IsDeprecated) { public PathParameter(OpenApiParameter parameter) : - this(parameter.Name, parameter.Schema, parameter.Description, parameter.IsDeprecated) { } + this(parameter.Name, parameter.Schema, parameter.Description, parameter.IsDeprecated) + { } public PathParameter(string name, OpenApiParameter parameter, JsonSchema schema) : this(name, schema, parameter.Description, - parameter.IsDeprecated) { } + parameter.IsDeprecated) + { } } private static IEndpointOverrides LoadOverrides(string endpointName, string methodName) diff --git a/src/ApiGenerator/Generator/ApiGenerator.cs b/src/ApiGenerator/Generator/ApiGenerator.cs index d1ee1eb6fa..cfb5cbc629 100644 --- a/src/ApiGenerator/Generator/ApiGenerator.cs +++ b/src/ApiGenerator/Generator/ApiGenerator.cs @@ -51,7 +51,7 @@ public class ApiGenerator public static async Task Generate(bool lowLevelOnly, RestApiSpec spec, CancellationToken token) { - async Task DoGenerate(IReadOnlyCollection generators, bool highLevel) + async Task DoGenerate(IReadOnlyCollection generators, bool highLevel) { var pbarOpts = new ProgressBarOptions { ProgressCharacter = '─', BackgroundColor = ConsoleColor.Yellow }; var message = $"Generating {(highLevel ? "high" : "low")} level code"; @@ -64,102 +64,105 @@ async Task DoGenerate(IReadOnlyCollection generators, bool h } } - RecursiveDelete(GeneratorLocations.LowLevelGeneratedFolder); - await DoGenerate( - new RazorGeneratorBase[] { + RecursiveDelete(GeneratorLocations.LowLevelGeneratedFolder); + await DoGenerate( + new RazorGeneratorBase[] { //low level client new LowLevelClientInterfaceGenerator(), - new LowLevelClientImplementationGenerator(), - new RequestParametersGenerator(), - new EnumsGenerator() - }, - highLevel: false - ); - - if (lowLevelOnly) return; - - RecursiveDelete(GeneratorLocations.HighLevelGeneratedFolder); - await DoGenerate( - new RazorGeneratorBase[] - { + new LowLevelClientImplementationGenerator(), + new RequestParametersGenerator(), + new EnumsGenerator() + }, + highLevel: false + ); + + if (lowLevelOnly) return; + + RecursiveDelete(GeneratorLocations.HighLevelGeneratedFolder); + await DoGenerate( + new RazorGeneratorBase[] + { //high level client new ApiUrlsLookupsGenerator(), - new HighLevelClientInterfaceGenerator(), - new HighLevelClientImplementationGenerator(), - new DescriptorsGenerator(), - new RequestsGenerator(), - }, - highLevel: true - ); - } - - public static async Task CreateRestApiSpecModel(CancellationToken token = default) - { - var json = PreprocessRawOpenApiSpec(await File.ReadAllTextAsync(GeneratorLocations.OpenApiSpecFile, token)); - var document = await OpenApiDocument.FromJsonAsync(json, token); + new HighLevelClientInterfaceGenerator(), + new HighLevelClientImplementationGenerator(), + new DescriptorsGenerator(), + new RequestsGenerator(), + }, + highLevel: true + ); + } + + public static async Task CreateRestApiSpecModel(CancellationToken token = default) + { + var json = PreprocessRawOpenApiSpec(await File.ReadAllTextAsync(GeneratorLocations.OpenApiSpecFile, token)); + var document = await OpenApiDocument.FromJsonAsync(json, token); JsonSchemaReferenceUtilities.UpdateSchemaReferencePaths(document); - var enumsToGenerate = new Dictionary(); - - var endpoints = document.Paths - .Select(kv => new { HttpPath = kv.Key, PathItem = kv.Value }) - .SelectMany(p => p.PathItem.Select(kv => new - { - p.HttpPath, p.PathItem, HttpMethod = kv.Key, Operation = kv.Value - })) - .GroupBy(o => o.Operation.ExtensionData!["x-operation-group"]!.ToString()) - .Where(o => CodeConfiguration.IncludeOperation(o.Key)) - .Select(o => ApiEndpointFactory.From( - o.Key, - o.Select(i => (i.HttpPath, i.PathItem, i.HttpMethod, i.Operation)).ToList(), - (e, isFlag) => - { - if (enumsToGenerate.TryGetValue(e, out var f)) isFlag |= f; - enumsToGenerate[e] = isFlag; - })) - .ToImmutableSortedDictionary(e => e.Name, e => e); - - var enumsInSpec = enumsToGenerate.Select(kvp => new EnumDescription - { - Name = CsharpNames.GetEnumName(kvp.Key), - IsFlag = kvp.Value, - Options = document.Components.Schemas[kvp.Key].Enumeration.Where(e => e != null).Select(e => e.ToString()).ToImmutableList() - }) - .OrderBy(e => e.Name) - .ToImmutableList(); - - return new RestApiSpec { Endpoints = endpoints, EnumsInTheSpec = enumsInSpec }; - } - - private static string PreprocessRawOpenApiSpec(string yaml) - { - // FIXME: work-around until NSwag adds support for requestBody references: https://github.com/RicoSuter/NSwag/pull/4747 - dynamic doc = new DeserializerBuilder().Build().Deserialize(yaml)!; - var requestBodies = doc["components"]["requestBodies"]; - foreach (KeyValuePair pathPair in doc["paths"]) - { - foreach (KeyValuePair operationPair in pathPair.Value) - { - var operation = (Dictionary) operationPair.Value; - if (!operation.TryGetValue("requestBody", out var rb)) continue; - - var requestBody = (Dictionary) rb; - if (!requestBody.TryGetValue("$ref", out var reference)) continue; - - operation["requestBody"] = requestBodies[((string) reference).Split('/').Last()]; - } - } - return new SerializerBuilder() - .JsonCompatible() - .Build() - .Serialize(doc); - } - - private static void RecursiveDelete(string path) - { - if (!Directory.Exists(path)) return; - - Directory.Delete(path, true); - } + var enumsToGenerate = new Dictionary(); + + var endpoints = document.Paths + .Select(kv => new { HttpPath = kv.Key, PathItem = kv.Value }) + .SelectMany(p => p.PathItem.Select(kv => new + { + p.HttpPath, + p.PathItem, + HttpMethod = kv.Key, + Operation = kv.Value + })) + .GroupBy(o => o.Operation.ExtensionData!["x-operation-group"]!.ToString()) + .Where(o => CodeConfiguration.IncludeOperation(o.Key)) + .Select(o => ApiEndpointFactory.From( + o.Key, + o.Select(i => (i.HttpPath, i.PathItem, i.HttpMethod, i.Operation)).ToList(), + (e, isFlag) => + { + if (enumsToGenerate.TryGetValue(e, out var f)) isFlag |= f; + enumsToGenerate[e] = isFlag; + })) + .ToImmutableSortedDictionary(e => e.Name, e => e); + + var enumsInSpec = enumsToGenerate.Select(kvp => new EnumDescription + { + Name = CsharpNames.GetEnumName(kvp.Key), + IsFlag = kvp.Value, + Options = document.Components.Schemas[kvp.Key].Enumeration.Where(e => e != null).Select(e => e.ToString()).ToImmutableList() + }) + .OrderBy(e => e.Name) + .ToImmutableList(); + + return new RestApiSpec { Endpoints = endpoints, EnumsInTheSpec = enumsInSpec }; + } + + private static string PreprocessRawOpenApiSpec(string yaml) + { + // FIXME: work-around until NSwag adds support for requestBody references: https://github.com/RicoSuter/NSwag/pull/4747 + dynamic doc = new DeserializerBuilder().Build().Deserialize(yaml)!; + var requestBodies = doc["components"]["requestBodies"]; + foreach (KeyValuePair pathPair in doc["paths"]) + { + foreach (KeyValuePair operationPair in pathPair.Value) + { + var operation = (Dictionary)operationPair.Value; + if (!operation.TryGetValue("requestBody", out var rb)) continue; + + var requestBody = (Dictionary)rb; + if (!requestBody.TryGetValue("$ref", out var reference)) continue; + + operation["requestBody"] = requestBodies[((string)reference).Split('/').Last()]; + } + } + return new SerializerBuilder() + .JsonCompatible() + .Build() + .Serialize(doc); + } + + private static void RecursiveDelete(string path) + { + if (!Directory.Exists(path)) return; + + Directory.Delete(path, true); + } } } diff --git a/src/ApiGenerator/Generator/CodeGenerator.cs b/src/ApiGenerator/Generator/CodeGenerator.cs index 9a0a5cb025..d0b47a329f 100644 --- a/src/ApiGenerator/Generator/CodeGenerator.cs +++ b/src/ApiGenerator/Generator/CodeGenerator.cs @@ -50,7 +50,7 @@ public static string Property(string @namespace, string type, string name, strin { var components = new List(); foreach (var d in RenderDocumentation(doc)) A(d); - if (versionAdded != null) A($"/// Supported by OpenSearch servers of version {versionAdded} or greater."); + if (versionAdded != null) A($"/// Supported by OpenSearch servers of version {versionAdded} or greater."); if (!string.IsNullOrWhiteSpace(obsolete)) A($"[Obsolete(\"{obsolete}\")]"); var generated = @namespace != null && @namespace == "Cat" && name == "Format" diff --git a/src/ApiGenerator/Generator/Razor/DescriptorsGenerator.cs b/src/ApiGenerator/Generator/Razor/DescriptorsGenerator.cs index 647022027d..d2c34b6329 100644 --- a/src/ApiGenerator/Generator/Razor/DescriptorsGenerator.cs +++ b/src/ApiGenerator/Generator/Razor/DescriptorsGenerator.cs @@ -38,27 +38,27 @@ namespace ApiGenerator.Generator.Razor; public class DescriptorsGenerator : RazorGeneratorBase { - public override string Title => "OpenSearch.Client descriptors"; + public override string Title => "OpenSearch.Client descriptors"; - public override async Task Generate(RestApiSpec spec, ProgressBar progressBar, CancellationToken token) - { - await DoRazor(spec, View("RequestDescriptorBase"), Target(), token); + public override async Task Generate(RestApiSpec spec, ProgressBar progressBar, CancellationToken token) + { + await DoRazor(spec, View("RequestDescriptorBase"), Target(), token); - await DoRazor(HttpMethod.All, View("Descriptors.Http"), Target("Http"), token); + await DoRazor(HttpMethod.All, View("Descriptors.Http"), Target("Http"), token); - await DoRazorDependantFiles( - progressBar, - spec.EndpointsPerNamespaceHighLevel.ToList(), - View("Descriptors"), - kv => kv.Key, - Target, - token - ); + await DoRazorDependantFiles( + progressBar, + spec.EndpointsPerNamespaceHighLevel.ToList(), + View("Descriptors"), + kv => kv.Key, + Target, + token + ); - return; + return; - string View(string name) => ViewLocations.HighLevel("Descriptors", $"{name}.cshtml"); + string View(string name) => ViewLocations.HighLevel("Descriptors", $"{name}.cshtml"); - string Target(string id = null) => GeneratorLocations.HighLevel($"Descriptors{(id != null ? $".{id}" : string.Empty)}.cs"); - } + string Target(string id = null) => GeneratorLocations.HighLevel($"Descriptors{(id != null ? $".{id}" : string.Empty)}.cs"); + } } diff --git a/src/ApiGenerator/Generator/Razor/HighLevelClientImplementationGenerator.cs b/src/ApiGenerator/Generator/Razor/HighLevelClientImplementationGenerator.cs index 945de9ae74..b210227490 100644 --- a/src/ApiGenerator/Generator/Razor/HighLevelClientImplementationGenerator.cs +++ b/src/ApiGenerator/Generator/Razor/HighLevelClientImplementationGenerator.cs @@ -41,27 +41,27 @@ namespace ApiGenerator.Generator.Razor; public class HighLevelClientImplementationGenerator : RazorGeneratorBase { - public override string Title => "OpenSearch.Client client implementation"; + public override string Title => "OpenSearch.Client client implementation"; - public override async Task Generate(RestApiSpec spec, ProgressBar progressBar, CancellationToken token) - { - await DoRazor(spec, View(), Target(), token); + public override async Task Generate(RestApiSpec spec, ProgressBar progressBar, CancellationToken token) + { + await DoRazor(spec, View(), Target(), token); - await DoRazor(HttpMethod.All, View("Http"), Target("Http"), token); + await DoRazor(HttpMethod.All, View("Http"), Target("Http"), token); - await DoRazorDependantFiles( - progressBar, - spec.EndpointsPerNamespaceHighLevel.Where(kv => kv.Key != CsharpNames.RootNamespace).ToList(), - View("Namespace"), - kv => kv.Key, - Target, - token - ); + await DoRazorDependantFiles( + progressBar, + spec.EndpointsPerNamespaceHighLevel.Where(kv => kv.Key != CsharpNames.RootNamespace).ToList(), + View("Namespace"), + kv => kv.Key, + Target, + token + ); - return; + return; - string View(string ns = null) => ViewLocations.HighLevel("Client", "Implementation", $"OpenSearchClient{(ns != null ? $".{ns}" : string.Empty)}.cshtml"); + string View(string ns = null) => ViewLocations.HighLevel("Client", "Implementation", $"OpenSearchClient{(ns != null ? $".{ns}" : string.Empty)}.cshtml"); - string Target(string ns = null) => GeneratorLocations.HighLevel($"OpenSearchClient{(ns != null ? $".{ns}" : string.Empty)}.cs"); - } + string Target(string ns = null) => GeneratorLocations.HighLevel($"OpenSearchClient{(ns != null ? $".{ns}" : string.Empty)}.cs"); + } } diff --git a/src/ApiGenerator/Generator/Razor/LowLevelClientImplementationGenerator.cs b/src/ApiGenerator/Generator/Razor/LowLevelClientImplementationGenerator.cs index c5d6328c41..a34a3a8cc3 100644 --- a/src/ApiGenerator/Generator/Razor/LowLevelClientImplementationGenerator.cs +++ b/src/ApiGenerator/Generator/Razor/LowLevelClientImplementationGenerator.cs @@ -38,28 +38,28 @@ namespace ApiGenerator.Generator.Razor; public class LowLevelClientImplementationGenerator : RazorGeneratorBase { - public override string Title => "OpenSearch.Net client implementation"; + public override string Title => "OpenSearch.Net client implementation"; - public override async Task Generate(RestApiSpec spec, ProgressBar progressBar, CancellationToken token) - { - await DoRazor(spec, View(), Target(), token); + public override async Task Generate(RestApiSpec spec, ProgressBar progressBar, CancellationToken token) + { + await DoRazor(spec, View(), Target(), token); - await DoRazor(HttpMethod.All, View("Http"), Target("Http"), token); + await DoRazor(HttpMethod.All, View("Http"), Target("Http"), token); - await DoRazorDependantFiles( - progressBar, - spec.EndpointsPerNamespaceLowLevel.Where(kv => kv.Key != CsharpNames.RootNamespace).ToList(), - View("Namespace"), - kv => kv.Key, - Target, - token - ); + await DoRazorDependantFiles( + progressBar, + spec.EndpointsPerNamespaceLowLevel.Where(kv => kv.Key != CsharpNames.RootNamespace).ToList(), + View("Namespace"), + kv => kv.Key, + Target, + token + ); - return; + return; - string View(string id = null) => - ViewLocations.LowLevel("Client", "Implementation", $"OpenSearchLowLevelClient{(id != null ? $".{id}" : string.Empty)}.cshtml"); + string View(string id = null) => + ViewLocations.LowLevel("Client", "Implementation", $"OpenSearchLowLevelClient{(id != null ? $".{id}" : string.Empty)}.cshtml"); - string Target(string id = null) => GeneratorLocations.LowLevel($"OpenSearchLowLevelClient{(id != null ? $".{id}" : string.Empty)}.cs"); - } + string Target(string id = null) => GeneratorLocations.LowLevel($"OpenSearchLowLevelClient{(id != null ? $".{id}" : string.Empty)}.cs"); + } } diff --git a/src/ApiGenerator/Generator/Razor/RequestParametersGenerator.cs b/src/ApiGenerator/Generator/Razor/RequestParametersGenerator.cs index 9187f22739..4443dabe45 100644 --- a/src/ApiGenerator/Generator/Razor/RequestParametersGenerator.cs +++ b/src/ApiGenerator/Generator/Razor/RequestParametersGenerator.cs @@ -38,25 +38,25 @@ namespace ApiGenerator.Generator.Razor; public class RequestParametersGenerator : RazorGeneratorBase { - public override string Title => "OpenSearch.Net request parameters"; + public override string Title => "OpenSearch.Net request parameters"; - public override async Task Generate(RestApiSpec spec, ProgressBar progressBar, CancellationToken token) - { - await DoRazor(HttpMethod.All, View("Http"), Target("Http"), token); + public override async Task Generate(RestApiSpec spec, ProgressBar progressBar, CancellationToken token) + { + await DoRazor(HttpMethod.All, View("Http"), Target("Http"), token); - await DoRazorDependantFiles( - progressBar, - spec.EndpointsPerNamespaceLowLevel.ToList(), - View(), - kv => kv.Key, - Target, - token - ); + await DoRazorDependantFiles( + progressBar, + spec.EndpointsPerNamespaceLowLevel.ToList(), + View(), + kv => kv.Key, + Target, + token + ); - return; + return; - string View(string id = null) => ViewLocations.LowLevel("RequestParameters", $"RequestParameters{(id != null ? $".{id}" : string.Empty)}.cshtml"); + string View(string id = null) => ViewLocations.LowLevel("RequestParameters", $"RequestParameters{(id != null ? $".{id}" : string.Empty)}.cshtml"); - string Target(string id) => GeneratorLocations.LowLevel("Api", "RequestParameters", $"RequestParameters.{id}.cs"); - } + string Target(string id) => GeneratorLocations.LowLevel("Api", "RequestParameters", $"RequestParameters.{id}.cs"); + } } diff --git a/src/ApiGenerator/Generator/Razor/RequestsGenerator.cs b/src/ApiGenerator/Generator/Razor/RequestsGenerator.cs index 0e4d0c45fe..30c8395bac 100644 --- a/src/ApiGenerator/Generator/Razor/RequestsGenerator.cs +++ b/src/ApiGenerator/Generator/Razor/RequestsGenerator.cs @@ -48,21 +48,21 @@ public override async Task Generate(RestApiSpec spec, ProgressBar progressBar, C { await DoRazor(spec, View("PlainRequestBase"), Target(), token); - await DoRazor(HttpMethod.All, View("Requests.Http"), Target("Http"), token); + await DoRazor(HttpMethod.All, View("Requests.Http"), Target("Http"), token); - await DoRazorDependantFiles( - progressBar, - spec.EndpointsPerNamespaceHighLevel.ToList(), - View("Requests"), - kv => kv.Key, - Target, - token); + await DoRazorDependantFiles( + progressBar, + spec.EndpointsPerNamespaceHighLevel.ToList(), + View("Requests"), + kv => kv.Key, + Target, + token); - return; + return; - string View(string name) => ViewLocations.HighLevel("Requests", $"{name}.cshtml"); + string View(string name) => ViewLocations.HighLevel("Requests", $"{name}.cshtml"); - string Target(string id = null) => GeneratorLocations.HighLevel($"Requests{(id != null ? $".{id}" : string.Empty)}.cs"); - } + string Target(string id = null) => GeneratorLocations.HighLevel($"Requests{(id != null ? $".{id}" : string.Empty)}.cs"); + } } } diff --git a/src/ApiGenerator/Program.cs b/src/ApiGenerator/Program.cs index e310025447..7e004d0545 100644 --- a/src/ApiGenerator/Program.cs +++ b/src/ApiGenerator/Program.cs @@ -171,12 +171,6 @@ private static async Task Generate(bool download, string branch, bool inclu private static void RunDotNetFormat() { - var enviromentPath = System.Environment.GetEnvironmentVariable("PATH"); - var paths = enviromentPath.Split(';'); - var exePath = paths.Select(x => Path.Combine(x, "dotnet.exe")) - .Where(x => File.Exists(x)) - .FirstOrDefault(); - Console.WriteLine(); AnsiConsole.Write(new Rule("[b white on chartreuse4] Formatting Code using dotnet format [/]").LeftJustified()); Console.WriteLine(); diff --git a/src/ApiGenerator/RestSpecDownloader.cs b/src/ApiGenerator/RestSpecDownloader.cs index 71bac0d807..796a11fbff 100644 --- a/src/ApiGenerator/RestSpecDownloader.cs +++ b/src/ApiGenerator/RestSpecDownloader.cs @@ -37,15 +37,15 @@ namespace ApiGenerator { public static class RestSpecDownloader { - private static readonly HttpClient Http = new(); + private static readonly HttpClient Http = new(); - public static async Task DownloadAsync(string branch, CancellationToken token) - { - var githubUrl = $"https://github.com/opensearch-project/opensearch-api-specification/releases/download/{branch}-latest/opensearch-openapi.yaml"; - Console.WriteLine($"Downloading OpenAPI spec for branch {branch}"); - var spec = await Http.GetStringAsync(githubUrl, token); - await File.WriteAllTextAsync(GeneratorLocations.OpenApiSpecFile, spec, token); + public static async Task DownloadAsync(string branch, CancellationToken token) + { + var githubUrl = $"https://github.com/opensearch-project/opensearch-api-specification/releases/download/{branch}-latest/opensearch-openapi.yaml"; + Console.WriteLine($"Downloading OpenAPI spec for branch {branch}"); + var spec = await Http.GetStringAsync(githubUrl, token); + await File.WriteAllTextAsync(GeneratorLocations.OpenApiSpecFile, spec, token); Console.WriteLine($"Downloaded OpenAPI spec for branch {branch}"); } - } + } }