Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve maintenance cost and readability of generators #260

Merged
merged 7 commits into from
Jul 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions .nox/design/sample.solution.nox.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ name: SampleWebApp
description: Sample Nox solution yaml configuration

variables:
DATABASE_PROVIDER: slqServer
DATABASE_SERVER: ${{ secrets.database_server }}
DATABASE_USER: sa
DATABASE_PASSWORD: ${{ secrets.database_password }}
DATABASE_PORT: "5432"
DATABASE_PROVIDER: slqServer
DATABASE_SERVER: ${{ secrets.database_server }}
DATABASE_USER: sa
DATABASE_PASSWORD: ${{ secrets.database_password }}
DATABASE_PORT: "5432"

environments:

Expand Down
95 changes: 95 additions & 0 deletions src/Nox.Generator/Common/TemplateCodeBuilder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Scriban;

namespace Nox.Generator.Common;


internal class TemplateCodeBuilder

{
private static readonly Assembly Assembly = Assembly.GetExecutingAssembly();

private readonly SourceProductionContext _context;

private readonly NoxSolutionCodeGeneratorState _codeGeneratorState;

private string? _className;
private Dictionary<string, object>? _extendedModel;


public TemplateCodeBuilder(SourceProductionContext context, NoxSolutionCodeGeneratorState codeGeneratorState)
{
_context = context;
_codeGeneratorState = codeGeneratorState;
}

/// <summary>
/// Option class and file name to be generated, for "Entity" will generate a file name Entity.g.cs
/// Uses template name if undefined
/// </summary>
/// <param name="className">the name of the class to be generated</param>
/// <returns></returns>
public TemplateCodeBuilder WithClassName(string className)
{
_className = className;
return this;
}
/// <summary>
/// Extend the default model with a extended property to the extendedModel
/// </summary>
public TemplateCodeBuilder WithExtendedModel(Dictionary<string, object> extendedModel)
{
_extendedModel = extendedModel;
return this;
}

/// <summary>
/// Generates the class based on a file template
/// </summary>
/// <param name="templateFileName">the file relative namespace without template.cs. <example>Infrastructure.Persistence.DbContextGenerator.DbContext</example></param>
/// <returns></returns>
public TemplateCodeBuilder GenerateSourceCodeFromResource(string templateFileName)
{
var resourceName = $"Nox.Generator.{templateFileName}.template.cs";

var className = _className ?? ComputeDefaultClassName(templateFileName);
var model = new {
codeGeneratorState = _codeGeneratorState,
className = _className ?? className,
solution = _codeGeneratorState.Solution,
extended = _extendedModel
};
string template;

using (var stream = Assembly.GetManifestResourceStream(resourceName)!)
using (var reader = new StreamReader(stream))
{
template = reader.ReadToEnd();
}

GenerateSourceCode(template, model, $"{className}.g.cs");

return this;
}

private string ComputeDefaultClassName(string templateFileName)
{
return templateFileName.Split('.').Last();
}

private void GenerateSourceCode(string template, object model, string sourceFileName)
{
var strongTemplate = Template.Parse(template);

_context.AddSource(sourceFileName!,
SourceText.From(strongTemplate.Render(model, member => member.Name),
Encoding.UTF8));
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Generated

#nullable enable

using System;

namespace {{codeGeneratorState.DomainNameSpace}};

public partial class AuditableEntityBase
{
/// <summary>
/// The date and time when this entity was first created (in Coordinated Universal Time).
/// </summary>
public DateTime CreatedAtUtc { get; set; }

/// <summary>
/// The user that created the entity.
/// </summary>
public string? CreatedBy { get; set; }

/// <summary>
/// The date and time when this entity was last updated (in Coordinated Universal Time).
/// </summary>
public DateTime? UpdatedAtUtc { get; set; }

/// <summary>
/// The user that last updated the entity.
/// </summary>
public string? UpdatedBy { get; set; }

/// <summary>
/// The date and time when this entity was deleted (in Coordinated Universal Time).
/// </summary>
public DateTime? DeletedAtUtc { get; set; }

/// <summary>
/// The user that deleted the entity.
/// </summary>
public string? DeletedBy { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,53 +9,8 @@ public static void Generate(SourceProductionContext context, NoxSolutionCodeGene
{
context.CancellationToken.ThrowIfCancellationRequested();

var code = new CodeBuilder($"AuditableEntityBase.g.cs",context);
var code = new TemplateCodeBuilder(context, codeGeneratorState);

code.AppendLine($"using System;");
code.AppendLine();
code.AppendLine($"namespace {codeGeneratorState.DomainNameSpace};");
code.AppendLine();
code.AppendLine($"public partial class AuditableEntityBase");

code.StartBlock();

code.AppendLine($"/// <summary>");
code.AppendLine($"/// The date and time when this entity was first created (in Coordinated Universal Time).");
code.AppendLine($"/// </summary>");
code.AppendLine($"public DateTime CreatedAtUtc {{ get; set; }}");

code.AppendLine();
code.AppendLine($"/// <summary>");
code.AppendLine($"/// The user that created the entity.");
code.AppendLine($"/// </summary>");
code.AppendLine($"public string? CreatedBy {{ get; set; }}");

code.AppendLine();
code.AppendLine($"/// <summary>");
code.AppendLine($"/// The date and time when this entity was last updated (in Coordinated Universal Time).");
code.AppendLine($"/// </summary>");
code.AppendLine($"public DateTime? UpdatedAtUtc {{ get; set; }}");

code.AppendLine();
code.AppendLine($"/// <summary>");
code.AppendLine($"/// The user that last updated the entity.");
code.AppendLine($"/// </summary>");
code.AppendLine($"public string? UpdatedBy {{ get; set; }}");

code.AppendLine();
code.AppendLine($"/// <summary>");
code.AppendLine($"/// The date and time when this entity was deleted (in Coordinated Universal Time).");
code.AppendLine($"/// </summary>");
code.AppendLine($"public DateTime? DeletedAtUtc {{ get; set; }}");

code.AppendLine();
code.AppendLine($"/// <summary>");
code.AppendLine($"/// The user that deleted the entity.");
code.AppendLine($"/// </summary>");
code.AppendLine($"public string? DeletedBy {{ get; set; }}");

code.EndBlock();

code.GenerateSourceCode();
code.GenerateSourceCodeFromResource(@"Domain.ModelGenerator.AuditableEntityBase");
}
}
18 changes: 18 additions & 0 deletions src/Nox.Generator/Domain/ModelGenerator/EntityBase.template.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Generated

#nullable enable

using System;

namespace {{codeGeneratorState.DomainNameSpace}};

/// <summary>
/// The base class for all domain entities.
/// </summary>
public partial class EntityBase
{
/// <summary>
/// The state of the entity as at this date.
/// </summary>
public DateTime AsAt { get; set; }
}
22 changes: 2 additions & 20 deletions src/Nox.Generator/Domain/ModelGenerator/EntityBaseGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,8 @@ public static void Generate(SourceProductionContext context, NoxSolutionCodeGene
{
context.CancellationToken.ThrowIfCancellationRequested();

var code = new CodeBuilder($"EntityBase.g.cs", context);
var code = new TemplateCodeBuilder(context, codeGeneratorState);

code.AppendLine($"using System;");
code.AppendLine();
code.AppendLine($"namespace {codeGeneratorState.DomainNameSpace};");
code.AppendLine();
code.AppendLine($"/// <summary>");
code.AppendLine($"/// The base class for all domain entities.");
code.AppendLine($"/// </summary>");
code.AppendLine($"public partial class EntityBase");

code.StartBlock();

code.AppendLine($"/// <summary>");
code.AppendLine($"/// The state of the entity as at this date.");
code.AppendLine($"/// </summary>");
code.AppendLine($"public DateTime AsAt {{ get; set; }}");

code.EndBlock();

code.GenerateSourceCode();
code.GenerateSourceCodeFromResource(@"Domain.ModelGenerator.EntityBase");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Generated

#nullable enable

using Microsoft.EntityFrameworkCore;
using Nox.Solution;
using Nox.Generator.Common;
using Nox.Types.EntityFramework.Abstractions;
using {{codeGeneratorState.DomainNameSpace}};

namespace {{codeGeneratorState.PersistenceNameSpace}};

public partial class {{className}} : DbContext
{
private readonly NoxSolution _noxSolution;
private readonly INoxDatabaseProvider _dbProvider;

public {{className}}(
DbContextOptions<{{className}}> options,
NoxSolution noxSolution,
INoxDatabaseProvider databaseProvider
) : base(options)
{
_noxSolution = noxSolution;
_dbProvider = databaseProvider;
}

{{ for entity in solution.Domain.Entities }}
public DbSet<{{entity.Name}}> {{entity.PluralName}} { get; set; } = null!;
{{ end }}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
if (_noxSolution.Infrastructure is { Persistence.DatabaseServer: not null })
{
_dbProvider.ConfigureDbContext(optionsBuilder, "{{solution.Name}}", _noxSolution.Infrastructure!.Persistence.DatabaseServer);
}
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
if (_noxSolution.Domain != null)
{
var codeGeneratorState = new NoxSolutionCodeGeneratorState(_noxSolution);

foreach (var entity in _noxSolution.Domain.Entities)
{
var type = Type.GetType("{{codeGeneratorState.DomainNameSpace}}." + entity.Name);

if (type != null)
{
((INoxDatabaseConfigurator)_dbProvider).ConfigureEntity(codeGeneratorState, modelBuilder.Entity(type), entity);
}
}
}
}
}
Loading