From d55f84670ba35baebc5dfcba3737bdc6cfa2c68c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20=C3=87etinkaya?= Date: Wed, 7 Feb 2024 13:52:41 +0300 Subject: [PATCH] style: reformat --- .csharpierrc | 10 ++ .github/workflows/dotnet.yml | 30 ++++ .github/workflows/release.yml | 13 ++ .../Code/CSharp/CSharpCodeInjector.cs | 60 ++----- .../Code/CSharp/CSharpCodeReader.cs | 30 +--- .../Core.CodeGen/Code/StringCaseExtensions.cs | 22 +-- .../Core.CodeGen/Code/StringWordExtension.cs | 5 +- .../Core.CodeGen/File/DirectoryHelper.cs | 3 +- .../ScribanStringFunctionsExtensions.cs | 3 +- .../TemplateEngine/TemplateEngine.cs | 25 +-- .../Commands/New/CreateNewProjectCommand.cs | 38 ++--- .../Command/GenerateCommandCommand.cs | 78 ++------- .../Commands/Crud/GenerateCrudCommand.cs | 156 ++++++------------ .../Commands/Query/GenerateQueryCommand.cs | 82 ++------- .../Generate/Rules/GenerateBusinessRules.cs | 12 +- .../Command/GenerateCommandCliCommand.cs | 20 +-- .../GenerateCommandCliCommandSettings.cs | 34 +--- .../Generate/Crud/GenerateCrudCliCommand.cs | 38 +---- .../Crud/GenerateCrudCliCommandSettings.cs | 43 +---- .../Generate/Query/GenerateQueryCliCommand.cs | 20 +-- .../Query/GenerateQueryCliCommandSettings.cs | 34 +--- .../New/CreateNewProjectCliCommand.cs | 15 +- 22 files changed, 220 insertions(+), 551 deletions(-) create mode 100644 .csharpierrc create mode 100644 .github/workflows/dotnet.yml create mode 100644 .github/workflows/release.yml diff --git a/.csharpierrc b/.csharpierrc new file mode 100644 index 0000000..f1da26d --- /dev/null +++ b/.csharpierrc @@ -0,0 +1,10 @@ +{ + "printWidth": 140, + "useTabs": false, + "tabWidth": 4, + "preprocessorSymbolSets": [ + "", + "DEBUG", + "DEBUG,CODE_STYLE" + ] +} diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml new file mode 100644 index 0000000..b5d2d8f --- /dev/null +++ b/.github/workflows/dotnet.yml @@ -0,0 +1,30 @@ +name: .NET + +on: + push: + branches: ["main"] + pull_request: + branches: ["main"] + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + with: + submodules: recursive + - name: Setup .NET + uses: actions/setup-dotnet@v3 + with: + dotnet-version: 7.0.x + - name: Restore dependencies + run: dotnet restore + - name: Build + run: dotnet build --no-restore + - name: Test + run: dotnet test --no-build --verbosity normal + - name: Restore tool dependencies + run: dotnet tool restore + - name: Check format + run: dotnet csharpier --check . diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..86c05eb --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,13 @@ +name: "Release" + +on: + push: + tags: + - "v*.*.*" + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: GH Release + uses: softprops/action-gh-release@v0.1.15 diff --git a/src/corePackages/Core.CodeGen/Code/CSharp/CSharpCodeInjector.cs b/src/corePackages/Core.CodeGen/Code/CSharp/CSharpCodeInjector.cs index 6acba5d..f9d3dcb 100644 --- a/src/corePackages/Core.CodeGen/Code/CSharp/CSharpCodeInjector.cs +++ b/src/corePackages/Core.CodeGen/Code/CSharp/CSharpCodeInjector.cs @@ -4,11 +4,7 @@ namespace Core.CodeGen.Code.CSharp; public static class CSharpCodeInjector { - public static async Task AddCodeLinesToMethodAsync( - string filePath, - string methodName, - string[] codeLines - ) + public static async Task AddCodeLinesToMethodAsync(string filePath, string methodName, string[] codeLines) { List fileContent = (await System.IO.File.ReadAllLinesAsync(filePath)).ToList(); string methodStartRegex = @@ -57,9 +53,7 @@ string[] codeLines break; if ( Regex.Match(input: fileContent[j], pattern: @"\s+return").Success - && Regex - .Match(input: fileContent[j - 1], pattern: @"(if|else if|else)\s*\(") - .Success + && Regex.Match(input: fileContent[j - 1], pattern: @"(if|else if|else)\s*\(").Success ) break; @@ -76,14 +70,10 @@ string[] codeLines if (methodStartIndex == -1 || methodEndIndex == -1) throw new Exception($"{methodName} not found in \"{filePath}\"."); - ICollection methodContent = fileContent - .Skip(methodStartIndex + 1) - .Take(methodEndIndex - 1 - methodStartIndex) - .ToArray(); + ICollection methodContent = fileContent.Skip(methodStartIndex + 1).Take(methodEndIndex - 1 - methodStartIndex).ToArray(); int minimumSpaceCountInMethod; if (methodContent.Count < 2) - minimumSpaceCountInMethod = - fileContent[methodStartIndex].TakeWhile(char.IsWhiteSpace).Count() * 2; + minimumSpaceCountInMethod = fileContent[methodStartIndex].TakeWhile(char.IsWhiteSpace).Count() * 2; else minimumSpaceCountInMethod = methodContent .Where(line => !string.IsNullOrEmpty(line)) @@ -133,14 +123,11 @@ public static async Task AddCodeLinesAsPropertyAsync(string filePath, string[] c } } - propertySpaceCountInClass = - fileContent[indexToAdd].TakeWhile(char.IsWhiteSpace).Count() * 2; + propertySpaceCountInClass = fileContent[indexToAdd].TakeWhile(char.IsWhiteSpace).Count() * 2; } else { - propertySpaceCountInClass = fileContent[indexToAdd] - .TakeWhile(char.IsWhiteSpace) - .Count(); + propertySpaceCountInClass = fileContent[indexToAdd].TakeWhile(char.IsWhiteSpace).Count(); } List updatedFileContent = new(fileContent); @@ -152,11 +139,7 @@ public static async Task AddCodeLinesAsPropertyAsync(string filePath, string[] c await System.IO.File.WriteAllLinesAsync(filePath, contents: updatedFileContent.ToArray()); } - public static async Task AddCodeLinesToRegionAsync( - string filePath, - IEnumerable linesToAdd, - string regionName - ) + public static async Task AddCodeLinesToRegionAsync(string filePath, IEnumerable linesToAdd, string regionName) { List fileContent = (await System.IO.File.ReadAllLinesAsync(filePath)).ToList(); string regionStartRegex = @$"^\s*#region\s*{regionName}\s*"; @@ -189,15 +172,11 @@ string regionName if (!string.IsNullOrEmpty(previousLine)) fileContent.Insert(index: indexToAdd - 1, string.Empty); - int minimumSpaceCountInRegion = fileContent[indexToAdd] - .TakeWhile(char.IsWhiteSpace) - .Count(); + int minimumSpaceCountInRegion = fileContent[indexToAdd].TakeWhile(char.IsWhiteSpace).Count(); fileContent.InsertRange( index: indexToAdd - 1, - collection: linesToAdd.Select( - line => new string(' ', minimumSpaceCountInRegion) + line - ) + collection: linesToAdd.Select(line => new string(' ', minimumSpaceCountInRegion) + line) ); await System.IO.File.WriteAllLinesAsync(filePath, fileContent); break; @@ -208,9 +187,7 @@ public static async Task AddUsingToFile(string filePath, IEnumerable usi { List fileContent = (await System.IO.File.ReadAllLinesAsync(filePath)).ToList(); - IEnumerable usingLinesToAdd = usingLines.Where( - usingLine => !fileContent.Contains(usingLine) - ); + IEnumerable usingLinesToAdd = usingLines.Where(usingLine => !fileContent.Contains(usingLine)); Regex usingRegex = new(@"^using\s+.*;$"); int indexToAdd = 0; @@ -231,9 +208,7 @@ public static async Task AddMethodToClass(string filePath, string className, str { List fileContent = (await System.IO.File.ReadAllLinesAsync(filePath)).ToList(); Regex classStartRegex = - new( - @$"((public|protected|internal|protected internal|private protected|private)\s+)?(static\s+)?\s+\b{className}" - ); + new(@$"((public|protected|internal|protected internal|private protected|private)\s+)?(static\s+)?\s+\b{className}"); Regex scopeBlockStartRegex = new(@"\{"); Regex scopeBlockEndRegex = new(@"\}"); @@ -275,24 +250,17 @@ public static async Task AddMethodToClass(string filePath, string className, str if (classStartIndex == -1 || classEndIndex == -1) throw new Exception($"{className} not found in \"{filePath}\"."); - ICollection classContent = fileContent - .Skip(classStartIndex + 1) - .Take(classEndIndex - 1 - classStartIndex) - .ToArray(); + ICollection classContent = fileContent.Skip(classStartIndex + 1).Take(classEndIndex - 1 - classStartIndex).ToArray(); int minimumSpaceCountInClass; if (classContent.Count < 2) - minimumSpaceCountInClass = - fileContent[classStartIndex].TakeWhile(char.IsWhiteSpace).Count() * 2; + minimumSpaceCountInClass = fileContent[classStartIndex].TakeWhile(char.IsWhiteSpace).Count() * 2; else minimumSpaceCountInClass = classContent .Where(line => !string.IsNullOrEmpty(line)) .Min(line => line.TakeWhile(char.IsWhiteSpace).Count()); - fileContent.InsertRange( - classEndIndex, - collection: codeLines.Select(line => new string(' ', minimumSpaceCountInClass) + line) - ); + fileContent.InsertRange(classEndIndex, collection: codeLines.Select(line => new string(' ', minimumSpaceCountInClass) + line)); await System.IO.File.WriteAllLinesAsync(filePath, contents: fileContent.ToArray()); } } diff --git a/src/corePackages/Core.CodeGen/Code/CSharp/CSharpCodeReader.cs b/src/corePackages/Core.CodeGen/Code/CSharp/CSharpCodeReader.cs index c119e5c..2430a65 100644 --- a/src/corePackages/Core.CodeGen/Code/CSharp/CSharpCodeReader.cs +++ b/src/corePackages/Core.CodeGen/Code/CSharp/CSharpCodeReader.cs @@ -31,9 +31,7 @@ public static async Task ReadBaseClassNameAsync(string filePath) return match.Groups[1].Value; } - public static async Task> ReadBaseClassGenericArgumentsAsync( - string filePath - ) + public static async Task> ReadBaseClassGenericArgumentsAsync(string filePath) { string fileContent = await System.IO.File.ReadAllTextAsync(filePath); const string pattern = @"class\s+\w+\s*:?\s*(\w+)\s*<([\w,\s]+)>"; @@ -46,10 +44,7 @@ string filePath return genericArguments.Select(genericArgument => genericArgument.Trim()).ToArray(); } - public static async Task> ReadClassPropertiesAsync( - string filePath, - string projectPath - ) + public static async Task> ReadClassPropertiesAsync(string filePath, string projectPath) { string fileContent = await System.IO.File.ReadAllTextAsync(filePath); Regex propertyRegex = @@ -73,14 +68,11 @@ string projectPath string? nameSpace = null; if (!builtInTypeRegex.IsMatch(typeName)) { - ICollection potentialPropertyTypeFilePaths = - DirectoryHelper.GetFilesInDirectoryTree( - projectPath, - searchPattern: $"{typeName}.cs" - ); - ICollection usingNameSpacesInFile = await ReadUsingNameSpacesAsync( - filePath + ICollection potentialPropertyTypeFilePaths = DirectoryHelper.GetFilesInDirectoryTree( + projectPath, + searchPattern: $"{typeName}.cs" ); + ICollection usingNameSpacesInFile = await ReadUsingNameSpacesAsync(filePath); foreach (string potentialPropertyTypeFilePath in potentialPropertyTypeFilePaths) { string potentialPropertyNameSpace = string.Join( @@ -91,11 +83,7 @@ string projectPath .Replace(oldValue: $".{typeName}.cs", string.Empty) .Substring(1) .Split('.') - .Select( - part => - char.ToUpper(part[0], CultureInfo.GetCultureInfo("en-EN")) - + part[1..] - ) + .Select(part => char.ToUpper(part[0], CultureInfo.GetCultureInfo("en-EN")) + part[1..]) ); if (!usingNameSpacesInFile.Contains(potentialPropertyNameSpace)) continue; @@ -107,9 +95,7 @@ string projectPath PropertyInfo propertyInfo = new() { - AccessModifier = string.IsNullOrEmpty(accessModifier) - ? "private" - : accessModifier, + AccessModifier = string.IsNullOrEmpty(accessModifier) ? "private" : accessModifier, Type = type, Name = name, NameSpace = nameSpace diff --git a/src/corePackages/Core.CodeGen/Code/StringCaseExtensions.cs b/src/corePackages/Core.CodeGen/Code/StringCaseExtensions.cs index a1190b9..e5900c8 100644 --- a/src/corePackages/Core.CodeGen/Code/StringCaseExtensions.cs +++ b/src/corePackages/Core.CodeGen/Code/StringCaseExtensions.cs @@ -28,10 +28,7 @@ public static string ToPascalCase(this string value) return string.Join( string.Empty, - values: words.Select( - word => - char.ToUpper(word[index: 0], CultureInfo.GetCultureInfo("en-EN")) + word[1..] - ) + values: words.Select(word => char.ToUpper(word[index: 0], CultureInfo.GetCultureInfo("en-EN")) + word[1..]) ); } @@ -44,10 +41,7 @@ public static string ToSnakeCase(this string value) if (words.Length == 1) return value.ToLower(CultureInfo.GetCultureInfo("en-EN")); - return string.Join( - separator: "_", - values: words.Select(word => word.ToLower(CultureInfo.GetCultureInfo("en-EN"))) - ); + return string.Join(separator: "_", values: words.Select(word => word.ToLower(CultureInfo.GetCultureInfo("en-EN")))); } public static string ToKebabCase(this string value) @@ -59,10 +53,7 @@ public static string ToKebabCase(this string value) if (words.Length == 1) return value.ToLower(CultureInfo.GetCultureInfo("en-EN")); - return string.Join( - separator: "-", - values: words.Select(word => word.ToLower(CultureInfo.GetCultureInfo("en-EN"))) - ); + return string.Join(separator: "-", values: words.Select(word => word.ToLower(CultureInfo.GetCultureInfo("en-EN")))); } public static string ToAbbreviation(this string value) @@ -74,11 +65,6 @@ public static string ToAbbreviation(this string value) if (words.Length == 1) return char.ToLower(value[index: 0], CultureInfo.GetCultureInfo("en-EN")).ToString(); - return string.Join( - string.Empty, - values: words.Select( - word => char.ToLower(word[index: 0], CultureInfo.GetCultureInfo("en-EN")) - ) - ); + return string.Join(string.Empty, values: words.Select(word => char.ToLower(word[index: 0], CultureInfo.GetCultureInfo("en-EN")))); } } diff --git a/src/corePackages/Core.CodeGen/Code/StringWordExtension.cs b/src/corePackages/Core.CodeGen/Code/StringWordExtension.cs index 63c8d03..ee098d0 100644 --- a/src/corePackages/Core.CodeGen/Code/StringWordExtension.cs +++ b/src/corePackages/Core.CodeGen/Code/StringWordExtension.cs @@ -6,10 +6,7 @@ namespace Core.CodeGen.Code; public static class StringWordExtension { public static string[] GetWords(this string value) => - Regex - .Split(value, pattern: @"(? !string.IsNullOrEmpty(word)) - .ToArray(); + Regex.Split(value, pattern: @"(? !string.IsNullOrEmpty(word)).ToArray(); public static string ToPlural(this string value) => PluralizationProvider.Pluralize(value); diff --git a/src/corePackages/Core.CodeGen/File/DirectoryHelper.cs b/src/corePackages/Core.CodeGen/File/DirectoryHelper.cs index 959163d..e7ea924 100644 --- a/src/corePackages/Core.CodeGen/File/DirectoryHelper.cs +++ b/src/corePackages/Core.CodeGen/File/DirectoryHelper.cs @@ -9,8 +9,7 @@ public static string AssemblyDirectory { get { - string codeBase = - PlatformHelper.GetDirectoryHeader() + Assembly.GetExecutingAssembly().Location; + string codeBase = PlatformHelper.GetDirectoryHeader() + Assembly.GetExecutingAssembly().Location; UriBuilder uri = new(codeBase); string path = Uri.UnescapeDataString(uri.Path); return Path.GetDirectoryName(path)!; diff --git a/src/corePackages/Core.CodeGen/TemplateEngine/Scriban/ScribanStringFunctionsExtensions.cs b/src/corePackages/Core.CodeGen/TemplateEngine/Scriban/ScribanStringFunctionsExtensions.cs index b6ad3de..3bc4346 100644 --- a/src/corePackages/Core.CodeGen/TemplateEngine/Scriban/ScribanStringFunctionsExtensions.cs +++ b/src/corePackages/Core.CodeGen/TemplateEngine/Scriban/ScribanStringFunctionsExtensions.cs @@ -19,6 +19,5 @@ public class ScribanStringFunctionsExtensions : StringFunctions public static string Singular(string input) => input.ToSingular(); - public static string Words(string input) => - string.Join(separator: ' ', value: input.GetWords()); + public static string Words(string input) => string.Join(separator: ' ', value: input.GetWords()); } diff --git a/src/corePackages/Core.CodeGen/TemplateEngine/TemplateEngine.cs b/src/corePackages/Core.CodeGen/TemplateEngine/TemplateEngine.cs index 9ededa6..ed51f7a 100644 --- a/src/corePackages/Core.CodeGen/TemplateEngine/TemplateEngine.cs +++ b/src/corePackages/Core.CodeGen/TemplateEngine/TemplateEngine.cs @@ -26,17 +26,9 @@ ITemplateData templateData { string templateFileText = await System.IO.File.ReadAllTextAsync(templateFilePath); - string newRenderedFileText = await _templateRenderer.RenderAsync( - templateFileText, - templateData - ); + string newRenderedFileText = await _templateRenderer.RenderAsync(templateFileText, templateData); string newRenderedFilePath = await _templateRenderer.RenderAsync( - template: getOutputFilePath( - templateFilePath, - templateDir, - replacePathVariable, - outputDir - ), + template: getOutputFilePath(templateFilePath, templateDir, replacePathVariable, outputDir), templateData ); @@ -55,13 +47,7 @@ ITemplateData templateData List newRenderedFilePaths = new(); foreach (string templateFilePath in templateFilePaths) { - string newRenderedFilePath = await RenderFileAsync( - templateFilePath, - templateDir, - replacePathVariable, - outputDir, - templateData - ); + string newRenderedFilePath = await RenderFileAsync(templateFilePath, templateDir, replacePathVariable, outputDir, templateData); newRenderedFilePaths.Add(newRenderedFilePath); } @@ -77,10 +63,7 @@ string outputDir { string outputFilePath = templateFilePath; foreach (KeyValuePair replacePathVariableItem in replacePathVariable) - outputFilePath = outputFilePath.Replace( - replacePathVariableItem.Key, - replacePathVariableItem.Value - ); + outputFilePath = outputFilePath.Replace(replacePathVariableItem.Key, replacePathVariableItem.Value); outputFilePath = outputFilePath .Replace(templateDir, outputDir) .Replace(oldValue: $".{_templateRenderer.TemplateExtension}", string.Empty); diff --git a/src/nArchGen/Application/Features/Create/Commands/New/CreateNewProjectCommand.cs b/src/nArchGen/Application/Features/Create/Commands/New/CreateNewProjectCommand.cs index a1687bf..6b9aeba 100644 --- a/src/nArchGen/Application/Features/Create/Commands/New/CreateNewProjectCommand.cs +++ b/src/nArchGen/Application/Features/Create/Commands/New/CreateNewProjectCommand.cs @@ -23,8 +23,7 @@ public CreateNewProjectCommand(string projectName, bool isThereSecurityMechanism IsThereSecurityMechanism = isThereSecurityMechanism; } - public class CreateNewProjectCommandHandler - : IStreamRequestHandler + public class CreateNewProjectCommandHandler : IStreamRequestHandler { public async IAsyncEnumerable Handle( CreateNewProjectCommand request, @@ -38,16 +37,14 @@ [EnumeratorCancellation] CancellationToken cancellationToken yield return response; response.OutputMessage = null; await downloadStarterProject(request.ProjectName); - response.LastOperationMessage = - "Starter project has been cloned from 'https://github.com/kodlamaio-projects/nArchitecture'."; + response.LastOperationMessage = "Starter project has been cloned from 'https://github.com/kodlamaio-projects/nArchitecture'."; response.CurrentStatusMessage = "Preparing project..."; yield return response; await renameProject(request.ProjectName); if (!request.IsThereSecurityMechanism) await removeSecurityMechanism(request.ProjectName); - response.LastOperationMessage = - $"Project has been prepared with {request.ProjectName.ToPascalCase()}."; + response.LastOperationMessage = $"Project has been prepared with {request.ProjectName.ToPascalCase()}."; ICollection newFiles = DirectoryHelper.GetFilesInDirectoryTree( root: $"{Environment.CurrentDirectory}/{request.ProjectName}", @@ -63,16 +60,14 @@ [EnumeratorCancellation] CancellationToken cancellationToken response.NewFilePathsResult = newFiles; response.OutputMessage = $":warning: Check the configuration that has name 'appsettings.json' in 'src/{request.ProjectName.ToCamelCase()}'."; - response.OutputMessage = - ":warning: Run 'Update-Database' nuget command on the Persistence layer to apply initial migration."; + response.OutputMessage = ":warning: Run 'Update-Database' nuget command on the Persistence layer to apply initial migration."; yield return response; } private async Task downloadStarterProject(string projectName) { // Download zip on url - string releaseUrl = - "https://github.com/kodlamaio-projects/nArchitecture/archive/refs/tags/v0.1.0.zip"; + string releaseUrl = "https://github.com/kodlamaio-projects/nArchitecture/archive/refs/tags/v0.1.0.zip"; using HttpClient client = new(); using HttpResponseMessage response = await client.GetAsync(releaseUrl); response.EnsureSuccessStatusCode(); @@ -105,10 +100,7 @@ await replaceFileContentWithProjectName( ); string projectPath = $"{Environment.CurrentDirectory}/src/{projectName.ToCamelCase()}"; - Directory.Move( - sourceDirName: $"{Environment.CurrentDirectory}/src/starterProject", - projectPath - ); + Directory.Move(sourceDirName: $"{Environment.CurrentDirectory}/src/starterProject", projectPath); await replaceFileContentWithProjectName( path: $"{Environment.CurrentDirectory}/{projectName.ToPascalCase()}.sln", @@ -116,8 +108,7 @@ await replaceFileContentWithProjectName( projectName: projectName.ToCamelCase() ); - string testProjectDir = - $"{Environment.CurrentDirectory}/tests/{projectName.ToPascalCase()}.Application.Tests"; + string testProjectDir = $"{Environment.CurrentDirectory}/tests/{projectName.ToPascalCase()}.Application.Tests"; Directory.Move( sourceDirName: $"{Environment.CurrentDirectory}/tests/StarterProject.Application.Tests/", destDirName: testProjectDir @@ -182,11 +173,7 @@ await replaceFileContentWithProjectName( Directory.SetCurrentDirectory("../"); - static async Task replaceFileContentWithProjectName( - string path, - string search, - string projectName - ) + static async Task replaceFileContentWithProjectName(string path, string search, string projectName) { if (path.Contains(search)) { @@ -337,7 +324,7 @@ await FileHelper.RemoveContentAsync( "using Microsoft.OpenApi.Models;\n", "builder.Services.AddSecurityServices();\n", "const string tokenOptionsConfigurationSection = \"TokenOptions\";\nTokenOptions tokenOptions =\n builder.Configuration.GetSection(tokenOptionsConfigurationSection).Get()\n ?? throw new InvalidOperationException($\"\\\"{tokenOptionsConfigurationSection}\\\" section cannot found in configuration.\");\nbuilder\n .Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)\n .AddJwtBearer(options =>\n {\n options.TokenValidationParameters = new TokenValidationParameters\n {\n ValidateIssuer = true,\n ValidateAudience = true,\n ValidateLifetime = true,\n ValidIssuer = tokenOptions.Issuer,\n ValidAudience = tokenOptions.Audience,\n ValidateIssuerSigningKey = true,\n IssuerSigningKey = SecurityKeyHelper.CreateSecurityKey(tokenOptions.SecurityKey)\n };\n });\n\n", - " opt.AddSecurityDefinition(\n name: \"Bearer\",\n securityScheme: new OpenApiSecurityScheme\n {\n Name = \"Authorization\",\n Type = SecuritySchemeType.Http,\n Scheme = \"Bearer\",\n BearerFormat = \"JWT\",\n In = ParameterLocation.Header,\n Description =\n \"JWT Authorization header using the Bearer scheme. Example: \\\"Authorization: Bearer YOUR_TOKEN\\\". \\r\\n\\r\\n\"\n + \"`Enter your token in the text input below.`\"\n }\n );\n opt.OperationFilter();\n", + " opt.AddSecurityDefinition(\n name: \"Bearer\",\n securityScheme: new OpenApiSecurityScheme\n {\n Name = \"Authorization\",\n Type = SecuritySchemeType.Http,\n Scheme = \"Bearer\",\n BearerFormat = \"JWT\",\n In = ParameterLocation.Header,\n Description =\n \"JWT Authorization header using the Bearer scheme. Example: \\\"Authorization: Bearer YOUR_TOKEN\\\". \\r\\n\\r\\n\"\n + \"`Enter your token in the text input below.`\"\n }\n );\n opt.OperationFilter();\n", "app.UseAuthentication();\n", "app.UseAuthorization();\n" } @@ -350,16 +337,13 @@ private async Task initializeGitRepository(string projectName) await GitCommandHelper.RunAsync($"init"); await GitCommandHelper.RunAsync($"branch -m master main"); await downloadCorePackages(projectName); - await GitCommandHelper.CommitChangesAsync( - "chore: initial commit from nArchitecture.Gen" - ); + await GitCommandHelper.CommitChangesAsync("chore: initial commit from nArchitecture.Gen"); Directory.SetCurrentDirectory("../"); } private async Task downloadCorePackages(string projectName) { - string releaseUrl = - "https://github.com/kodlamaio-projects/nArchitecture.Core/archive/refs/tags/v0.1.0.zip"; + string releaseUrl = "https://github.com/kodlamaio-projects/nArchitecture.Core/archive/refs/tags/v0.1.0.zip"; using HttpClient client = new(); using HttpResponseMessage response = await client.GetAsync(releaseUrl); response.EnsureSuccessStatusCode(); diff --git a/src/nArchGen/Application/Features/Generate/Commands/Command/GenerateCommandCommand.cs b/src/nArchGen/Application/Features/Generate/Commands/Command/GenerateCommandCommand.cs index 21338d0..8283f4d 100644 --- a/src/nArchGen/Application/Features/Generate/Commands/Command/GenerateCommandCommand.cs +++ b/src/nArchGen/Application/Features/Generate/Commands/Command/GenerateCommandCommand.cs @@ -18,16 +18,12 @@ public class GenerateCommandCommand : IStreamRequest public string ProjectPath { get; set; } = null!; public CommandTemplateData CommandTemplateData { get; set; } = null!; - public class GenerateCommandCommandHandler - : IStreamRequestHandler + public class GenerateCommandCommandHandler : IStreamRequestHandler { private readonly ITemplateEngine _templateEngine; private readonly GenerateBusinessRules _businessRules; - public GenerateCommandCommandHandler( - ITemplateEngine templateEngine, - GenerateBusinessRules businessRules - ) + public GenerateCommandCommandHandler(ITemplateEngine templateEngine, GenerateBusinessRules businessRules) { _templateEngine = templateEngine; _businessRules = businessRules; @@ -56,29 +52,14 @@ await _businessRules.FileShouldNotBeExists( response.CurrentStatusMessage = "Generating Application layer codes..."; yield return response; - newFilePaths.AddRange( - await generateApplicationCodes(request.ProjectPath, request.CommandTemplateData) - ); - updatedFilePaths.AddRange( - await injectOperationClaims( - request.ProjectPath, - request.FeatureName, - request.CommandTemplateData - ) - ); + newFilePaths.AddRange(await generateApplicationCodes(request.ProjectPath, request.CommandTemplateData)); + updatedFilePaths.AddRange(await injectOperationClaims(request.ProjectPath, request.FeatureName, request.CommandTemplateData)); response.LastOperationMessage = "Application layer codes have been generated."; response.CurrentStatusMessage = "Adding endpoint to WebAPI..."; yield return response; - updatedFilePaths.AddRange( - await injectWebApiEndpoint( - request.ProjectPath, - request.FeatureName, - request.CommandTemplateData - ) - ); - response.LastOperationMessage = - $"New endpoint has been add to {request.FeatureName.ToPascalCase()}Controller."; + updatedFilePaths.AddRange(await injectWebApiEndpoint(request.ProjectPath, request.FeatureName, request.CommandTemplateData)); + response.LastOperationMessage = $"New endpoint has been add to {request.FeatureName.ToPascalCase()}Controller."; response.CurrentStatusMessage = "Completed."; response.NewFilePathsResult = newFilePaths; @@ -86,10 +67,7 @@ await injectWebApiEndpoint( yield return response; } - private async Task> generateApplicationCodes( - string projectPath, - CommandTemplateData commandTemplateData - ) + private async Task> generateApplicationCodes(string projectPath, CommandTemplateData commandTemplateData) { string templateDir = PlatformHelper.SecuredPathJoin( DirectoryHelper.AssemblyDirectory, @@ -131,10 +109,7 @@ CommandTemplateData commandTemplateData async line => await _templateEngine.RenderAsync(line, commandTemplateData) ) ); - await CSharpCodeInjector.AddCodeLinesAsPropertyAsync( - featureOperationClaimFilePath, - commandOperationClaimPropertyCodeLines - ); + await CSharpCodeInjector.AddCodeLinesAsPropertyAsync(featureOperationClaimFilePath, commandOperationClaimPropertyCodeLines); string operationClaimsEntityConfigurationFilePath = PlatformHelper.SecuredPathJoin( projectPath, @@ -165,11 +140,7 @@ await CSharpCodeInjector.AddCodeLinesToRegionAsync( featureName ); - return new[] - { - featureOperationClaimFilePath, - operationClaimsEntityConfigurationFilePath - }; + return new[] { featureOperationClaimFilePath, operationClaimsEntityConfigurationFilePath }; } private async Task> generateFolderCodes( @@ -179,17 +150,10 @@ CommandTemplateData commandTemplateData ) { List templateFilePaths = DirectoryHelper - .GetFilesInDirectoryTree( - templateDir, - searchPattern: $"*.{_templateEngine.TemplateExtension}" - ) + .GetFilesInDirectoryTree(templateDir, searchPattern: $"*.{_templateEngine.TemplateExtension}") .ToList(); Dictionary replacePathVariable = - new() - { - { "FEATURE", "{{ feature_name | string.pascalcase }}" }, - { "COMMAND", "{{ command_name | string.pascalcase }}" } - }; + new() { { "FEATURE", "{{ feature_name | string.pascalcase }}" }, { "COMMAND", "{{ command_name | string.pascalcase }}" } }; ICollection newRenderedFilePaths = await _templateEngine.RenderFileAsync( templateFilePaths, templateDir, @@ -206,12 +170,7 @@ private async Task> injectWebApiEndpoint( CommandTemplateData commandTemplateData ) { - string controllerFilePath = PlatformHelper.SecuredPathJoin( - projectPath, - "WebAPI", - "Controllers", - $"{featureName}Controller.cs" - ); + string controllerFilePath = PlatformHelper.SecuredPathJoin(projectPath, "WebAPI", "Controllers", $"{featureName}Controller.cs"); string[] controllerEndPointMethodTemplateCodeLines = await File.ReadAllLinesAsync( PlatformHelper.SecuredPathJoin( @@ -222,9 +181,7 @@ CommandTemplateData commandTemplateData ) ); string[] controllerEndPointMethodRenderedCodeLines = await Task.WhenAll( - controllerEndPointMethodTemplateCodeLines.Select( - async line => await _templateEngine.RenderAsync(line, commandTemplateData) - ) + controllerEndPointMethodTemplateCodeLines.Select(async line => await _templateEngine.RenderAsync(line, commandTemplateData)) ); await CSharpCodeInjector.AddMethodToClass( @@ -242,14 +199,9 @@ await CSharpCodeInjector.AddMethodToClass( ) ); string[] commandUsingNameSpaceRenderedCodeLines = await Task.WhenAll( - commandUsingNameSpaceTemplateCodeLines.Select( - async line => await _templateEngine.RenderAsync(line, commandTemplateData) - ) - ); - await CSharpCodeInjector.AddUsingToFile( - controllerFilePath, - commandUsingNameSpaceRenderedCodeLines + commandUsingNameSpaceTemplateCodeLines.Select(async line => await _templateEngine.RenderAsync(line, commandTemplateData)) ); + await CSharpCodeInjector.AddUsingToFile(controllerFilePath, commandUsingNameSpaceRenderedCodeLines); return new[] { controllerFilePath }; } diff --git a/src/nArchGen/Application/Features/Generate/Commands/Crud/GenerateCrudCommand.cs b/src/nArchGen/Application/Features/Generate/Commands/Crud/GenerateCrudCommand.cs index a1e0afa..47854e7 100644 --- a/src/nArchGen/Application/Features/Generate/Commands/Crud/GenerateCrudCommand.cs +++ b/src/nArchGen/Application/Features/Generate/Commands/Crud/GenerateCrudCommand.cs @@ -16,16 +16,12 @@ public class GenerateCrudCommand : IStreamRequest public CrudTemplateData CrudTemplateData { get; set; } public string DbContextName { get; set; } - public class GenerateCrudCommandHandler - : IStreamRequestHandler + public class GenerateCrudCommandHandler : IStreamRequestHandler { private readonly ITemplateEngine _templateEngine; private readonly GenerateBusinessRules _businessRules; - public GenerateCrudCommandHandler( - ITemplateEngine templateEngine, - GenerateBusinessRules businessRules - ) + public GenerateCrudCommandHandler(ITemplateEngine templateEngine, GenerateBusinessRules businessRules) { _templateEngine = templateEngine; _businessRules = businessRules; @@ -36,50 +32,35 @@ public async IAsyncEnumerable Handle( [EnumeratorCancellation] CancellationToken cancellationToken ) { - await _businessRules.EntityClassShouldBeInhreitEntityBaseClass( - request.ProjectPath, - request.CrudTemplateData.Entity.Name - ); + await _businessRules.EntityClassShouldBeInhreitEntityBaseClass(request.ProjectPath, request.CrudTemplateData.Entity.Name); GeneratedCrudResponse response = new(); List newFilePaths = new(); List updatedFilePaths = new(); - response.CurrentStatusMessage = - $"Adding {request.CrudTemplateData.Entity.Name} entity to BaseContext."; + response.CurrentStatusMessage = $"Adding {request.CrudTemplateData.Entity.Name} entity to BaseContext."; yield return response; - updatedFilePaths.Add( - await injectEntityToContext(request.ProjectPath, request.CrudTemplateData) - ); - response.LastOperationMessage = - $"{request.CrudTemplateData.Entity.Name} has been added to BaseContext."; + updatedFilePaths.Add(await injectEntityToContext(request.ProjectPath, request.CrudTemplateData)); + response.LastOperationMessage = $"{request.CrudTemplateData.Entity.Name} has been added to BaseContext."; response.CurrentStatusMessage = "Generating Persistence layer codes..."; yield return response; - newFilePaths.AddRange( - await generatePersistenceCodes(request.ProjectPath, request.CrudTemplateData) - ); + newFilePaths.AddRange(await generatePersistenceCodes(request.ProjectPath, request.CrudTemplateData)); response.LastOperationMessage = "Persistence layer codes have been generated."; response.CurrentStatusMessage = "Generating Application layer codes..."; yield return response; - newFilePaths.AddRange( - await generateApplicationCodes(request.ProjectPath, request.CrudTemplateData) - ); + newFilePaths.AddRange(await generateApplicationCodes(request.ProjectPath, request.CrudTemplateData)); response.LastOperationMessage = "Application layer codes have been generated."; response.CurrentStatusMessage = "Adding service registrations..."; yield return response; - updatedFilePaths.AddRange( - await injectServiceRegistrations(request.ProjectPath, request.CrudTemplateData) - ); + updatedFilePaths.AddRange(await injectServiceRegistrations(request.ProjectPath, request.CrudTemplateData)); response.LastOperationMessage = "Service registrations have been added."; response.CurrentStatusMessage = "Generating WebAPI layer codes..."; yield return response; - newFilePaths.AddRange( - await generateWebApiCodes(request.ProjectPath, request.CrudTemplateData) - ); + newFilePaths.AddRange(await generateWebApiCodes(request.ProjectPath, request.CrudTemplateData)); response.LastOperationMessage = "WebAPI layer codes have been generated."; response.CurrentStatusMessage = "Completed."; @@ -88,10 +69,7 @@ await generateWebApiCodes(request.ProjectPath, request.CrudTemplateData) yield return response; } - private async Task injectEntityToContext( - string projectPath, - CrudTemplateData crudTemplateData - ) + private async Task injectEntityToContext(string projectPath, CrudTemplateData crudTemplateData) { string contextFilePath = PlatformHelper.SecuredPathJoin( projectPath, @@ -118,26 +96,15 @@ CrudTemplateData crudTemplateData "EntityContextProperty.cs.sbn" ) ); - string dbSetPropertyCodeLine = await _templateEngine.RenderAsync( - dbSetPropertyTemplateCodeLine, - crudTemplateData - ); - bool isExists = (await File.ReadAllLinesAsync(contextFilePath)).Any( - line => line.Contains(dbSetPropertyCodeLine) - ); + string dbSetPropertyCodeLine = await _templateEngine.RenderAsync(dbSetPropertyTemplateCodeLine, crudTemplateData); + bool isExists = (await File.ReadAllLinesAsync(contextFilePath)).Any(line => line.Contains(dbSetPropertyCodeLine)); if (!isExists) - await CSharpCodeInjector.AddCodeLinesAsPropertyAsync( - contextFilePath, - codeLines: new[] { dbSetPropertyCodeLine } - ); + await CSharpCodeInjector.AddCodeLinesAsPropertyAsync(contextFilePath, codeLines: new[] { dbSetPropertyCodeLine }); return contextFilePath; } - private async Task> generatePersistenceCodes( - string projectPath, - CrudTemplateData crudTemplateData - ) + private async Task> generatePersistenceCodes(string projectPath, CrudTemplateData crudTemplateData) { string templateDir = PlatformHelper.SecuredPathJoin( DirectoryHelper.AssemblyDirectory, @@ -152,10 +119,7 @@ CrudTemplateData crudTemplateData ); } - private async Task> generateApplicationCodes( - string projectPath, - CrudTemplateData crudTemplateData - ) + private async Task> generateApplicationCodes(string projectPath, CrudTemplateData crudTemplateData) { string templateDir = PlatformHelper.SecuredPathJoin( DirectoryHelper.AssemblyDirectory, @@ -171,10 +135,7 @@ CrudTemplateData crudTemplateData ); } - private async Task> generateWebApiCodes( - string projectPath, - CrudTemplateData crudTemplateData - ) + private async Task> generateWebApiCodes(string projectPath, CrudTemplateData crudTemplateData) { string templateDir = PlatformHelper.SecuredPathJoin( DirectoryHelper.AssemblyDirectory, @@ -189,17 +150,10 @@ CrudTemplateData crudTemplateData ); } - private async Task> generateFolderCodes( - string templateDir, - string outputDir, - CrudTemplateData crudTemplateData - ) + private async Task> generateFolderCodes(string templateDir, string outputDir, CrudTemplateData crudTemplateData) { var templateFilePaths = DirectoryHelper - .GetFilesInDirectoryTree( - templateDir, - searchPattern: $"*.{_templateEngine.TemplateExtension}" - ) + .GetFilesInDirectoryTree(templateDir, searchPattern: $"*.{_templateEngine.TemplateExtension}") .ToList(); Dictionary replacePathVariable = new() @@ -217,10 +171,7 @@ CrudTemplateData crudTemplateData return newRenderedFilePaths; } - private async Task> injectServiceRegistrations( - string projectPath, - CrudTemplateData crudTemplateData - ) + private async Task> injectServiceRegistrations(string projectPath, CrudTemplateData crudTemplateData) { #region Persistence string persistenceServiceRegistrationFilePath = PlatformHelper.SecuredPathJoin( @@ -237,18 +188,13 @@ CrudTemplateData crudTemplateData "EntityRepositoryServiceRegistration.cs.sbn" ) ); - string persistenceServiceRegistrationRenderedCodeLine = - await _templateEngine.RenderAsync( - persistenceServiceRegistrationTemplateCodeLine, - crudTemplateData - ); + string persistenceServiceRegistrationRenderedCodeLine = await _templateEngine.RenderAsync( + persistenceServiceRegistrationTemplateCodeLine, + crudTemplateData + ); await CSharpCodeInjector.AddUsingToFile( persistenceServiceRegistrationFilePath, - usingLines: new[] - { - "using Application.Services.Repositories;", - "using Persistence.Repositories;" - } + usingLines: new[] { "using Application.Services.Repositories;", "using Persistence.Repositories;" } ); await CSharpCodeInjector.AddCodeLinesToMethodAsync( persistenceServiceRegistrationFilePath, @@ -258,27 +204,24 @@ await CSharpCodeInjector.AddCodeLinesToMethodAsync( #endregion #region Application - string applicationServiceRegistrationNameSpaceUsingFilePath = - PlatformHelper.SecuredPathJoin( - projectPath, - "Application", - "ApplicationServiceRegistration.cs" - ); + string applicationServiceRegistrationNameSpaceUsingFilePath = PlatformHelper.SecuredPathJoin( + projectPath, + "Application", + "ApplicationServiceRegistration.cs" + ); - string applicationServiceRegistrationNameSpaceUsingTemplateCodeLine = - await File.ReadAllTextAsync( - PlatformHelper.SecuredPathJoin( - DirectoryHelper.AssemblyDirectory, - Templates.Paths.Crud, - "Lines", - "EntityServiceRegistrationNameSpaceUsing.cs.sbn" - ) - ); - string applicationServiceRegistrationNameSpaceUsingRenderedCodeLine = - await _templateEngine.RenderAsync( - applicationServiceRegistrationNameSpaceUsingTemplateCodeLine, - crudTemplateData - ); + string applicationServiceRegistrationNameSpaceUsingTemplateCodeLine = await File.ReadAllTextAsync( + PlatformHelper.SecuredPathJoin( + DirectoryHelper.AssemblyDirectory, + Templates.Paths.Crud, + "Lines", + "EntityServiceRegistrationNameSpaceUsing.cs.sbn" + ) + ); + string applicationServiceRegistrationNameSpaceUsingRenderedCodeLine = await _templateEngine.RenderAsync( + applicationServiceRegistrationNameSpaceUsingTemplateCodeLine, + crudTemplateData + ); await CSharpCodeInjector.AddUsingToFile( applicationServiceRegistrationNameSpaceUsingFilePath, usingLines: new[] { applicationServiceRegistrationNameSpaceUsingRenderedCodeLine } @@ -298,11 +241,10 @@ await CSharpCodeInjector.AddUsingToFile( "EntityServiceRegistration.cs.sbn" ) ); - string applicationServiceRegistrationRenderedCodeLine = - await _templateEngine.RenderAsync( - applicationServiceRegistrationTemplateCodeLine, - crudTemplateData - ); + string applicationServiceRegistrationRenderedCodeLine = await _templateEngine.RenderAsync( + applicationServiceRegistrationTemplateCodeLine, + crudTemplateData + ); await CSharpCodeInjector.AddCodeLinesToMethodAsync( applicationServiceRegistrationFilePath, methodName: "AddApplicationServices", @@ -310,11 +252,7 @@ await CSharpCodeInjector.AddCodeLinesToMethodAsync( ); #endregion - return new[] - { - persistenceServiceRegistrationFilePath, - applicationServiceRegistrationFilePath - }; + return new[] { persistenceServiceRegistrationFilePath, applicationServiceRegistrationFilePath }; } } } diff --git a/src/nArchGen/Application/Features/Generate/Commands/Query/GenerateQueryCommand.cs b/src/nArchGen/Application/Features/Generate/Commands/Query/GenerateQueryCommand.cs index 9dbd49d..2370d62 100644 --- a/src/nArchGen/Application/Features/Generate/Commands/Query/GenerateQueryCommand.cs +++ b/src/nArchGen/Application/Features/Generate/Commands/Query/GenerateQueryCommand.cs @@ -18,16 +18,12 @@ public class GenerateQueryCommand : IStreamRequest public string ProjectPath { get; set; } = null!; public QueryTemplateData QueryTemplateData { get; set; } = null!; - public class GenerateQueryCommandHandler - : IStreamRequestHandler + public class GenerateQueryCommandHandler : IStreamRequestHandler { private readonly ITemplateEngine _templateEngine; private readonly GenerateBusinessRules _businessRules; - public GenerateQueryCommandHandler( - ITemplateEngine templateEngine, - GenerateBusinessRules businessRules - ) + public GenerateQueryCommandHandler(ITemplateEngine templateEngine, GenerateBusinessRules businessRules) { _templateEngine = templateEngine; _businessRules = businessRules; @@ -56,29 +52,14 @@ await _businessRules.FileShouldNotBeExists( response.CurrentStatusMessage = "Generating Application layer codes..."; yield return response; - newFilePaths.AddRange( - await generateApplicationCodes(request.ProjectPath, request.QueryTemplateData) - ); - updatedFilePaths.AddRange( - await injectOperationClaims( - request.ProjectPath, - request.FeatureName, - request.QueryTemplateData - ) - ); + newFilePaths.AddRange(await generateApplicationCodes(request.ProjectPath, request.QueryTemplateData)); + updatedFilePaths.AddRange(await injectOperationClaims(request.ProjectPath, request.FeatureName, request.QueryTemplateData)); response.LastOperationMessage = "Application layer codes have been generated."; response.CurrentStatusMessage = "Adding endpoint to WebAPI..."; yield return response; - updatedFilePaths.AddRange( - await injectWebApiEndpoint( - request.ProjectPath, - request.FeatureName, - request.QueryTemplateData - ) - ); - response.LastOperationMessage = - $"New endpoint has been add to {request.FeatureName.ToPascalCase()}Controller."; + updatedFilePaths.AddRange(await injectWebApiEndpoint(request.ProjectPath, request.FeatureName, request.QueryTemplateData)); + response.LastOperationMessage = $"New endpoint has been add to {request.FeatureName.ToPascalCase()}Controller."; response.CurrentStatusMessage = "Completed."; response.NewFilePathsResult = newFilePaths; @@ -86,10 +67,7 @@ await injectWebApiEndpoint( yield return response; } - private async Task> generateApplicationCodes( - string projectPath, - QueryTemplateData QueryTemplateData - ) + private async Task> generateApplicationCodes(string projectPath, QueryTemplateData QueryTemplateData) { string templateDir = PlatformHelper.SecuredPathJoin( DirectoryHelper.AssemblyDirectory, @@ -132,10 +110,7 @@ QueryTemplateData QueryTemplateData async line => await _templateEngine.RenderAsync(line, QueryTemplateData) ) ); - await CSharpCodeInjector.AddCodeLinesAsPropertyAsync( - featureOperationClaimFilePath, - queryOperationClaimPropertyCodeLines - ); + await CSharpCodeInjector.AddCodeLinesAsPropertyAsync(featureOperationClaimFilePath, queryOperationClaimPropertyCodeLines); string operationClaimsEntityConfigurationFilePath = PlatformHelper.SecuredPathJoin( projectPath, @@ -156,9 +131,7 @@ await CSharpCodeInjector.AddCodeLinesAsPropertyAsync( ) ); string[] queryOperationClaimSeedCodeLines = await Task.WhenAll( - queryOperationClaimSeedTemplateCodeLines.Select( - async line => await _templateEngine.RenderAsync(line, QueryTemplateData) - ) + queryOperationClaimSeedTemplateCodeLines.Select(async line => await _templateEngine.RenderAsync(line, QueryTemplateData)) ); await CSharpCodeInjector.AddCodeLinesToRegionAsync( operationClaimsEntityConfigurationFilePath, @@ -166,11 +139,7 @@ await CSharpCodeInjector.AddCodeLinesToRegionAsync( featureName ); - return new[] - { - featureOperationClaimFilePath, - operationClaimsEntityConfigurationFilePath - }; + return new[] { featureOperationClaimFilePath, operationClaimsEntityConfigurationFilePath }; } private async Task> generateFolderCodes( @@ -180,17 +149,10 @@ QueryTemplateData QueryTemplateData ) { List templateFilePaths = DirectoryHelper - .GetFilesInDirectoryTree( - templateDir, - searchPattern: $"*.{_templateEngine.TemplateExtension}" - ) + .GetFilesInDirectoryTree(templateDir, searchPattern: $"*.{_templateEngine.TemplateExtension}") .ToList(); Dictionary replacePathVariable = - new() - { - { "FEATURE", "{{ feature_name | string.pascalcase }}" }, - { "QUERY", "{{ query_name | string.pascalcase }}" } - }; + new() { { "FEATURE", "{{ feature_name | string.pascalcase }}" }, { "QUERY", "{{ query_name | string.pascalcase }}" } }; ICollection newRenderedFilePaths = await _templateEngine.RenderFileAsync( templateFilePaths, templateDir, @@ -207,12 +169,7 @@ private async Task> injectWebApiEndpoint( QueryTemplateData QueryTemplateData ) { - string controllerFilePath = PlatformHelper.SecuredPathJoin( - projectPath, - "WebAPI", - "Controllers", - $"{featureName}Controller.cs" - ); + string controllerFilePath = PlatformHelper.SecuredPathJoin(projectPath, "WebAPI", "Controllers", $"{featureName}Controller.cs"); string[] controllerEndPointMethodTemplateCodeLines = await File.ReadAllLinesAsync( PlatformHelper.SecuredPathJoin( DirectoryHelper.AssemblyDirectory, @@ -222,9 +179,7 @@ QueryTemplateData QueryTemplateData ) ); string[] controllerEndPointMethodRenderedCodeLines = await Task.WhenAll( - controllerEndPointMethodTemplateCodeLines.Select( - async line => await _templateEngine.RenderAsync(line, QueryTemplateData) - ) + controllerEndPointMethodTemplateCodeLines.Select(async line => await _templateEngine.RenderAsync(line, QueryTemplateData)) ); await CSharpCodeInjector.AddMethodToClass( @@ -242,14 +197,9 @@ await CSharpCodeInjector.AddMethodToClass( ) ); string[] queryUsingNameSpaceCodeLines = await Task.WhenAll( - queryUsingNameSpaceTemplateCodeLines.Select( - async line => await _templateEngine.RenderAsync(line, QueryTemplateData) - ) - ); - await CSharpCodeInjector.AddUsingToFile( - controllerFilePath, - queryUsingNameSpaceCodeLines + queryUsingNameSpaceTemplateCodeLines.Select(async line => await _templateEngine.RenderAsync(line, QueryTemplateData)) ); + await CSharpCodeInjector.AddUsingToFile(controllerFilePath, queryUsingNameSpaceCodeLines); return new[] { controllerFilePath }; } diff --git a/src/nArchGen/Application/Features/Generate/Rules/GenerateBusinessRules.cs b/src/nArchGen/Application/Features/Generate/Rules/GenerateBusinessRules.cs index 0fc72b6..5145211 100644 --- a/src/nArchGen/Application/Features/Generate/Rules/GenerateBusinessRules.cs +++ b/src/nArchGen/Application/Features/Generate/Rules/GenerateBusinessRules.cs @@ -9,10 +9,7 @@ namespace Application.Features.Generate.Rules; public class GenerateBusinessRules { - public async Task EntityClassShouldBeInhreitEntityBaseClass( - string projectPath, - string entityName - ) + public async Task EntityClassShouldBeInhreitEntityBaseClass(string projectPath, string entityName) { string[] fileContent = await File.ReadAllLinesAsync( PlatformHelper.SecuredPathJoin(projectPath, "Domain", "Entities", $"{entityName}.cs") @@ -28,13 +25,10 @@ string entityName ); Regex entityBaseClassRegex = new(@$"public\s+class\s+{entityName}\s*:\s*Entity\s*"); bool isExists = - fileContent.Any(line => line == entityBaseClassNameSpaceUsingTemplate) - && fileContent.Any(entityBaseClassRegex.IsMatch); + fileContent.Any(line => line == entityBaseClassNameSpaceUsingTemplate) && fileContent.Any(entityBaseClassRegex.IsMatch); if (!isExists) - throw new BusinessException( - GenerateBusinessMessages.EntityClassShouldBeInheritEntityBaseClass(entityName) - ); + throw new BusinessException(GenerateBusinessMessages.EntityClassShouldBeInheritEntityBaseClass(entityName)); } public Task FileShouldNotBeExists(string filePath) diff --git a/src/nArchGen/ConsoleUI/Commands/Generate/Command/GenerateCommandCliCommand.cs b/src/nArchGen/ConsoleUI/Commands/Generate/Command/GenerateCommandCliCommand.cs index 6de61c2..d92f7ce 100644 --- a/src/nArchGen/ConsoleUI/Commands/Generate/Command/GenerateCommandCliCommand.cs +++ b/src/nArchGen/ConsoleUI/Commands/Generate/Command/GenerateCommandCliCommand.cs @@ -41,9 +41,7 @@ public override async Task ExecuteAsync(CommandContext context, Settings se } }; - IAsyncEnumerable resultsStream = _mediator.CreateStream( - request: generateCommandCommand - ); + IAsyncEnumerable resultsStream = _mediator.CreateStream(request: generateCommandCommand); await AnsiConsole .Status() @@ -61,30 +59,20 @@ await AnsiConsole AnsiConsole.MarkupLine(result.OutputMessage); if (result.LastOperationMessage is not null) - AnsiConsole.MarkupLine( - $":check_mark_button: {result.LastOperationMessage}" - ); + AnsiConsole.MarkupLine($":check_mark_button: {result.LastOperationMessage}"); if (result.NewFilePathsResult is not null) { AnsiConsole.MarkupLine(":new_button: [green]Generated files:[/]"); foreach (string filePath in result.NewFilePathsResult) - AnsiConsole.Write( - new TextPath(filePath) - .StemColor(Color.Yellow) - .LeafColor(Color.Blue) - ); + AnsiConsole.Write(new TextPath(filePath).StemColor(Color.Yellow).LeafColor(Color.Blue)); } if (result.UpdatedFilePathsResult is not null) { AnsiConsole.MarkupLine(":up_button: [green]Updated files:[/]"); foreach (string filePath in result.UpdatedFilePathsResult) - AnsiConsole.Write( - new TextPath(filePath) - .StemColor(Color.Yellow) - .LeafColor(Color.Blue) - ); + AnsiConsole.Write(new TextPath(filePath).StemColor(Color.Yellow).LeafColor(Color.Blue)); } } } diff --git a/src/nArchGen/ConsoleUI/Commands/Generate/Command/GenerateCommandCliCommandSettings.cs b/src/nArchGen/ConsoleUI/Commands/Generate/Command/GenerateCommandCliCommandSettings.cs index 3e96821..0829b68 100644 --- a/src/nArchGen/ConsoleUI/Commands/Generate/Command/GenerateCommandCliCommandSettings.cs +++ b/src/nArchGen/ConsoleUI/Commands/Generate/Command/GenerateCommandCliCommandSettings.cs @@ -36,11 +36,7 @@ public class Settings : CommandSettings public string ProjectPath => ProjectName != null - ? PlatformHelper.SecuredPathJoin( - Environment.CurrentDirectory, - "src", - ProjectName.ToCamelCase() - ) + ? PlatformHelper.SecuredPathJoin(Environment.CurrentDirectory, "src", ProjectName.ToCamelCase()) : Environment.CurrentDirectory; public void CheckCommandName() @@ -51,29 +47,20 @@ public void CheckCommandName() return; } - CommandName = AnsiConsole.Prompt( - new TextPrompt("[blue]What is [green]new command name[/]?[/]") - ); + CommandName = AnsiConsole.Prompt(new TextPrompt("[blue]What is [green]new command name[/]?[/]")); } public void CheckFeatureName() { if (FeatureName is not null) { - AnsiConsole.MarkupLine( - $"[green]Feature[/] name that the command will be in is [blue]{FeatureName}[/]." - ); + AnsiConsole.MarkupLine($"[green]Feature[/] name that the command will be in is [blue]{FeatureName}[/]."); return; } - string?[] features = Directory - .GetDirectories($"{ProjectPath}/Application/Features") - .Select(Path.GetFileName) - .ToArray()!; + string?[] features = Directory.GetDirectories($"{ProjectPath}/Application/Features").Select(Path.GetFileName).ToArray()!; if (features.Length == 0) - throw new BusinessException( - $"No feature found in \"{ProjectPath}/Application/Features\"." - ); + throw new BusinessException($"No feature found in \"{ProjectPath}/Application/Features\"."); FeatureName = AnsiConsole.Prompt( new SelectionPrompt() @@ -94,11 +81,7 @@ public void CheckProjectName() } string[] layerFolders = { "Application", "Domain", "Persistence", "WebAPI" }; - if ( - layerFolders.All( - folder => Directory.Exists($"{Environment.CurrentDirectory}/{folder}") - ) - ) + if (layerFolders.All(folder => Directory.Exists($"{Environment.CurrentDirectory}/{folder}"))) return; string[] projects = Directory @@ -153,10 +136,7 @@ public void CheckMechanismOptions() .NotRequired() .PageSize(5) .MoreChoicesText("[grey](Move up and down to reveal more mechanisms)[/]") - .InstructionsText( - "[grey](Press [blue][/] to toggle a mechanism, " - + "[green][/] to accept)[/]" - ) + .InstructionsText("[grey](Press [blue][/] to toggle a mechanism, " + "[green][/] to accept)[/]") .AddChoices(mechanismsToPrompt) ); diff --git a/src/nArchGen/ConsoleUI/Commands/Generate/Crud/GenerateCrudCliCommand.cs b/src/nArchGen/ConsoleUI/Commands/Generate/Crud/GenerateCrudCliCommand.cs index ef7ebe7..a042ca1 100644 --- a/src/nArchGen/ConsoleUI/Commands/Generate/Crud/GenerateCrudCliCommand.cs +++ b/src/nArchGen/ConsoleUI/Commands/Generate/Crud/GenerateCrudCliCommand.cs @@ -25,17 +25,9 @@ public override async Task ExecuteAsync(CommandContext context, Settings se settings.CheckDbContextArgument(); settings.CheckMechanismOptions(); - string entityPath = PlatformHelper.SecuredPathJoin( - settings.ProjectPath, - "Domain", - "Entities", - $"{settings.EntityName}.cs" - ); - ICollection entityProperties = - await CSharpCodeReader.ReadClassPropertiesAsync(entityPath, settings.ProjectPath); - string entityIdType = ( - await CSharpCodeReader.ReadBaseClassGenericArgumentsAsync(entityPath) - ).First(); + string entityPath = PlatformHelper.SecuredPathJoin(settings.ProjectPath, "Domain", "Entities", $"{settings.EntityName}.cs"); + ICollection entityProperties = await CSharpCodeReader.ReadClassPropertiesAsync(entityPath, settings.ProjectPath); + string entityIdType = (await CSharpCodeReader.ReadBaseClassGenericArgumentsAsync(entityPath)).First(); GenerateCrudCommand generateCrudCommand = new() { @@ -45,9 +37,7 @@ await CSharpCodeReader.ReadBaseClassGenericArgumentsAsync(entityPath) { Name = settings.EntityName!, IdType = entityIdType, - Properties = entityProperties - .Where(property => property.AccessModifier == "public") - .ToArray() + Properties = entityProperties.Where(property => property.AccessModifier == "public").ToArray() }, IsCachingUsed = settings.IsCachingUsed, IsLoggingUsed = settings.IsLoggingUsed, @@ -58,9 +48,7 @@ await CSharpCodeReader.ReadBaseClassGenericArgumentsAsync(entityPath) ProjectPath = settings.ProjectPath }; - IAsyncEnumerable resultsStream = _mediator.CreateStream( - request: generateCrudCommand - ); + IAsyncEnumerable resultsStream = _mediator.CreateStream(request: generateCrudCommand); await AnsiConsole .Status() @@ -78,30 +66,20 @@ await AnsiConsole AnsiConsole.MarkupLine(result.OutputMessage); if (result.LastOperationMessage is not null) - AnsiConsole.MarkupLine( - $":check_mark_button: {result.LastOperationMessage}" - ); + AnsiConsole.MarkupLine($":check_mark_button: {result.LastOperationMessage}"); if (result.NewFilePathsResult is not null) { AnsiConsole.MarkupLine(":new_button: [green]Generated files:[/]"); foreach (string filePath in result.NewFilePathsResult) - AnsiConsole.Write( - new TextPath(filePath) - .StemColor(Color.Yellow) - .LeafColor(Color.Blue) - ); + AnsiConsole.Write(new TextPath(filePath).StemColor(Color.Yellow).LeafColor(Color.Blue)); } if (result.UpdatedFilePathsResult is not null) { AnsiConsole.MarkupLine(":up_button: [green]Updated files:[/]"); foreach (string filePath in result.UpdatedFilePathsResult) - AnsiConsole.Write( - new TextPath(filePath) - .StemColor(Color.Yellow) - .LeafColor(Color.Blue) - ); + AnsiConsole.Write(new TextPath(filePath).StemColor(Color.Yellow).LeafColor(Color.Blue)); } } } diff --git a/src/nArchGen/ConsoleUI/Commands/Generate/Crud/GenerateCrudCliCommandSettings.cs b/src/nArchGen/ConsoleUI/Commands/Generate/Crud/GenerateCrudCliCommandSettings.cs index 42414af..8dacb10 100644 --- a/src/nArchGen/ConsoleUI/Commands/Generate/Crud/GenerateCrudCliCommandSettings.cs +++ b/src/nArchGen/ConsoleUI/Commands/Generate/Crud/GenerateCrudCliCommandSettings.cs @@ -35,11 +35,7 @@ public class Settings : CommandSettings public string ProjectPath => ProjectName != null - ? PlatformHelper.SecuredPathJoin( - Environment.CurrentDirectory, - "src", - ProjectName.ToCamelCase() - ) + ? PlatformHelper.SecuredPathJoin(Environment.CurrentDirectory, "src", ProjectName.ToCamelCase()) : Environment.CurrentDirectory; public void CheckProjectName() @@ -53,11 +49,7 @@ public void CheckProjectName() } string[] layerFolders = { "Application", "Domain", "Persistence", "WebAPI" }; - if ( - layerFolders.All( - folder => Directory.Exists($"{Environment.CurrentDirectory}/{folder}") - ) - ) + if (layerFolders.All(folder => Directory.Exists($"{Environment.CurrentDirectory}/{folder}"))) return; string[] projects = Directory @@ -95,15 +87,10 @@ public void CheckEntityArgument() .Select(Path.GetFileNameWithoutExtension) .ToArray()!; if (entities.Length == 0) - throw new BusinessException( - $"No entities found in \"{ProjectPath}\\Domain\\Entities\"" - ); + throw new BusinessException($"No entities found in \"{ProjectPath}\\Domain\\Entities\""); EntityName = AnsiConsole.Prompt( - new SelectionPrompt() - .Title("What's your [green]entity[/]?") - .PageSize(10) - .AddChoices(entities) + new SelectionPrompt().Title("What's your [green]entity[/]?").PageSize(10).AddChoices(entities) ); } @@ -111,28 +98,19 @@ public void CheckDbContextArgument() { if (DbContextName is not null) { - AnsiConsole.MarkupLine( - $"Selected [green]DbContext[/] is [blue]{DbContextName}[/]." - ); + AnsiConsole.MarkupLine($"Selected [green]DbContext[/] is [blue]{DbContextName}[/]."); return; } string[] dbContexts = Directory - .GetFiles( - path: PlatformHelper.SecuredPathJoin(ProjectPath, "Persistence", "Contexts") - ) + .GetFiles(path: PlatformHelper.SecuredPathJoin(ProjectPath, "Persistence", "Contexts")) .Select(Path.GetFileNameWithoutExtension) .ToArray()!; if (dbContexts.Length == 0) - throw new BusinessException( - $"No DbContexts found in \"{ProjectPath}\\Persistence\\Contexts\"" - ); + throw new BusinessException($"No DbContexts found in \"{ProjectPath}\\Persistence\\Contexts\""); DbContextName = AnsiConsole.Prompt( - new SelectionPrompt() - .Title("What's your [green]DbContext[/]?") - .PageSize(5) - .AddChoices(dbContexts) + new SelectionPrompt().Title("What's your [green]DbContext[/]?").PageSize(5).AddChoices(dbContexts) ); } @@ -166,10 +144,7 @@ public void CheckMechanismOptions() .NotRequired() .PageSize(5) .MoreChoicesText("[grey](Move up and down to reveal more mechanisms)[/]") - .InstructionsText( - "[grey](Press [blue][/] to toggle a mechanism, " - + "[green][/] to accept)[/]" - ) + .InstructionsText("[grey](Press [blue][/] to toggle a mechanism, " + "[green][/] to accept)[/]") .AddChoices(mechanismsToPrompt) ); diff --git a/src/nArchGen/ConsoleUI/Commands/Generate/Query/GenerateQueryCliCommand.cs b/src/nArchGen/ConsoleUI/Commands/Generate/Query/GenerateQueryCliCommand.cs index cdafd3f..7a768b9 100644 --- a/src/nArchGen/ConsoleUI/Commands/Generate/Query/GenerateQueryCliCommand.cs +++ b/src/nArchGen/ConsoleUI/Commands/Generate/Query/GenerateQueryCliCommand.cs @@ -38,9 +38,7 @@ public override async Task ExecuteAsync(CommandContext context, Settings se } }; - IAsyncEnumerable resultsStream = _mediator.CreateStream( - request: generateQueryCommand - ); + IAsyncEnumerable resultsStream = _mediator.CreateStream(request: generateQueryCommand); await AnsiConsole .Status() @@ -58,30 +56,20 @@ await AnsiConsole AnsiConsole.MarkupLine(result.OutputMessage); if (result.LastOperationMessage is not null) - AnsiConsole.MarkupLine( - $":check_mark_button: {result.LastOperationMessage}" - ); + AnsiConsole.MarkupLine($":check_mark_button: {result.LastOperationMessage}"); if (result.NewFilePathsResult is not null) { AnsiConsole.MarkupLine(":new_button: [green]Generated files:[/]"); foreach (string filePath in result.NewFilePathsResult) - AnsiConsole.Write( - new TextPath(filePath) - .StemColor(Color.Yellow) - .LeafColor(Color.Blue) - ); + AnsiConsole.Write(new TextPath(filePath).StemColor(Color.Yellow).LeafColor(Color.Blue)); } if (result.UpdatedFilePathsResult is not null) { AnsiConsole.MarkupLine(":up_button: [green]Updated files:[/]"); foreach (string filePath in result.UpdatedFilePathsResult) - AnsiConsole.Write( - new TextPath(filePath) - .StemColor(Color.Yellow) - .LeafColor(Color.Blue) - ); + AnsiConsole.Write(new TextPath(filePath).StemColor(Color.Yellow).LeafColor(Color.Blue)); } } } diff --git a/src/nArchGen/ConsoleUI/Commands/Generate/Query/GenerateQueryCliCommandSettings.cs b/src/nArchGen/ConsoleUI/Commands/Generate/Query/GenerateQueryCliCommandSettings.cs index cf18b32..219d99e 100644 --- a/src/nArchGen/ConsoleUI/Commands/Generate/Query/GenerateQueryCliCommandSettings.cs +++ b/src/nArchGen/ConsoleUI/Commands/Generate/Query/GenerateQueryCliCommandSettings.cs @@ -30,11 +30,7 @@ public class Settings : CommandSettings public string ProjectPath => ProjectName != null - ? PlatformHelper.SecuredPathJoin( - Environment.CurrentDirectory, - "src", - ProjectName.ToCamelCase() - ) + ? PlatformHelper.SecuredPathJoin(Environment.CurrentDirectory, "src", ProjectName.ToCamelCase()) : Environment.CurrentDirectory; public void CheckQueryName() @@ -45,29 +41,20 @@ public void CheckQueryName() return; } - QueryName = AnsiConsole.Prompt( - new TextPrompt("[blue]What is [green]new query name[/]?[/]") - ); + QueryName = AnsiConsole.Prompt(new TextPrompt("[blue]What is [green]new query name[/]?[/]")); } public void CheckFeatureName() { if (FeatureName is not null) { - AnsiConsole.MarkupLine( - $"[green]Feature[/] name that the query will be in is [blue]{FeatureName}[/]." - ); + AnsiConsole.MarkupLine($"[green]Feature[/] name that the query will be in is [blue]{FeatureName}[/]."); return; } - string?[] features = Directory - .GetDirectories($"{ProjectPath}/Application/Features") - .Select(Path.GetFileName) - .ToArray()!; + string?[] features = Directory.GetDirectories($"{ProjectPath}/Application/Features").Select(Path.GetFileName).ToArray()!; if (features.Length == 0) - throw new BusinessException( - $"No feature found in \"{ProjectPath}/Application/Features\"." - ); + throw new BusinessException($"No feature found in \"{ProjectPath}/Application/Features\"."); FeatureName = AnsiConsole.Prompt( new SelectionPrompt() @@ -88,11 +75,7 @@ public void CheckProjectName() } string[] layerFolders = { "Application", "Domain", "Persistence", "WebAPI" }; - if ( - layerFolders.All( - folder => Directory.Exists($"{Environment.CurrentDirectory}/{folder}") - ) - ) + if (layerFolders.All(folder => Directory.Exists($"{Environment.CurrentDirectory}/{folder}"))) return; string[] projects = Directory @@ -143,10 +126,7 @@ public void CheckMechanismOptions() .NotRequired() .PageSize(5) .MoreChoicesText("[grey](Move up and down to reveal more mechanisms)[/]") - .InstructionsText( - "[grey](Press [blue][/] to toggle a mechanism, " - + "[green][/] to accept)[/]" - ) + .InstructionsText("[grey](Press [blue][/] to toggle a mechanism, " + "[green][/] to accept)[/]") .AddChoices(mechanismsToPrompt) ); diff --git a/src/nArchGen/ConsoleUI/Commands/New/CreateNewProjectCliCommand.cs b/src/nArchGen/ConsoleUI/Commands/New/CreateNewProjectCliCommand.cs index 11bac7c..5f4f1c0 100644 --- a/src/nArchGen/ConsoleUI/Commands/New/CreateNewProjectCliCommand.cs +++ b/src/nArchGen/ConsoleUI/Commands/New/CreateNewProjectCliCommand.cs @@ -20,10 +20,7 @@ public override async Task ExecuteAsync(CommandContext context, Settings se settings.CheckIsThereSecurityMechanismArgument(); CreateNewProjectCommand request = - new( - projectName: settings.ProjectName!, - isThereSecurityMechanism: settings.IsThereSecurityMechanism - ); + new(projectName: settings.ProjectName!, isThereSecurityMechanism: settings.IsThereSecurityMechanism); IAsyncEnumerable resultsStream = _mediator.CreateStream(request); @@ -40,19 +37,13 @@ await AnsiConsole ctx.Status(result.CurrentStatusMessage); if (result.LastOperationMessage is not null) - AnsiConsole.MarkupLine( - $":check_mark_button: {result.LastOperationMessage}" - ); + AnsiConsole.MarkupLine($":check_mark_button: {result.LastOperationMessage}"); if (result.NewFilePathsResult is not null) { AnsiConsole.MarkupLine(":new_button: [green]Generated files:[/]"); foreach (string filePath in result.NewFilePathsResult) - AnsiConsole.Write( - new TextPath(filePath) - .StemColor(Color.Yellow) - .LeafColor(Color.Blue) - ); + AnsiConsole.Write(new TextPath(filePath).StemColor(Color.Yellow).LeafColor(Color.Blue)); } if (result.OutputMessage is not null)