From 39e5feb808adcc98cf94815b5c8e8b34edf5986c Mon Sep 17 00:00:00 2001 From: "Eric Sibly [chullybun]" Date: Sun, 10 Mar 2024 14:13:58 -0700 Subject: [PATCH] LoadConfigAsync. (#20) --- CHANGELOG.md | 4 ++ README.md | 14 ++-- src/OnRamp/CodeGenOutputArgs.cs | 34 +++------ src/OnRamp/CodeGenerator.cs | 69 +++++++++++++------ src/OnRamp/CodeGeneratorArgsBase.cs | 4 +- src/OnRamp/Config/CodeGenCategoryAttribute.cs | 11 +-- src/OnRamp/Config/CodeGenClassAttribute.cs | 11 +-- .../CodeGenPropertyCollectionAttribute.cs | 11 +-- src/OnRamp/Config/ConfigBaseT.cs | 4 +- src/OnRamp/Config/ConfigRootBase.cs | 2 +- src/OnRamp/Console/AssemblyValidator.cs | 11 +-- src/OnRamp/Console/CodeGenConsole.cs | 23 ++----- src/OnRamp/Console/ConsoleLogger.cs | 11 +-- src/OnRamp/Console/ParametersValidator.cs | 11 +-- src/OnRamp/Generators/CodeGeneratorBaseT2.cs | 2 +- src/OnRamp/OnRamp.csproj | 8 +-- src/OnRamp/Scripts/CodeGenScript.cs | 4 +- src/OnRamp/Scripts/CodeGenScriptItem.cs | 6 +- src/OnRamp/Utility/HandlebarsHelpers.cs | 16 ++--- src/OnRamp/Utility/StreamExtensions.cs | 2 +- src/OnRamp/Utility/StreamLocator.cs | 4 +- src/OnRamp/Utility/StringConverter.cs | 2 +- tests/OnRamp.Test/OnRamp.Test.csproj | 8 +-- 23 files changed, 124 insertions(+), 148 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cd673ba..16f4a9e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ Represents the **NuGet** versions. +## v2.1.0 +- *Enhancement:* Added `CodeGenerator.LoadConfigAsync` to enable the loading of the configuration without having to execute the code generation. This is useful when needing to either further validate the configuration prior to execution, or be able to query the configuration without initiating the code generation. +- *Fixed:* All dependencies updated to the latest version. + ## v2.0.0 - *Enhancement:* **Breaking change** - underlying JSON serialization has been changed from `Newtonsoft.Json` to `System.Text.Json`, with new `Utility.JsonSerializer` encapsulating logic to enable. The following steps are required to migrate existing usage: - Rename all attribute references from `JsonProperty` to `JsonPropertyName`. diff --git a/README.md b/README.md index 9ec8ff6..7f0b3f1 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ Attribute | Description [`CodeGenPropertyAttribute`](./src/OnRamp/Config/CodeGenPropertyAttribute.cs) | Defines validation (`IsMandatory`, `IsUnique` and `Options`) and documentation for a property (non-collection). [`CodeGenPropertyCollectionAttribute`](./src/OnRamp/Config/CodeGenPropertyCollectionAttribute.cs) | Defines validation (`IsMandatory`) and documentation for a collection property. -The configuration must also use the [Newtonsoft Json.NET serializer attributes](https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm) as [Json.NET](https://www.newtonsoft.com/json/help) is used internally to perform all JSON deserialization. +The configuration must also use the `System.Text.Json` [serializer attributes](https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/customize-properties) as [`System.Text.Json`](https://learn.microsoft.com/en-us/dotnet/standard/serialization/) is used internally to perform all JSON deserialization.
@@ -85,17 +85,16 @@ The configuration must also use the [Newtonsoft Json.NET serializer attributes]( An example is as follows: ``` csharp -[JsonObject(MemberSerialization = MemberSerialization.OptIn)] [CodeGenClass("Entity", Title = "'Entity' object.", Description = "The `Entity` object.", Markdown = "This is a _sample_ markdown.", ExampleMarkdown = "This is an `example` markdown.")] [CodeGenCategory("Key", Title = "Provides the _Key_ configuration.")] [CodeGenCategory("Collection", Title = "Provides related child (hierarchical) configuration.")] public class EntityConfig : ConfigRootBase { - [JsonProperty("name")] + [JsonPropertyName("name")] [CodeGenProperty("Key", Title = "The entity name.", IsMandatory = true)] public string? Name { get; set; } - [JsonProperty("properties")] + [JsonPropertyName("properties")] [CodeGenPropertyCollection("Collection", Title = "The `Property` collection.", IsImportant = true)] public List? Properties { get; set; } @@ -105,22 +104,21 @@ public class EntityConfig : ConfigRootBase } } -[JsonObject(MemberSerialization = MemberSerialization.OptIn)] [CodeGenClass("Property", Title = "'Property' object.", Description = "The `Property` object.")] [CodeGenCategory("Key", Title = "Provides the _Key_ configuration.")] public class PropertyConfig : ConfigBase { public override string QualifiedKeyName => BuildQualifiedKeyName("Property", Name); - [JsonProperty("name")] + [JsonPropertyName("name")] [CodeGenProperty("Key", Title = "The property name.", IsMandatory = true, IsUnique = true)] public string? Name { get; set; } - [JsonProperty("type")] + [JsonPropertyName("type")] [CodeGenProperty("Key", Title = "The property type.", Description = "This is a more detailed description for the property type.", IsImportant = true, Options = new string[] { "string", "int", "decimal" })] public string? Type { get; set; } - [JsonProperty("isNullable")] + [JsonPropertyName("isNullable")] [CodeGenProperty("Key", Title = "Indicates whether the property is nullable.")] public bool? IsNullable { get; set; } diff --git a/src/OnRamp/CodeGenOutputArgs.cs b/src/OnRamp/CodeGenOutputArgs.cs index c4e8fc5..4e9d69b 100644 --- a/src/OnRamp/CodeGenOutputArgs.cs +++ b/src/OnRamp/CodeGenOutputArgs.cs @@ -8,48 +8,36 @@ namespace OnRamp /// /// The resulting arguments. /// - public class CodeGenOutputArgs + /// The corresponding . + /// The optional generated directory name. + /// The generated file name. + /// The generated gen-once file name. + /// The generated content. + public class CodeGenOutputArgs(CodeGenScriptItem script, string? directoryName, string fileName, string? genOncePattern, string? content) { - /// - /// Initializes a new instance of the class. - /// - /// The corresponding . - /// The optional generated directory name. - /// The generated file name. - /// The generated gen-once file name. - /// The generated content. - public CodeGenOutputArgs(CodeGenScriptItem script, string? directoryName, string fileName, string? genOncePattern, string? content) - { - Script = script ?? throw new ArgumentNullException(nameof(script)); - DirectoryName = directoryName; - FileName = string.IsNullOrEmpty(fileName) ? throw new ArgumentNullException(nameof(fileName)) : fileName; - GenOncePattern = genOncePattern; - Content = content; - } - /// /// Gets the . /// - public CodeGenScriptItem Script { get; } + public CodeGenScriptItem Script { get; } = script ?? throw new ArgumentNullException(nameof(script)); /// /// Gets the optional generated directory name. /// - public string? DirectoryName { get; } + public string? DirectoryName { get; } = directoryName; /// /// Gets the generated file name. /// - public string FileName { get; } + public string FileName { get; } = string.IsNullOrEmpty(fileName) ? throw new ArgumentNullException(nameof(fileName)) : fileName; /// /// Gets the generated content. /// - public string? Content { get; } + public string? Content { get; } = content; /// /// Gets the gen-once file name pattern (where specified). /// - public string? GenOncePattern { get; } + public string? GenOncePattern { get; } = genOncePattern; } } \ No newline at end of file diff --git a/src/OnRamp/CodeGenerator.cs b/src/OnRamp/CodeGenerator.cs index 5f7b9de..2f7fc61 100644 --- a/src/OnRamp/CodeGenerator.cs +++ b/src/OnRamp/CodeGenerator.cs @@ -42,7 +42,7 @@ public static async Task CreateAsync(ICodeGenera /// private static async Task LoadScriptsAsync(ICodeGeneratorArgs args) { - var r = StreamLocator.GetScriptStreamReader(args.ScriptFileName ?? throw new CodeGenException("Script file name must be specified."), args.Assemblies.ToArray(), StreamLocator.YamlJsonExtensions); + var r = StreamLocator.GetScriptStreamReader(args.ScriptFileName ?? throw new CodeGenException("Script file name must be specified."), [.. args.Assemblies], StreamLocator.YamlJsonExtensions); using var s = r.StreamReader ?? throw new CodeGenException($"Script '{args.ScriptFileName}' does not exist."); args.ScriptFileName = r.FileName; return await LoadScriptStreamAsync(args, null, args.ScriptFileName, s).ConfigureAwait(false); @@ -84,7 +84,7 @@ private static async Task LoadScriptStreamAsync(ICodeGeneratorArg { foreach (var ifn in scripts.Inherits) { - using var s = StreamLocator.GetScriptStreamReader(ifn, args.Assemblies.ToArray(), StreamLocator.YamlJsonExtensions).StreamReader ?? throw new CodeGenException($"Script '{ifn}' does not exist."); + using var s = StreamLocator.GetScriptStreamReader(ifn, [.. args.Assemblies], StreamLocator.YamlJsonExtensions).StreamReader ?? throw new CodeGenException($"Script '{ifn}' does not exist."); var inherit = await LoadScriptStreamAsync(args, rootScript, ifn, s).ConfigureAwait(false); foreach (var iscript in inherit.Generators!) { @@ -131,22 +131,20 @@ protected CodeGenerator(ICodeGeneratorArgs args, CodeGenScript scripts) public ICodeGeneratorArgs CodeGenArgs { get; } /// - /// Execute the code-generation; loads the configuration file and executes each of the scripted templates. + /// Loads the from the specified . /// - /// The filename (defaults to ) to load the content from the file system (primary) or (secondary, recursive until found). - /// The resultant . - /// Thrown when an error is encountered during the code-generation. - /// Thrown where the code-generation would result in changes to an underlying artefact. This is managed by setting to true. - public async Task GenerateAsync(string? configFileName = null) + /// The configuration file name. + /// The . + public async Task LoadConfigAsync(string? configFileName = null) { var fn = configFileName ?? CodeGenArgs.ConfigFileName ?? throw new CodeGenException("Config file must be specified."); - var r = StreamLocator.GetStreamReader(fn, null, CodeGenArgs.Assemblies.ToArray()); + var r = StreamLocator.GetStreamReader(fn, null, [.. CodeGenArgs.Assemblies]); using var sr = r.StreamReader ?? throw new CodeGenException($"Config '{fn}' does not exist."); - return await GenerateAsync(fn, sr, StreamLocator.GetContentType(r.FileName)).ConfigureAwait(false); + return await LoadConfigAsync(sr, StreamLocator.GetContentType(r.FileName), r.FileName).ConfigureAwait(false); } /// - /// Execute the code-generation; loads the configuration from the and executes each of the scripted templates. + /// Loads the from the specified . /// /// The containing the configuration. /// The corresponding . @@ -154,12 +152,7 @@ public async Task GenerateAsync(string? configFileName = null /// The resultant . /// Thrown when an error is encountered during the code-generation. /// Thrown where the code-generation would result in changes to an underlying artefact. This is managed by setting to true. - public async Task GenerateAsync(TextReader configReader, StreamContentType contentType, string configFileName = "") => await GenerateAsync(configFileName, configReader, contentType).ConfigureAwait(false); - - /// - /// Executes the code-generation. - /// - private async Task GenerateAsync(string configFileName, TextReader configReader, StreamContentType contentType) + public async Task LoadConfigAsync(TextReader configReader, StreamContentType contentType, string configFileName = "") { ConfigBase? config; IRootConfig rootConfig; @@ -199,11 +192,45 @@ private async Task GenerateAsync(string configFileName, TextR { await ce.AfterPrepareAsync(rootConfig).ConfigureAwait(false); } + + return config; } catch (CodeGenException cgex) { throw new CodeGenException($"Config '{configFileName}' is invalid: {cgex.Message}"); } + } + + /// + /// Execute the code-generation; loads the configuration file and executes each of the scripted templates. + /// + /// The filename (defaults to ) to load the content from the file system (primary) or (secondary, recursive until found). + /// The resultant . + /// Thrown when an error is encountered during the code-generation. + /// Thrown where the code-generation would result in changes to an underlying artefact. This is managed by setting to true. + public async Task GenerateAsync(string? configFileName = null) + => await GenerateAsync(await LoadConfigAsync(configFileName).ConfigureAwait(false)).ConfigureAwait(false); + + /// + /// Execute the code-generation; loads the configuration from the and executes each of the scripted templates. + /// + /// The containing the configuration. + /// The corresponding . + /// The optional configuration file name used specifically in error messages. + /// The resultant . + /// Thrown when an error is encountered during the code-generation. + /// Thrown where the code-generation would result in changes to an underlying artefact. This is managed by setting to true. + public async Task GenerateAsync(TextReader configReader, StreamContentType contentType, string configFileName = "") + => await GenerateAsync(await LoadConfigAsync(configReader, contentType, configFileName).ConfigureAwait(false)).ConfigureAwait(false); + + /// + /// Executes the code-generation for the specific . + /// + /// The . + public Task GenerateAsync(ConfigBase config) + { + if (config is not IRootConfig rootConfig) + throw new ArgumentException("Configuration must implement IRootConfig.", nameof(config)); // Generate the scripted artefacts. var overallStopwatch = Stopwatch.StartNew(); @@ -232,7 +259,7 @@ private async Task GenerateAsync(string configFileName, TextR overallStopwatch.Stop(); overallStats.ElapsedMilliseconds = overallStopwatch.ElapsedMilliseconds; - return overallStats; + return Task.FromResult(overallStats); } /// @@ -268,7 +295,7 @@ protected virtual void OnCodeGenerated(CodeGenOutputArgs outputArgs, CodeGenStat else { // Perform a wildcard search and stop code-gen where any matches. - if (di.GetFiles(outputArgs.GenOncePattern).Any()) + if (di.GetFiles(outputArgs.GenOncePattern).Length != 0) return; } } @@ -314,7 +341,7 @@ protected virtual void OnCodeGenerated(CodeGenOutputArgs outputArgs, CodeGenStat private static string[] ConvertContentIntoLines(string? content) { if (content is null) - return Array.Empty(); + return []; string line; var lines = new List(); @@ -324,7 +351,7 @@ private static string[] ConvertContentIntoLines(string? content) lines.Add(line); } - return lines.ToArray(); + return [.. lines]; } /// diff --git a/src/OnRamp/CodeGeneratorArgsBase.cs b/src/OnRamp/CodeGeneratorArgsBase.cs index 96ddf48..be4d7c2 100644 --- a/src/OnRamp/CodeGeneratorArgsBase.cs +++ b/src/OnRamp/CodeGeneratorArgsBase.cs @@ -23,10 +23,10 @@ public abstract class CodeGeneratorArgsBase : CodeGeneratorDbArgsBase, ICodeGene public DirectoryInfo? OutputDirectory { get; set; } /// - public List Assemblies { get; } = new List(); + public List Assemblies { get; } = []; /// - public Dictionary Parameters { get; } = new Dictionary(); + public Dictionary Parameters { get; } = []; /// public ILogger? Logger { get; set; } diff --git a/src/OnRamp/Config/CodeGenCategoryAttribute.cs b/src/OnRamp/Config/CodeGenCategoryAttribute.cs index ff0bcb1..89284ce 100644 --- a/src/OnRamp/Config/CodeGenCategoryAttribute.cs +++ b/src/OnRamp/Config/CodeGenCategoryAttribute.cs @@ -7,19 +7,14 @@ namespace OnRamp.Config /// /// Represents the code-generation class category configuration. /// + /// The grouping category name. [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] - public sealed class CodeGenCategoryAttribute : Attribute + public sealed class CodeGenCategoryAttribute(string category) : Attribute { - /// - /// Initializes a new instance of the class. - /// - /// The grouping category name. - public CodeGenCategoryAttribute(string category) => Category = category; - /// /// Gets or sets the category name. /// - public string Category { get; } + public string Category { get; } = category; /// /// Gets or sets the title. diff --git a/src/OnRamp/Config/CodeGenClassAttribute.cs b/src/OnRamp/Config/CodeGenClassAttribute.cs index 9c9dd4e..0a922aa 100644 --- a/src/OnRamp/Config/CodeGenClassAttribute.cs +++ b/src/OnRamp/Config/CodeGenClassAttribute.cs @@ -7,19 +7,14 @@ namespace OnRamp.Config /// /// Represents the code-generation class configuration. /// + /// The class name. [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] - public sealed class CodeGenClassAttribute : Attribute + public sealed class CodeGenClassAttribute(string name) : Attribute { - /// - /// Initializes a new instance of the class. - /// - /// The class name. - public CodeGenClassAttribute(string name) => Name = name ?? throw new ArgumentNullException(nameof(name)); - /// /// Gets the class name. /// - public string Name { get; } + public string Name { get; } = name ?? throw new ArgumentNullException(nameof(name)); /// /// Gets or sets the title. diff --git a/src/OnRamp/Config/CodeGenPropertyCollectionAttribute.cs b/src/OnRamp/Config/CodeGenPropertyCollectionAttribute.cs index 818521e..a8e5493 100644 --- a/src/OnRamp/Config/CodeGenPropertyCollectionAttribute.cs +++ b/src/OnRamp/Config/CodeGenPropertyCollectionAttribute.cs @@ -8,19 +8,14 @@ namespace OnRamp.Config /// Represents the code-generation property collection configuration. /// /// The property should be either a List<string> or List<T> where T inherits from . + /// The grouping category. [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] - public sealed class CodeGenPropertyCollectionAttribute : Attribute + public sealed class CodeGenPropertyCollectionAttribute(string category) : Attribute { - /// - /// Initializes a new instance of the class. - /// - /// The grouping category. - public CodeGenPropertyCollectionAttribute(string category) => Category = category; - /// /// Gets or sets the category. /// - public string Category { get; } + public string Category { get; } = category; /// /// Gets or sets the title. diff --git a/src/OnRamp/Config/ConfigBaseT.cs b/src/OnRamp/Config/ConfigBaseT.cs index eb70e7d..fbfcd9f 100644 --- a/src/OnRamp/Config/ConfigBaseT.cs +++ b/src/OnRamp/Config/ConfigBaseT.cs @@ -97,7 +97,7 @@ private void CheckConfiguration() protected async Task> PrepareCollectionAsync(List? coll) where T : ConfigBase { if (coll == null) - return new List(); + return []; var dict = new Dictionary>(); foreach (var pi in typeof(T).GetProperties()) @@ -105,7 +105,7 @@ protected async Task> PrepareCollectionAsync(List? coll) where T : foreach (var psa in pi.GetCustomAttributes(typeof(CodeGenPropertyAttribute), true).OfType()) { if (psa.IsUnique) - dict.Add(pi, new HashSet()); + dict.Add(pi, []); } } diff --git a/src/OnRamp/Config/ConfigRootBase.cs b/src/OnRamp/Config/ConfigRootBase.cs index 6e849bd..df33be6 100644 --- a/src/OnRamp/Config/ConfigRootBase.cs +++ b/src/OnRamp/Config/ConfigRootBase.cs @@ -20,7 +20,7 @@ public abstract class ConfigRootBase : ConfigBase, IRootCon /// /// Gets the parameter overrides. /// - public Dictionary RuntimeParameters { get; } = new Dictionary(); + public Dictionary RuntimeParameters { get; } = []; /// /// Sets the . diff --git a/src/OnRamp/Console/AssemblyValidator.cs b/src/OnRamp/Console/AssemblyValidator.cs index e40a204..bcf345f 100644 --- a/src/OnRamp/Console/AssemblyValidator.cs +++ b/src/OnRamp/Console/AssemblyValidator.cs @@ -14,15 +14,10 @@ namespace OnRamp.Console /// /// Validates the assembly name(s). /// - public class AssemblyValidator : IOptionValidator + /// The to update. + public class AssemblyValidator(ICodeGeneratorArgs args) : IOptionValidator { - private readonly ICodeGeneratorArgs _args; - - /// - /// Initilizes a new instance of the class. - /// - /// The to update. - public AssemblyValidator(ICodeGeneratorArgs args) => _args = args ?? throw new ArgumentNullException(nameof(args)); + private readonly ICodeGeneratorArgs _args = args ?? throw new ArgumentNullException(nameof(args)); /// /// Performs the validation. diff --git a/src/OnRamp/Console/CodeGenConsole.cs b/src/OnRamp/Console/CodeGenConsole.cs index 4c8ddbe..2c6ca7c 100644 --- a/src/OnRamp/Console/CodeGenConsole.cs +++ b/src/OnRamp/Console/CodeGenConsole.cs @@ -20,10 +20,12 @@ namespace OnRamp.Console /// , and . Changes to the console output can be achieved by overridding /// , , and . /// The underlying command line parsing is provided by . - public class CodeGenConsole + /// The default that will be overridden/updated by the command-line argument values. + /// The console command-line ; defaults to . + public class CodeGenConsole(CodeGeneratorArgs? args = null, SupportedOptions options = SupportedOptions.All) { - private readonly SupportedOptions _supportedOptions; - private readonly Dictionary _options = new(); + private readonly SupportedOptions _supportedOptions = options; + private readonly Dictionary _options = []; /// /// Split an into an of arguments. @@ -33,7 +35,7 @@ public class CodeGenConsole public static string[] SplitArgumentsIntoArray(string? args) { if (string.IsNullOrEmpty(args)) - return Array.Empty(); + return []; // See for inspiration: https://stackoverflow.com/questions/298830/split-string-containing-command-line-parameters-into-string-in-c-sharp/298990#298990 var regex = Regex.Matches(args, @"\G(""((""""|[^""])+)""|(\S+)) *"); @@ -63,21 +65,10 @@ public static string GetBaseExeDirectory() return exeDir; } - /// - /// Initializes a new instance of the class. - /// - /// The default that will be overridden/updated by the command-line argument values. - /// The console command-line ; defaults to . - public CodeGenConsole(CodeGeneratorArgs? args = null, SupportedOptions options = SupportedOptions.All) - { - Args = args ?? new CodeGeneratorArgs(); - _supportedOptions = options; - } - /// /// Gets the . /// - public CodeGeneratorArgs Args { get; } + public CodeGeneratorArgs Args { get; } = args ?? new CodeGeneratorArgs(); /// /// Gets the application/command name. diff --git a/src/OnRamp/Console/ConsoleLogger.cs b/src/OnRamp/Console/ConsoleLogger.cs index e98cfe4..8719d14 100644 --- a/src/OnRamp/Console/ConsoleLogger.cs +++ b/src/OnRamp/Console/ConsoleLogger.cs @@ -9,15 +9,10 @@ namespace OnRamp.Console /// /// Represents an that writes to an . /// - public class ConsoleLogger : ILogger + /// The ; where null will default to using . + public class ConsoleLogger(IConsole? console = null) : ILogger { - private readonly IConsole? _console; - - /// - /// Initializes a new instance of the . - /// - /// The ; where null will default to using . - public ConsoleLogger(IConsole? console = null) => _console = console; + private readonly IConsole? _console = console; /// public IDisposable BeginScope(TState state) where TState : notnull => NullScope.Default; diff --git a/src/OnRamp/Console/ParametersValidator.cs b/src/OnRamp/Console/ParametersValidator.cs index 1cc02ee..45fdff2 100644 --- a/src/OnRamp/Console/ParametersValidator.cs +++ b/src/OnRamp/Console/ParametersValidator.cs @@ -12,15 +12,10 @@ namespace OnRamp.Console /// /// Validate the Params to ensure format is correct and values are not duplicated. /// - public class ParametersValidator : IOptionValidator + /// The to update. + public class ParametersValidator(ICodeGeneratorArgs args) : IOptionValidator { - private readonly ICodeGeneratorArgs _args; - - /// - /// Initilizes a new instance of the class. - /// - /// The to update. - public ParametersValidator(ICodeGeneratorArgs args) => _args = args ?? throw new ArgumentNullException(nameof(args)); + private readonly ICodeGeneratorArgs _args = args ?? throw new ArgumentNullException(nameof(args)); /// /// Performs the validation. diff --git a/src/OnRamp/Generators/CodeGeneratorBaseT2.cs b/src/OnRamp/Generators/CodeGeneratorBaseT2.cs index c0a9f20..de954ac 100644 --- a/src/OnRamp/Generators/CodeGeneratorBaseT2.cs +++ b/src/OnRamp/Generators/CodeGeneratorBaseT2.cs @@ -57,7 +57,7 @@ public void Generate(CodeGenScriptItem script, TRootConfig config, ActionExe netstandard2.1 OnRamp - 2.0.0 + 2.1.0 true Avanade Avanade @@ -49,12 +49,12 @@ - + - - + + \ No newline at end of file diff --git a/src/OnRamp/Scripts/CodeGenScript.cs b/src/OnRamp/Scripts/CodeGenScript.cs index 204940f..43c2e42 100644 --- a/src/OnRamp/Scripts/CodeGenScript.cs +++ b/src/OnRamp/Scripts/CodeGenScript.cs @@ -18,7 +18,7 @@ namespace OnRamp.Scripts public class CodeGenScript : ConfigRootBase { private Type? _configType; - private readonly List _editorTypes = new(); + private readonly List _editorTypes = []; /// /// Gets or sets the .NET Type for the underlying . @@ -96,7 +96,7 @@ protected override async Task PrepareAsync() catch (CodeGenException) { throw; } catch (Exception ex) { throw new CodeGenException(this, nameof(EditorType), $"Type '{EditorType}' is invalid: {ex.Message}"); } - if (!typeof(IConfigEditor).IsAssignableFrom(configEditorType) || configEditorType.GetConstructor(Array.Empty()) == null) + if (!typeof(IConfigEditor).IsAssignableFrom(configEditorType) || configEditorType.GetConstructor([]) == null) throw new CodeGenException(this, nameof(EditorType), $"Type '{EditorType}' does not implement IConfigEditor and/or have a default parameterless constructor."); MergeEditors(configEditorType); diff --git a/src/OnRamp/Scripts/CodeGenScriptItem.cs b/src/OnRamp/Scripts/CodeGenScriptItem.cs index f49324d..fea975e 100644 --- a/src/OnRamp/Scripts/CodeGenScriptItem.cs +++ b/src/OnRamp/Scripts/CodeGenScriptItem.cs @@ -80,7 +80,7 @@ public class CodeGenScriptItem : ConfigBase /// /// Gets the runtime parameters (as specified via ). /// - public Dictionary RuntimeParameters { get; } = new Dictionary(); + public Dictionary RuntimeParameters { get; } = []; /// /// Gets the as specified by . @@ -99,7 +99,7 @@ protected override Task PrepareAsync() { type = System.Type.GetType(Type ?? throw new CodeGenException(this, nameof(Type), $"Type must be specified.")) ?? throw new CodeGenException(this, nameof(Type), $"Type '{Type}' does not exist."); - if (!IsSubclassOfBaseType(typeof(CodeGeneratorBase), type) || type.GetConstructor(Array.Empty()) == null) + if (!IsSubclassOfBaseType(typeof(CodeGeneratorBase), type) || type.GetConstructor([]) == null) throw new CodeGenException(this, nameof(Type), $"Type '{Type}' does not implement CodeGeneratorBase and/or have a default parameterless constructor."); _generator = (CodeGeneratorBase)(Activator.CreateInstance(type) ?? throw new CodeGenException(this, nameof(Type), $"Type '{Type}' was unable to be instantiated.")); @@ -110,7 +110,7 @@ protected override Task PrepareAsync() catch (Exception ex) { throw new CodeGenException(this, nameof(Type), $"Type '{Type}' is invalid: {ex.Message}"); } // Make sure the template exists. - var (Exists, FileName) = StreamLocator.HasTemplateStream(Template!, Root!.CodeGenArgs!.Assemblies.ToArray(), StreamLocator.HandlebarsExtensions); + var (Exists, FileName) = StreamLocator.HasTemplateStream(Template!, [.. Root!.CodeGenArgs!.Assemblies], StreamLocator.HandlebarsExtensions); if (!Exists) throw new CodeGenException(this, nameof(Template), $"Template '{Template}' does not exist."); diff --git a/src/OnRamp/Utility/HandlebarsHelpers.cs b/src/OnRamp/Utility/HandlebarsHelpers.cs index 3e2c7ab..f89d672 100644 --- a/src/OnRamp/Utility/HandlebarsHelpers.cs +++ b/src/OnRamp/Utility/HandlebarsHelpers.cs @@ -135,9 +135,9 @@ public static void RegisterHelpers() Handlebars.RegisterHelper("singularize", (writer, context, args) => writer.WriteSafeString(StringConverter.ToSingle(ValidateArgs("singularize", args).FirstOrDefault()?.ToString()) ?? "")); // Logs using the String.Format. - Handlebars.RegisterHelper("log-info", (writer, context, args) => (Logger ?? new ConsoleLogger()).LogInformation(FormatString(ValidateArgs("log-info", args)))); - Handlebars.RegisterHelper("log-warning", (writer, context, args) => (Logger ?? new ConsoleLogger()).LogWarning(FormatString(ValidateArgs("log-warning", args)))); - Handlebars.RegisterHelper("log-error", (writer, context, args) => (Logger ?? new ConsoleLogger()).LogError(FormatString(ValidateArgs("log-error", args)))); + Handlebars.RegisterHelper("log-info", (writer, context, args) => (Logger ?? new ConsoleLogger()).LogInformation("{Info}", FormatString(ValidateArgs("log-info", args)))); + Handlebars.RegisterHelper("log-warning", (writer, context, args) => (Logger ?? new ConsoleLogger()).LogWarning("{Warning}", FormatString(ValidateArgs("log-warning", args)))); + Handlebars.RegisterHelper("log-error", (writer, context, args) => (Logger ?? new ConsoleLogger()).LogError("{Error}", FormatString(ValidateArgs("log-error", args)))); Handlebars.RegisterHelper("log-debug", (writer, context, args) => System.Diagnostics.Debug.WriteLine($"Handlebars > {FormatString(ValidateArgs("log-debug", args))}")); // Logs using the String.Format to the debugger and then initiates a break in the debugger itself. @@ -210,9 +210,8 @@ public static void RegisterHelpers() if (args[0] is not string name) throw new CodeGenException("Handlebars template invokes function 'set-value' where the first argument must be a string, being the property name."); - var pi = context.Value.GetType().GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.SetProperty); - if (pi == null) - throw new CodeGenException($"Handlebars template invokes function 'set-value' where the property '{name}' does not exist for Type {context.Value.GetType().Name}."); + var pi = context.Value.GetType().GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.SetProperty) + ?? throw new CodeGenException($"Handlebars template invokes function 'set-value' where the property '{name}' does not exist for Type {context.Value.GetType().Name}."); try { @@ -231,9 +230,8 @@ public static void RegisterHelpers() if (args[0] is not string name) throw new CodeGenException("Handlebars template invokes function 'add-value' where the first argument must be a string, being the property name."); - var pi = context.Value.GetType().GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.SetProperty); - if (pi == null) - throw new CodeGenException($"Handlebars template invokes function 'add-value' where the property '{name}' does not exist for Type {context.Value.GetType().Name}."); + var pi = context.Value.GetType().GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.SetProperty) + ?? throw new CodeGenException($"Handlebars template invokes function 'add-value' where the property '{name}' does not exist for Type {context.Value.GetType().Name}."); decimal sum = 0; try diff --git a/src/OnRamp/Utility/StreamExtensions.cs b/src/OnRamp/Utility/StreamExtensions.cs index 0df0530..ad8d59a 100644 --- a/src/OnRamp/Utility/StreamExtensions.cs +++ b/src/OnRamp/Utility/StreamExtensions.cs @@ -65,7 +65,7 @@ public static class TextReaderExtensions private class YamlNodeTypeResolver : INodeTypeResolver { - private static readonly string[] boolValues = { "true", "false" }; + private static readonly string[] boolValues = ["true", "false"]; /// bool INodeTypeResolver.Resolve(NodeEvent? nodeEvent, ref Type currentType) diff --git a/src/OnRamp/Utility/StreamLocator.cs b/src/OnRamp/Utility/StreamLocator.cs index 7d605e3..c55c048 100644 --- a/src/OnRamp/Utility/StreamLocator.cs +++ b/src/OnRamp/Utility/StreamLocator.cs @@ -16,12 +16,12 @@ public static class StreamLocator /// /// Gets the list of standard YAML and JSON extensions. /// - public static readonly string[] YamlJsonExtensions = new string[] { "yaml", "yml", "json", "jsn" }; + public static readonly string[] YamlJsonExtensions = ["yaml", "yml", "json", "jsn"]; /// /// Gets the list of standard Handlebars extensions. /// - public static readonly string[] HandlebarsExtensions = new string[] { "hb", "hbs" }; + public static readonly string[] HandlebarsExtensions = ["hb", "hbs"]; /// /// Gets the Resource content from the file system and then Resources folder within the until found. diff --git a/src/OnRamp/Utility/StringConverter.cs b/src/OnRamp/Utility/StringConverter.cs index cc503bd..12d45eb 100644 --- a/src/OnRamp/Utility/StringConverter.cs +++ b/src/OnRamp/Utility/StringConverter.cs @@ -125,7 +125,7 @@ public static class StringConverter /// Gets or sets the special prefixes whereby the first two characters will be converted to lowercase versus the standard one. /// /// Defaults to "ETag" and "OData". - public static string[] TwoCharacterPrefixes { get; set; } = new string[] { "ETag", "OData" }; + public static string[] TwoCharacterPrefixes { get; set; } = ["ETag", "OData"]; /// /// Performs the special case handling. diff --git a/tests/OnRamp.Test/OnRamp.Test.csproj b/tests/OnRamp.Test/OnRamp.Test.csproj index e739138..b24b05f 100644 --- a/tests/OnRamp.Test/OnRamp.Test.csproj +++ b/tests/OnRamp.Test/OnRamp.Test.csproj @@ -64,14 +64,14 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + - + all runtime; build; native; contentfiles; analyzers; buildtransitive