Skip to content

Commit

Permalink
[BREAKING CHANGE] IFileSystem has a new GetLastWriteTimeUtc property.…
Browse files Browse the repository at this point in the history
… This is done to remove the extra IGeneratorFileSystem interface and the same property from ITemporaryFileSystem. If you have custom implementation for IFileSystem, you should also implement GetLastWriteTimeUtc method. Usings MSBuild's new command line build property extraction feature in Sergen for .NET8+
  • Loading branch information
volkanceylan committed Nov 23, 2023
1 parent ed92ffd commit 2a1e083
Show file tree
Hide file tree
Showing 49 changed files with 589 additions and 491 deletions.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,53 +1,11 @@
namespace Serenity.CodeGeneration;
namespace Serenity.CodeGeneration;

public class PhysicalGeneratorFileSystem : PhysicalFileSystem, IGeneratorFileSystem
public class PhysicalGeneratorFileSystem : PhysicalFileSystem
{
public DateTime GetLastWriteTime(string path)
{
return System.IO.File.GetLastWriteTime(path);
}

#if ISSOURCEGENERATOR
// https://stackoverflow.com/questions/275689/how-to-get-relative-path-from-absolute-path/32113484#32113484
public override string GetRelativePath(string fromPath, string toPath)
{
if (string.IsNullOrEmpty(fromPath))
throw new ArgumentNullException("fromPath");

if (string.IsNullOrEmpty(toPath))
throw new ArgumentNullException("toPath");

fromPath = fromPath.Replace("/", "\\", StringComparison.Ordinal);
toPath = toPath.Replace("/", "\\", StringComparison.Ordinal);

if (!fromPath.Contains(':', StringComparison.Ordinal))
fromPath = "z:\\" + fromPath;

if (!toPath.Contains(':', StringComparison.Ordinal))
toPath = "z:\\" + toPath;

Uri fromUri = new(AppendDirectorySeparatorChar(fromPath));
Uri toUri = new(AppendDirectorySeparatorChar(toPath));

if (fromUri.Scheme != toUri.Scheme)
return toPath;

Uri relativeUri = fromUri.MakeRelativeUri(toUri);
string relativePath = Uri.UnescapeDataString(relativeUri.ToString());

if (string.Equals(toUri.Scheme, Uri.UriSchemeFile, StringComparison.OrdinalIgnoreCase))
relativePath = relativePath.Replace(System.IO.Path.AltDirectorySeparatorChar, System.IO.Path.DirectorySeparatorChar);

return relativePath;
}

private static string AppendDirectorySeparatorChar(string path)
{
if (!System.IO.Path.HasExtension(path) &&
!path.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()))
return path + System.IO.Path.DirectorySeparatorChar;

return path;
}
#endif
}
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,12 @@ public override void VisitNamedType(INamedTypeSymbol type)
}
}
#else
protected TypingsGeneratorBase(IGeneratorFileSystem fileSystem, params Assembly[] assemblies)
protected TypingsGeneratorBase(IFileSystem fileSystem, params Assembly[] assemblies)
: this(TypingsUtils.ToDefinitions(fileSystem, assemblies?.Select(x => x.Location)))
{
}

protected TypingsGeneratorBase(IGeneratorFileSystem fileSystem, params string[] assemblyLocations)
protected TypingsGeneratorBase(IFileSystem fileSystem, params string[] assemblyLocations)
: this(TypingsUtils.ToDefinitions(fileSystem, assemblyLocations))
{
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -579,7 +579,7 @@ public static bool IsSubclassOf(TypeReference type, string ns, string name)
}

