Parcourir la source

Able to generate records

Piotr Czajkowski il y a 4 mois
Parent
commit
c42cbabf5a

+ 6 - 0
CodeGenerators/CodeGenerators.sln

@@ -4,6 +4,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeGenerators", "CodeGener
 EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeGeneratorsTests", "CodeGeneratorsTests\CodeGeneratorsTests.csproj", "{251E5058-FEC4-4160-B33F-0E801C9E5523}"
 EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GeneratorForExcelORM", "GeneratorForExcelORM\GeneratorForExcelORM.csproj", "{2C508AE1-CE1B-4733-91C3-7B71B4179F52}"
+EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Any CPU = Debug|Any CPU
@@ -18,5 +20,9 @@ Global
 		{251E5058-FEC4-4160-B33F-0E801C9E5523}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{251E5058-FEC4-4160-B33F-0E801C9E5523}.Release|Any CPU.ActiveCfg = Release|Any CPU
 		{251E5058-FEC4-4160-B33F-0E801C9E5523}.Release|Any CPU.Build.0 = Release|Any CPU
+		{2C508AE1-CE1B-4733-91C3-7B71B4179F52}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{2C508AE1-CE1B-4733-91C3-7B71B4179F52}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{2C508AE1-CE1B-4733-91C3-7B71B4179F52}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{2C508AE1-CE1B-4733-91C3-7B71B4179F52}.Release|Any CPU.Build.0 = Release|Any CPU
 	EndGlobalSection
 EndGlobal

+ 3 - 3
CodeGenerators/CodeGenerators/ClassRecordGenerator.cs

@@ -7,13 +7,13 @@ public class ClassRecordGenerator : IGenerator
     public List<string> Usings { get; } = new();
     public Dictionary<string, IGenerator> Properties { get; set; } = new();
     private readonly string namespaceName;
-    private readonly string name;
+    public string Name { get; }
     private readonly bool isRecord;
 
     public ClassRecordGenerator(string namespaceName, string name, bool isRecord = false)
     {
         this.namespaceName = Helpers.SanitizeName(namespaceName);
-        this.name = Helpers.SanitizeName(name);
+        Name = Helpers.SanitizeName(name);
         this.isRecord = isRecord;
     }
 
@@ -31,7 +31,7 @@ public class ClassRecordGenerator : IGenerator
         sb.AppendLine($"namespace {namespaceName};");
         sb.AppendLine();
 
-        sb.AppendLine($"public {(isRecord ? "record" : "class")} {name}\n{{");
+        sb.AppendLine($"public {(isRecord ? "record" : "class")} {Name}\n{{");
 
         if (Properties.Any())
             sb.AppendLine(string.Join("\n\n", Properties.Select(x => x.Value.Build(indent+1))));

+ 71 - 1
CodeGenerators/GeneratorForExcelORM/GeneratorCmd.cs

@@ -1,6 +1,76 @@
+using System.ComponentModel;
+using ClosedXML.Excel;
+using CodeGenerators;
+using ExcelInfo;
+using Spectre.Cli;
+
 namespace GeneratorForExcelORM;
 
-public class GeneratorCmd
+internal sealed class GeneratorCmd : Command<GeneratorCmd.Settings>
 {
+    public sealed class Settings : CommandSettings
+    {
+        [Description("Path to XLSX file.")]
+        [CommandArgument(0, "[inputPath]")]
+        public string? InputPath { get; init; }
+
+        [Description("Start from n row. Default 1.")]
+        [DefaultValue((uint)1)]
+        [CommandOption("-s|--startFrom")]
+        public uint StartFrom { get; init; }
+    }
+
+    string GetType(XLDataType type) =>
+        type switch
+        {
+            XLDataType.Number => "double?",
+            XLDataType.Text => "string?",
+            XLDataType.DateTime => "DateTime?",
+            XLDataType.TimeSpan => "TimeSpan?",
+            _ => throw new Exception($"Can't match {type}!")
+        };
+    
+    void GenerateRecord(WorksheetRecord worksheet, string outputFolder, string filename)
+    {
+        var recordObject = new ClassRecordGenerator(filename, worksheet.Name, true);
+        var outputPath = Path.Combine(outputFolder, $"{recordObject.Name}.cs");
+        recordObject.Usings.Add("ExcelORM");
+
+        foreach (var column in worksheet.Columns)
+        {
+            if (string.IsNullOrWhiteSpace(column.Name)) continue;
+            
+            var propertyObject = new Property(column.Name, GetType(column.Type));
+            propertyObject.Attributes.Add(new AttributeElement("Column", column.Name));
+            
+            if (!recordObject.Properties.TryAdd(propertyObject.Name, propertyObject))
+                Console.Error.WriteLine($"Duplicated property {propertyObject.Name}!");
+        }
+        
+        File.WriteAllText(outputPath, recordObject.Build());
+    }
+
+    void Generate(Settings settings)
+    {
+        if (string.IsNullOrWhiteSpace(settings.InputPath)) return;
+        
+        var worksheetsInfo = WorkbookInfo.GetInfoOnWorksheets(settings.InputPath, settings.StartFrom).ToArray();
+        if (worksheetsInfo.Length == 0) throw new Exception("Nothing to process!");
+
+        var outputFolder = Path.GetDirectoryName(settings.InputPath);
+        if (string.IsNullOrWhiteSpace(outputFolder))
+            throw new Exception($"Can't establish folder from {settings.InputPath}!");
+        
+        var filename = Path.GetFileNameWithoutExtension(settings.InputPath);
+        foreach(var worksheet in worksheetsInfo)
+            GenerateRecord(worksheet, outputFolder, filename);
+    }
     
+    public override int Execute(CommandContext context, Settings settings)
+    {
+        if (!File.Exists(settings.InputPath)) throw new FileNotFoundException(settings.InputPath);
+        
+        Generate(settings);
+        return 0;
+    } 
 }

+ 25 - 0
CodeGenerators/GeneratorForExcelORM/GeneratorForExcelORM.csproj

@@ -0,0 +1,25 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+    <PropertyGroup>
+        <OutputType>Exe</OutputType>
+        <TargetFramework>net7.0</TargetFramework>
+        <ImplicitUsings>enable</ImplicitUsings>
+        <Nullable>enable</Nullable>
+    </PropertyGroup>
+
+    <ItemGroup>
+      <ProjectReference Include="..\CodeGenerators\CodeGenerators.csproj" />
+    </ItemGroup>
+
+    <ItemGroup>
+      <PackageReference Include="ExcelInfo" Version="1.0.0" />
+      <PackageReference Include="Spectre.Cli" Version="0.49.0" />
+    </ItemGroup>
+
+    <ItemGroup>
+      <None Update="testFiles\differentTypes.xlsx">
+        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+      </None>
+    </ItemGroup>
+
+</Project>

+ 5 - 0
CodeGenerators/GeneratorForExcelORM/Program.cs

@@ -0,0 +1,5 @@
+using GeneratorForExcelORM;
+using Spectre.Cli;
+
+var app = new CommandApp<GeneratorCmd>();
+return app.Run(args);

BIN
CodeGenerators/GeneratorForExcelORM/testFiles/differentTypes.xlsx