Skip to content

Commit

Permalink
CodeGenerator fixed. (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
chullybun authored Mar 20, 2023
1 parent abb05e1 commit ed7b42f
Show file tree
Hide file tree
Showing 8 changed files with 63 additions and 32 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

Represents the **NuGet** versions.

## v1.0.7
- *Fixed:* `CodeGenerator` now supports inheritance as intended; new `CreateAsync<TCodeGenerator>` added to enable.
- *Fixed:* The `CodeGeneratorArgsBase.ConfigFileName` per script `IRootConfig` instance included within `CodeGenStatistics` per script item execution to enable access from `CodeGenerator`.

## v1.0.6
- *Enhancement:* Added new `set-value` function to allow a variable to be updated from the template when executed.
- *Enhancement:* Added new `add-value` function to allow a variable to be added to from the template when executed.
Expand Down
7 changes: 7 additions & 0 deletions src/OnRamp/CodeGenStatistics.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// Copyright (c) Avanade. Licensed under the MIT License. See https://github.com/Avanade/OnRamp

using OnRamp.Config;

namespace OnRamp
{
/// <summary>
Expand Down Expand Up @@ -33,6 +35,11 @@ public class CodeGenStatistics
/// <summary>A <c>null</c> indicates that the value has not been set.</summary>
public long? ElapsedMilliseconds { get; set; }

/// <summary>
/// Gets or sets the <see cref="CodeGeneratorArgsBase.ConfigFileName"/> <see cref="IRootConfig"/> instance.
/// </summary>
public IRootConfig? RootConfig { get; set; }

/// <summary>
/// Adds other <paramref name="stats"/> to this instance.
/// </summary>
Expand Down
17 changes: 15 additions & 2 deletions src/OnRamp/CodeGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,16 @@ public class CodeGenerator
public static async Task<CodeGenerator> CreateAsync(ICodeGeneratorArgs args)
=> new CodeGenerator(args, await LoadScriptsAsync(args).ConfigureAwait(false));

/// <summary>
/// Create a new instance of the <typeparamref name="TCodeGenerator"/> class.
/// </summary>
/// <typeparam name="TCodeGenerator">The <see cref="CodeGenerator"/> <see cref="Type"/>.</typeparam>
/// <param name="args">The <see cref="ICodeGeneratorArgs"/>.</param>
/// <returns>The <typeparamref name="TCodeGenerator"/> instance.</returns>
/// <remarks>The constructor must be the same as the <see cref="CodeGenerator"/>.</remarks>
public static async Task<TCodeGenerator> CreateAsync<TCodeGenerator>(ICodeGeneratorArgs args) where TCodeGenerator : CodeGenerator
=> (TCodeGenerator)Activator.CreateInstance(typeof(TCodeGenerator), new object[] { args, await LoadScriptsAsync(args).ConfigureAwait(false) });

/// <summary>
/// Load the Scripts.
/// </summary>
Expand Down Expand Up @@ -99,7 +109,10 @@ private static async Task<CodeGenScript> LoadScriptStreamAsync(ICodeGeneratorArg
/// <summary>
/// Initializes a new instance of the <see cref="CodeGenerator"/> class.
/// </summary>
private CodeGenerator(ICodeGeneratorArgs args, CodeGenScript scripts)
/// <param name="args">The <see cref="ICodeGeneratorArgs"/>.</param>
/// <param name="scripts">The <see cref="CodeGenScript"/>.</param>
/// <remarks>The class should only be instantiated by <see cref="CreateAsync(ICodeGeneratorArgs)"/> or <see cref="CreateAsync{TCodeGenerator}(ICodeGeneratorArgs)"/> to ensure conrrectly set up for execution.</remarks>
protected CodeGenerator(ICodeGeneratorArgs args, CodeGenScript scripts)
{
CodeGenArgs = args ?? throw new ArgumentNullException(nameof(args));
CodeGenArgs.OutputDirectory ??= new DirectoryInfo(Environment.CurrentDirectory);
Expand Down Expand Up @@ -205,7 +218,7 @@ private async Task<CodeGenStatistics> GenerateAsync(string configFileName, TextR
rootConfig.MergeRuntimeParameters(script.RuntimeParameters);
rootConfig.MergeRuntimeParameters(Scripts.RuntimeParameters);

var scriptStats = new CodeGenStatistics();
var scriptStats = new CodeGenStatistics { RootConfig = rootConfig };
OnBeforeScript(script, scriptStats);
script.GetGenerator().Generate(script, config, (oa) => OnCodeGenerated(oa, scriptStats));

Expand Down
50 changes: 25 additions & 25 deletions src/OnRamp/Console/CodeGenConsole.cs
Original file line number Diff line number Diff line change
Expand Up @@ -185,14 +185,14 @@ public async Task<int> RunAsync(string[] args)
}
catch (CommandParsingException cpex)
{
Args.Logger?.LogError(cpex.Message);
Args.Logger?.LogError(string.Empty);
Args.Logger?.LogError("{Content}", cpex.Message);
Args.Logger?.LogError("{Content}", string.Empty);
return 1;
}
catch (CodeGenException cgex)
{
Args.Logger?.LogError(cgex.Message);
Args.Logger?.LogError(string.Empty);
Args.Logger?.LogError("{Content}", cgex.Message);
Args.Logger?.LogError("{Content}", string.Empty);
return 2;
}
}
Expand Down Expand Up @@ -282,16 +282,16 @@ private async Task<int> RunRunawayAsync() /* Method name inspired by: Slade - Ru
{
if (cgex.Message != null)
{
Args.Logger?.LogError(cgex.Message);
Args.Logger?.LogError(string.Empty);
Args.Logger?.LogError("{Content}", cgex.Message);
Args.Logger?.LogError("{Content}", string.Empty);
}

return 2;
}
catch (CodeGenChangesFoundException cgcfex)
{
Args.Logger?.LogError(cgcfex.Message);
Args.Logger?.LogError(string.Empty);
Args.Logger?.LogError("{Content}", cgcfex.Message);
Args.Logger?.LogError("{Content}", string.Empty);
return 3;
}
}
Expand All @@ -302,7 +302,7 @@ private async Task<int> RunRunawayAsync() /* Method name inspired by: Slade - Ru
protected virtual void OnWriteMasthead()
{
if (MastheadText != null)
Logger?.LogInformation(MastheadText);
Logger?.LogInformation("{Content}", MastheadText);
}

/// <summary>
Expand All @@ -322,8 +322,8 @@ protected virtual async Task<CodeGenStatistics> OnCodeGenerationAsync()
/// <remarks>Writes the <see cref="AppTitle"/>.</remarks>
protected virtual void OnWriteHeader()
{
Logger?.LogInformation(AppTitle);
Logger?.LogInformation(string.Empty);
Logger?.LogInformation("{Content}", AppTitle);
Logger?.LogInformation("{Content}", string.Empty);
}

/// <summary>
Expand All @@ -341,26 +341,26 @@ public static void WriteStandardizedArgs(ICodeGeneratorArgs args)
if (args == null || args.Logger == null)
return;

args.Logger.LogInformation($"Config = {args.ConfigFileName}");
args.Logger.LogInformation($"Script = {args.ScriptFileName}");
args.Logger.LogInformation($"OutDir = {args.OutputDirectory?.FullName}");
args.Logger.LogInformation($"ExpectNoChanges = {args.ExpectNoChanges}");
args.Logger.LogInformation($"IsSimulation = {args.IsSimulation}");
args.Logger.LogInformation("{Content}", $"Config = {args.ConfigFileName}");
args.Logger.LogInformation("{Content}", $"Script = {args.ScriptFileName}");
args.Logger.LogInformation("{Content}", $"OutDir = {args.OutputDirectory?.FullName}");
args.Logger.LogInformation("{Content}", $"ExpectNoChanges = {args.ExpectNoChanges}");
args.Logger.LogInformation("{Content}", $"IsSimulation = {args.IsSimulation}");

args.Logger.LogInformation($"Parameters{(args.Parameters.Count == 0 ? " = none" : ":")}");
args.Logger.LogInformation("{Content}", $"Parameters{(args.Parameters.Count == 0 ? " = none" : ":")}");
foreach (var p in args.Parameters)
{
args.Logger.LogInformation($" {p.Key} = {p.Value}");
args.Logger.LogInformation("{Content}", $" {p.Key} = {p.Value}");
}

args.Logger.LogInformation($"Assemblies{(args.Assemblies.Count == 0 ? " = none" : ":")}");
args.Logger.LogInformation("{Content}", $"Assemblies{(args.Assemblies.Count == 0 ? " = none" : ":")}");
foreach (var a in args.Assemblies)
{
args.Logger.LogInformation($" {a.FullName}");
args.Logger.LogInformation("{Content}", $" {a.FullName}");
}

args.Logger.LogInformation(string.Empty);
args.Logger.LogInformation("Scripts:");
args.Logger.LogInformation("{Content}", string.Empty);
args.Logger.LogInformation("{Content}", "Scripts:");
}

/// <summary>
Expand All @@ -369,9 +369,9 @@ public static void WriteStandardizedArgs(ICodeGeneratorArgs args)
/// <param name="stats">The <see cref="CodeGenStatistics"/> information.</param>
protected virtual void OnWriteFooter(CodeGenStatistics stats)
{
Logger?.LogInformation(string.Empty);
Logger?.LogInformation($"{AppName} Complete. {stats.ToSummaryString()}");
Logger?.LogInformation(string.Empty);
Logger?.LogInformation("{Content}", string.Empty);
Logger?.LogInformation("{Content}", $"{AppName} Complete. {stats.ToSummaryString()}");
Logger?.LogInformation("{Content}", string.Empty);
}
}
}
2 changes: 1 addition & 1 deletion src/OnRamp/OnRamp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<OutputType>Exe</OutputType>
<TargetFramework>netstandard2.1</TargetFramework>
<RootNamespace>OnRamp</RootNamespace>
<Version>1.0.6</Version>
<Version>1.0.7</Version>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Authors>Avanade</Authors>
<Company>Avanade</Company>
Expand Down
6 changes: 3 additions & 3 deletions src/OnRamp/Scripts/CodeGenScriptItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,11 +111,11 @@ 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 r = StreamLocator.HasTemplateStream(Template!, Root!.CodeGenArgs!.Assemblies.ToArray(), StreamLocator.HandlebarsExtensions);
if (!r.Exists)
var (Exists, FileName) = StreamLocator.HasTemplateStream(Template!, Root!.CodeGenArgs!.Assemblies.ToArray(), StreamLocator.HandlebarsExtensions);
if (!Exists)
throw new CodeGenException(this, nameof(Template), $"Template '{Template}' does not exist.");

Template = r.FileName;
Template = FileName;

// Add special runtime parameters.
RuntimeParameters.Add(nameof(IsGenOnce), IsGenOnce);
Expand Down
2 changes: 1 addition & 1 deletion tests/OnRamp.Test/CodeGeneratorTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public class CodeGeneratorTest
[Test]
public void A100_Script_DoesNotExist()
{
var ex = Assert.ThrowsAsync<CodeGenException>(() => CodeGenerator.CreateAsync(new CodeGeneratorArgs("DoesNotExist.yaml").AddAssembly(typeof(CodeGeneratorTest).Assembly)));
var ex = Assert.ThrowsAsync<CodeGenException>(() => CodeGenerator.CreateAsync<CodeGenerator>(new CodeGeneratorArgs("DoesNotExist.yaml").AddAssembly(typeof(CodeGeneratorTest).Assembly)));
Assert.AreEqual("Script 'DoesNotExist.yaml' does not exist.", ex.Message);
}

Expand Down
7 changes: 7 additions & 0 deletions tests/OnRamp.Test/HandlebarsHelpersTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,13 @@ public void Add()
Assert.AreEqual("12", g.Generate(new { Count = -2 }));
}

[Test]
public void Add_Index()
{
var g = new HandlebarsCodeGenerator("{{#each .}}{{.}}{{add @index 1}}{{/each}}");
Assert.AreEqual("a1b2", g.Generate(new System.Collections.Generic.List<string> { "a", "b" }));
}

public class SetData { public int Count { get; set; } internal bool Check { get; set; } public decimal Sum { get; set; } }

[Test]
Expand Down

0 comments on commit ed7b42f

Please sign in to comment.