#if !ISSOURCEGENERATOR
public static Mono.Cecil.AssemblyDefinition[] ToDefinitions(IGeneratorFileSystem fileSystem,
public static Mono.Cecil.AssemblyDefinition[] ToDefinitions(IFileSystem fileSystem,
IEnumerable<string> assemblyLocations)
{
if (assemblyLocations == null || !assemblyLocations.Any())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ public partial class ServerTypingsGenerator(Microsoft.CodeAnalysis.Compilation c
#else
public partial class ServerTypingsGenerator : TypingsGeneratorBase
{
public ServerTypingsGenerator(IGeneratorFileSystem fileSystem, params Assembly[] assemblies)
public ServerTypingsGenerator(IFileSystem fileSystem, params Assembly[] assemblies)
: base(fileSystem, assemblies)
{
}

public ServerTypingsGenerator(IGeneratorFileSystem fileSystem, params string[] assemblyLocations)
public ServerTypingsGenerator(IFileSystem fileSystem, params string[] assemblyLocations)
: base(fileSystem, assemblyLocations)
{
}
Expand Down
14 changes: 7 additions & 7 deletions src/Serenity.Net.CodeGenerator/Commands/ClientTypesCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@

namespace Serenity.CodeGenerator;

public class ClientTypesCommand(IGeneratorFileSystem fileSystem) : BaseFileSystemCommand(fileSystem)
public class ClientTypesCommand(ProjectFileInfo project) : BaseGeneratorCommand(project)
{
public void Run(string csproj, List<ExternalType> tsTypes)
public void Run(List<ExternalType> tsTypes)
{
var projectDir = fileSystem.GetDirectoryName(csproj);
var config = fileSystem.LoadGeneratorConfig(projectDir);
var projectDir = FileSystem.GetDirectoryName(ProjectFile);
var config = FileSystem.LoadGeneratorConfig(projectDir);

config.ClientTypes ??= new GeneratorConfig.ClientTypesConfig();

if (string.IsNullOrEmpty(config.RootNamespace))
config.RootNamespace = config.GetRootNamespaceFor(fileSystem, csproj);
config.RootNamespace = config.GetRootNamespaceFor(new ProjectFileInfo(FileSystem, ProjectFile));

var outDir = fileSystem.Combine(projectDir, PathHelper.ToPath(config.ClientTypes.OutDir.TrimToNull() ?? "Imports/ClientTypes"));
var outDir = FileSystem.Combine(projectDir, PathHelper.ToPath(config.ClientTypes.OutDir.TrimToNull() ?? "Imports/ClientTypes"));

Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("Transforming ClientTypes at: ");
Expand All @@ -35,7 +35,7 @@ public void Run(string csproj, List<ExternalType> tsTypes)
generator.AddTSType(type);

var generatedSources = generator.Run();
MultipleOutputHelper.WriteFiles(fileSystem, outDir,
MultipleOutputHelper.WriteFiles(FileSystem, outDir,
generatedSources.Select(x => (x.Filename, x.Text)),
deleteExtraPattern: null,
endOfLine: config.EndOfLine);
Expand Down
18 changes: 7 additions & 11 deletions src/Serenity.Net.CodeGenerator/Commands/GenerateCommand.Shared.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,16 +42,14 @@ private static void UpdateConfigTableFor(EntityModelInputs inputs,
}
}

private static EntityModel CreateEntityModel(EntityModelInputs inputs,
private EntityModel CreateEntityModel(EntityModelInputs inputs,
IEntityModelGenerator modelGenerator,
string csproj,
IGeneratorFileSystem fileSystem,
ISqlConnections sqlConnections)
{
using var connection = sqlConnections.NewByKey(inputs.ConnectionKey);
connection.EnsureOpen();

var csprojContent = fileSystem.ReadAllText(csproj);
var csprojContent = FileSystem.ReadAllText(Project.ProjectFile);
inputs.Net5Plus = !targetFrameworkNetCoreRegexGen().IsMatch(csprojContent);

inputs.SchemaIsDatabase = connection.GetDialect().ServerType.StartsWith("MySql",
Expand All @@ -61,23 +59,21 @@ private static EntityModel CreateEntityModel(EntityModelInputs inputs,
return modelGenerator.GenerateModel(inputs);
}

private static EntityCodeGenerator CreateCodeGenerator(EntityModelInputs inputs,
private EntityCodeGenerator CreateCodeGenerator(EntityModelInputs inputs,
IEntityModelGenerator modelGenerator,
string csproj,
IGeneratorFileSystem fileSystem,
ISqlConnections sqlConnections,
bool interactive = true)
{
var entityModel = CreateEntityModel(inputs, modelGenerator, csproj, fileSystem, sqlConnections);
var entityModel = CreateEntityModel(inputs, modelGenerator, sqlConnections);

var codeFileHelper = new CodeFileHelper(fileSystem)
var codeFileHelper = new CodeFileHelper(Project.FileSystem)
{
NoUserInteraction = !interactive,
Kdiff3Path = new[] { inputs.Config.KDiff3Path }.FirstOrDefault(fileSystem.FileExists),
Kdiff3Path = new[] { inputs.Config.KDiff3Path }.FirstOrDefault(Project.FileSystem.FileExists),
TSCPath = inputs.Config.TSCPath ?? "tsc"
};

return new EntityCodeGenerator(fileSystem, codeFileHelper, entityModel, inputs.Config, csproj);
return new EntityCodeGenerator(Project, codeFileHelper, entityModel, inputs.Config);
}

private static void RegisterSqlProviders()
Expand Down
22 changes: 11 additions & 11 deletions src/Serenity.Net.CodeGenerator/Commands/GenerateCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@

namespace Serenity.CodeGenerator;

public partial class GenerateCommand(IGeneratorFileSystem fileSystem, IAnsiConsole ansiConsole) : BaseFileSystemCommand(fileSystem)
public partial class GenerateCommand(IProjectFileInfo project, IAnsiConsole ansiConsole) : BaseGeneratorCommand(project)
{
private readonly IAnsiConsole ansiConsole = ansiConsole ?? throw new ArgumentNullException(nameof(ansiConsole));

public ExitCodes Run(string csproj, string[] args)
public ExitCodes Run(string[] args)
{
var projectDir = fileSystem.GetDirectoryName(csproj);
var config = fileSystem.LoadGeneratorConfig(projectDir);
var projectDir = FileSystem.GetDirectoryName(ProjectFile);
var config = FileSystem.LoadGeneratorConfig(projectDir);

var connectionStrings = ParseConnectionStrings(fileSystem, csproj, config);
var connectionStrings = ParseConnectionStrings(FileSystem, ProjectFile, config);
if (connectionStrings.Count == 0)
{
Error("No connections in appsettings files or sergen.json!");
Expand All @@ -25,7 +25,7 @@ public ExitCodes Run(string csproj, string[] args)
var argsPermissionKey = GetOption(args, "p").TrimToNull();

if (!string.IsNullOrEmpty(config.CustomTemplates))
Templates.TemplatePath = fileSystem.Combine(projectDir, config.CustomTemplates);
Templates.TemplatePath = FileSystem.Combine(projectDir, config.CustomTemplates);

WriteHeading("Table Code Generation");

Expand Down Expand Up @@ -132,10 +132,10 @@ public ExitCodes Run(string csproj, string[] args)
ApplicationMetadata application = null;
try
{
var assemblyFiles = ServerTypingsCommand.DetermineAssemblyFiles(fileSystem, csproj, config, (error) => { });
var assemblyFiles = ServerTypingsCommand.DetermineAssemblyFiles(Project, config, (error) => { });
if (assemblyFiles != null && assemblyFiles.Length > 0)
{
application = new ApplicationMetadata(fileSystem, assemblyFiles)
application = new ApplicationMetadata(FileSystem, assemblyFiles)
{
DefaultSchema = schemaProvider.DefaultSchema
};
Expand All @@ -145,7 +145,7 @@ public ExitCodes Run(string csproj, string[] args)
inputs.SkipForeignKeys = true;
try
{
var entityModel = CreateEntityModel(inputs, new EntityModelGenerator(), csproj, fileSystem, sqlConnections);
var entityModel = CreateEntityModel(inputs, new EntityModelGenerator(), sqlConnections);
application.EntityModels.Add(entityModel);
}
finally
Expand All @@ -164,13 +164,13 @@ public ExitCodes Run(string csproj, string[] args)
inputs.Application = application;

var generator = CreateCodeGenerator(inputs, new EntityModelGenerator(),
csproj, fileSystem, sqlConnections, interactive: true);
sqlConnections, interactive: true);

generator.Run();
}

if (config.SaveGeneratedTables != false)
fileSystem.WriteAllText(fileSystem.Combine(projectDir, "sergen.json"), config.SaveToJson());
FileSystem.WriteAllText(FileSystem.Combine(projectDir, "sergen.json"), config.SaveToJson());

return ExitCodes.Success;
}
Expand Down
34 changes: 17 additions & 17 deletions src/Serenity.Net.CodeGenerator/Commands/MvcCommand.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
namespace Serenity.CodeGenerator;
namespace Serenity.CodeGenerator;

public class MvcCommand(IGeneratorFileSystem fileSystem) : BaseFileSystemCommand(fileSystem)
public class MvcCommand(IProjectFileInfo project) : BaseGeneratorCommand(project)
{
public void Run(string csproj)
public void Run()
{
var projectDir = fileSystem.GetDirectoryName(csproj);
var config = fileSystem.LoadGeneratorConfig(projectDir);
var projectDir = FileSystem.GetDirectoryName(ProjectFile);
var config = FileSystem.LoadGeneratorConfig(projectDir);

config.MVC ??= new();

var outDir = fileSystem.Combine(projectDir, PathHelper.ToPath(config.MVC.OutDir.TrimToNull() ?? "Imports/MVC"));
var outDir = FileSystem.Combine(projectDir, PathHelper.ToPath(config.MVC.OutDir.TrimToNull() ?? "Imports/MVC"));

Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("Transforming MVC at: ");
Expand All @@ -19,31 +19,31 @@ public void Run(string csproj)
string[] stripViewPaths = config.MVC.StripViewPaths ?? [
"Modules/",
"Views/",
fileSystem.GetFileNameWithoutExtension(csproj) + "/",
"Areas/" + fileSystem.GetFileNameWithoutExtension(csproj) + "/"
FileSystem.GetFileNameWithoutExtension(ProjectFile) + "/",
"Areas/" + FileSystem.GetFileNameWithoutExtension(ProjectFile) + "/"
];

var rootDir = projectDir + System.IO.Path.DirectorySeparatorChar;
var searchViewPaths = (config.MVC.SearchViewPaths ??
[
"Modules/",
"Views/",
fileSystem.GetFileNameWithoutExtension(csproj) + "/",
"Areas/" + fileSystem.GetFileNameWithoutExtension(csproj) + "/"
FileSystem.GetFileNameWithoutExtension(ProjectFile) + "/",
"Areas/" + FileSystem.GetFileNameWithoutExtension(ProjectFile) + "/"
])
.Select(x => fileSystem.Combine(rootDir, PathHelper.ToPath(x)));
.Select(x => FileSystem.Combine(rootDir, PathHelper.ToPath(x)));

IEnumerable<string> files = new List<string>();
foreach (var path in searchViewPaths)
{
if (fileSystem.DirectoryExists(path))
files = files.Concat(fileSystem.GetFiles(path, "*.cshtml", recursive: true));
if (FileSystem.DirectoryExists(path))
files = files.Concat(FileSystem.GetFiles(path, "*.cshtml", recursive: true));
}

string getName(string s)
{
var path = s[rootDir.Length..];
var name = fileSystem.ChangeExtension(path, null).Replace('\\', '/');
var name = FileSystem.ChangeExtension(path, null).Replace('\\', '/');
foreach (var strip in stripViewPaths)
{
if (name.StartsWith(strip, StringComparison.OrdinalIgnoreCase))
Expand All @@ -67,8 +67,8 @@ string getName(string s)
cw.AppendLine("");
var ns = (config.MVC.UseRootNamespace == true ||
(config.MVC.UseRootNamespace == null &&
fileSystem.ReadAllText(csproj).Contains("Sdk=\"Microsoft.NET.Sdk.Razor\"", StringComparison.CurrentCulture))) ?
config.GetRootNamespaceFor(fileSystem, csproj) + ".MVC" : "MVC";
FileSystem.ReadAllText(ProjectFile).Contains("Sdk=\"Microsoft.NET.Sdk.Razor\"", StringComparison.CurrentCulture))) ?
config.GetRootNamespaceFor(new ProjectFileInfo(FileSystem, ProjectFile)) + ".MVC" : "MVC";

cw.InNamespace(ns, () =>
{
Expand Down Expand Up @@ -141,7 +141,7 @@ string getName(string s)
});

MultipleOutputHelper.WriteFiles(fileSystem, outDir, new[]
MultipleOutputHelper.WriteFiles(FileSystem, outDir, new[]
{
("MVC.cs", cw.ToString())
}, deleteExtraPattern: null, endOfLine: config.EndOfLine);
Expand Down
Loading

0 comments on commit 2a1e083

Please sign in to comment.