饭太稀

This commit is contained in:
bob
2025-06-30 10:51:37 +08:00
commit 8e45469c83
753 changed files with 87652 additions and 0 deletions

View File

@@ -0,0 +1,24 @@
namespace Fantasy.Tools.ConfigTable;
/// <summary>
/// 导出类型枚举,用于标识不同类型的导出操作。
/// </summary>
public enum ExportType
{
/// <summary>
/// 无导出类型。
/// </summary>
None = 0,
/// <summary>
/// 所有数据的增量导出Excel类型。
/// </summary>
AllExcelIncrement = 1,
/// <summary>
/// 所有数据的全量导出Excel类型。
/// </summary>
AllExcel = 2,
/// <summary>
/// 导出类型枚举的最大值,一定要放在最后。
/// </summary>
Max,
}

View File

@@ -0,0 +1,158 @@
// using System;
// using System.Text;
// using Exporter.Excel;
// using Fantasy.Exporter;
// using OfficeOpenXml;
//
// namespace Exporter;
//
// public class ConstValueToConst : ACustomExport
// {
// public override void Run()
// {
// if (!ExcelExporter.LoadIgnoreExcel("#ConstValue", out var excelPackage))
// {
// Log.Error("ConstValueToConst: Load Excel failed.");
// return;
// }
//
// var worksheet = excelPackage.Workbook.Worksheets[0];
//
// var serverHotfixStrBuilder = new StringBuilder();
// serverHotfixStrBuilder.AppendLine("namespace Fantasy\n{");
// serverHotfixStrBuilder.AppendLine("\t// 生成器自动生成,请不要手动编辑,修改请在#ConstValue.xsl里。");
// serverHotfixStrBuilder.AppendLine("\tpublic partial class ConstValueHotfix\n\t{");
//
// var serverModelStrBuilder = new StringBuilder();
// serverModelStrBuilder.AppendLine("namespace Fantasy\n{");
// serverModelStrBuilder.AppendLine("\t// 生成器自动生成,请不要手动编辑。");
// serverModelStrBuilder.AppendLine("\tpublic partial class ConstValue\n\t{");
//
// var clientStrBuilder = new StringBuilder();
// clientStrBuilder.AppendLine("namespace Fantasy\n{");
// clientStrBuilder.AppendLine("\t// 生成器自动生成,请不要手动编辑。");
// clientStrBuilder.AppendLine("\tpublic class ConstValue\n\t{");
//
// for (var row = 2; row <= worksheet.Dimension.Rows; row++)
// {
// var first = worksheet.GetCellValue(row, 1);
// var second = worksheet.GetCellValue(row, 2);
// var lower = first?.ToLower() ?? "";
// var isClient = lower.Contains("c");
// var isServerModel = lower.Contains("sh");
// var isServerHotfix = lower.Contains("sm");
//
// if (string.IsNullOrEmpty(second))
// {
// continue;
// }
//
// string str;
//
// if (second.StartsWith("#"))
// {
// str = $"\t\t// {second}";
// clientStrBuilder.AppendLine(str);
// serverModelStrBuilder.AppendLine(str);
// serverHotfixStrBuilder.AppendLine(str);
// continue;
// }
//
// str = GetCodeStr(worksheet, row);
//
// if (isServerModel)
// {
// serverModelStrBuilder.AppendLine(str);
// }
//
// if (isServerHotfix)
// {
// serverHotfixStrBuilder.AppendLine(str);
// }
//
// if (isClient)
// {
// clientStrBuilder.AppendLine(str);
// }
// }
//
// clientStrBuilder.AppendLine("\t}\n}");
// serverModelStrBuilder.AppendLine("\t}\n}");
// serverHotfixStrBuilder.AppendLine("\t}\n}");
//
// Write("ConstValue.cs", clientStrBuilder.ToString(), CustomExportType.Client);
// Write("ConstValue.cs", serverModelStrBuilder.ToString(), CustomExportType.Server);
// Write("ConstValueHotfix.cs", serverHotfixStrBuilder.ToString(),"../../Server/Hotfix/Generate/CustomExport123" ,CustomExportType.Server);
// }
//
// private static string GetCodeStr(ExcelWorksheet sheet, int row)
// {
// var typeStr = sheet.GetCellValue(row, 3);
// var name = sheet.GetCellValue(row, 2);
// var value = sheet.GetCellValue(row, 4);
// var desc = sheet.GetCellValue(row, 5);
//
// try
// {
// if (typeStr.Contains("[]") || typeStr.Contains("[,]"))
// {
// return $"\t\tpublic static readonly {typeStr} {name} = {DefaultValue(typeStr, value)}; // {desc}";
// }
//
// if (typeStr.Contains("Vector"))
// {
// return $"\t\tpublic static readonly {typeStr} {name} = {DefaultValue(typeStr, value)}; // {desc}";
// }
//
// return $"\t\tpublic const {typeStr} {name} = {DefaultValue(typeStr, value)}; // {desc}";
// }
// catch (Exception e)
// {
// Log.Error($"{name} 常量导出异常 : {e}");
// return "";
// }
// }
//
// private static string DefaultValue(string type, string value)
// {
// switch (type)
// {
// case "byte[]":
// case "int[]":
// case "long[]":
// case "string[]":
// case "double[]":
// case "float[]":
// return $"new {type} {{{value}}}";
// case "byte[,]":
// case "int[,]":
// case "long[,]":
// case "string[,]":
// case "float[,]":
// case "double[,]":
// return $"new {type} {{{value}}}";
// case "int":
// case "bool":
// case "uint":
// case "long":
// case "double":
// return $"{value}";
// case "float":
// return value[^1] == 'f' ? value : $"{value}f";
// case "string":
// return $"\"{value}\"";
// case "Vector2":
// {
// var strings = value.Split(',', StringSplitOptions.TrimEntries);
// return $"new Vector2({strings[0]},{strings[1]})";
// }
// case "Vector3":
// {
// var strings = value.Split(',', StringSplitOptions.TrimEntries);
// return $"new Vector3({strings[0]},{strings[1]},{strings[2]})";
// }
// default:
// throw new Exception($"不支持此类型: {type}");
// }
// }
// }

View File

@@ -0,0 +1,62 @@
using System.Text;
using Fantasy.Tools.ConfigTable;
using System.Collections.Generic;
namespace Exporter;
/// <summary>
/// 将场景类型配置表转换为枚举和字典的自定义导出类。
/// </summary>
public class SceneTypeConfigToEnum : ACustomExport
{
public override void Run()
{
var sceneType = new Dictionary<string, string>();
// 获取场景配置表的完整路径
if (!Worksheets.TryGetValue("SceneTypeConfig", out var sceneTypeConfig))
{
return;
}
for (var row = 3; row <= sceneTypeConfig.Dimension.Rows; row++)
{
var sceneTypeId = sceneTypeConfig.GetCellValue(row, 1);
var sceneTypeStr = sceneTypeConfig.GetCellValue(row, 2);
if (string.IsNullOrEmpty(sceneTypeId) || string.IsNullOrEmpty(sceneTypeStr))
{
continue;
}
sceneType.Add(sceneTypeId, sceneTypeStr);
}
// 如果存在场景类型或场景子类型,执行导出操作
if (sceneType.Count > 0)
{
Write(CustomExportType.Server, sceneType);
}
}
private void Write(CustomExportType customExportType, Dictionary<string, string> sceneTypes)
{
var strBuilder = new StringBuilder();
var dicBuilder = new StringBuilder();
// 添加命名空间和注释头部
strBuilder.AppendLine("namespace Fantasy\n{");
strBuilder.AppendLine("\t// 生成器自动生成,请不要手动编辑。");
// 生成场景类型的静态类
strBuilder.AppendLine("\tpublic static class SceneType\n\t{");
dicBuilder.AppendLine("\n\t\tpublic static readonly Dictionary<string, int> SceneTypeDic = new Dictionary<string, int>()\n\t\t{");
// 遍历场景类型字典,生成场景类型的常量和字典项
foreach (var (sceneTypeId, sceneTypeStr) in sceneTypes)
{
dicBuilder.AppendLine($"\t\t\t{{ \"{sceneTypeStr}\", {sceneTypeId} }},");
strBuilder.AppendLine($"\t\tpublic const int {sceneTypeStr} = {sceneTypeId};");
}
// 添加场景类型字典尾部,合并到主字符串构建器中
dicBuilder.AppendLine("\t\t};");
strBuilder.Append(dicBuilder);
strBuilder.AppendLine("\t}\n}");
// 调用外部方法将生成的代码写入文件
Write("SceneType.cs", strBuilder.ToString(), customExportType);
}
}

View File

@@ -0,0 +1,13 @@
using Fantasy.Serialize;
#pragma warning disable CS8603 // Possible null reference return.
namespace Fantasy;
public static class ConfigTableHelper
{
public static T Load<T>() where T : ASerialize
{
return default;
}
}

View File

@@ -0,0 +1,170 @@
using System.Reflection;
using Fantasy.Exporter;
using Fantasy.Serialize;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using ProtoBuf;
#pragma warning disable CS8601 // Possible null reference assignment.
namespace Exporter.Excel;
/// <summary>
/// 动态程序集类,用于加载动态生成的程序集并获取动态信息。
/// </summary>
public static class DynamicAssembly
{
private static void MetadataReference(out string assemblyName, out List<MetadataReference> metadataReferenceList)
{
AssemblyMetadata assemblyMetadata;
MetadataReference metadataReference;
var currentDomain = AppDomain.CurrentDomain;
assemblyName = Path.GetRandomFileName();
var assemblyArray = currentDomain.GetAssemblies();
metadataReferenceList = new List<MetadataReference>();
// 注册引用
foreach (var domainAssembly in assemblyArray)
{
if (string.IsNullOrEmpty(domainAssembly.Location))
{
continue;
}
assemblyMetadata = AssemblyMetadata.CreateFromFile(domainAssembly.Location);
metadataReference = assemblyMetadata.GetReference();
metadataReferenceList.Add(metadataReference);
}
// 添加Proto支持
assemblyMetadata = AssemblyMetadata.CreateFromFile(typeof(ProtoMemberAttribute).Assembly.Location);
metadataReference = assemblyMetadata.GetReference();
metadataReferenceList.Add(metadataReference);
// 添加Fantasy支持
assemblyMetadata = AssemblyMetadata.CreateFromFile(typeof(ASerialize).Assembly.Location);
metadataReference = assemblyMetadata.GetReference();
metadataReferenceList.Add(metadataReference);
}
/// <summary>
/// 加载指定路径下的动态程序集。
/// </summary>
/// <param name="path">程序集文件路径。</param>
/// <returns>加载的动态程序集。</returns>
public static Assembly Load(string path)
{
var fileList = new List<string>();
// 找到所有需要加载的CS文件
foreach (string file in Directory.GetFiles(path))
{
if (Path.GetExtension(file) != ".cs")
{
continue;
}
fileList.Add(file);
}
var syntaxTreeList = new List<SyntaxTree>();
foreach (var file in fileList)
{
using var fileStream = new StreamReader(file);
var cSharp = CSharpSyntaxTree.ParseText(fileStream.ReadToEnd());
syntaxTreeList.Add(cSharp);
}
// 注册程序集
MetadataReference(out var assemblyName, out var metadataReferenceList);
var compilation = CSharpCompilation.Create(assemblyName, syntaxTreeList, metadataReferenceList, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using var ms = new MemoryStream();
var result = compilation.Emit(ms);
if (!result.Success)
{
foreach (var resultDiagnostic in result.Diagnostics)
{
Log.Error(resultDiagnostic.GetMessage());
}
throw new Exception("failures");
}
ms.Seek(0, SeekOrigin.Begin);
return Assembly.Load(ms.ToArray());
}
/// <summary>
/// 获取动态程序集中指定表格的动态信息。
/// </summary>
/// <param name="dynamicAssembly">动态程序集。</param>
/// <param name="tableName">表格名称。</param>
/// <returns>动态信息对象。</returns>
public static DynamicConfigDataType GetDynamicInfo(Assembly dynamicAssembly, string tableName)
{
var dynamicConfigDataType = new DynamicConfigDataType
{
ConfigDataType = GetConfigType(dynamicAssembly, $"{tableName}Data"),
ConfigType = GetConfigType(dynamicAssembly, $"{tableName}")
};
dynamicConfigDataType.ConfigData = CreateInstance(dynamicConfigDataType.ConfigDataType);
var listPropertyType = dynamicConfigDataType.ConfigDataType.GetProperty("List");
if (listPropertyType == null)
{
throw new Exception("No Property named Add was found");
}
dynamicConfigDataType.Obj = listPropertyType.GetValue(dynamicConfigDataType.ConfigData);
dynamicConfigDataType.Method = listPropertyType.PropertyType.GetMethod("Add");
if (dynamicConfigDataType.Method == null)
{
throw new Exception("No method named Add was found");
}
return dynamicConfigDataType;
}
/// <summary>
/// 根据类型名称获取动态类型。
/// </summary>
/// <param name="dynamicAssembly">动态程序集。</param>
/// <param name="typeName">类型名称。</param>
/// <returns>动态类型。</returns>
private static Type GetConfigType(Assembly dynamicAssembly, string typeName)
{
var configType = dynamicAssembly.GetType($"Fantasy.{typeName}");
if (configType == null)
{
throw new FileNotFoundException($"Fantasy.{typeName} not found");
}
return configType;
// return dynamicAssembly.GetType($"Fantasy.{typeName}");
}
/// <summary>
/// 创建动态实例。
/// </summary>
/// <param name="configType">动态类型。</param>
/// <returns>动态实例。</returns>
public static object CreateInstance(Type configType)
{
var config = Activator.CreateInstance(configType);
if (config == null)
{
throw new Exception($"{configType.Name} is Activator.CreateInstance error");
}
return config;
}
}

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Text;
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
namespace Exporter.Excel;
/// <summary>
/// 动态配置数据类型类,用于存储动态配置数据的相关信息。
/// </summary>
public class DynamicConfigDataType
{
/// <summary>
/// 配置数据对象,继承自 AProto 基类。
/// </summary>
public object ConfigData;
/// <summary>
/// 配置数据类型。
/// </summary>
public Type ConfigDataType;
/// <summary>
/// 配置类型。
/// </summary>
public Type ConfigType;
/// <summary>
/// 反射方法信息,用于调用特定方法。
/// </summary>
public MethodInfo Method;
/// <summary>
/// 配置数据对象实例。
/// </summary>
public object Obj;
/// <summary>
/// 用于生成 JSON 格式数据的字符串构建器。
/// </summary>
public StringBuilder Json = new StringBuilder();
}

View File

@@ -0,0 +1,70 @@
using System.Reflection;
using Fantasy.Exporter;
using Fantasy.Serialize;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using ProtoBuf;
namespace Exporter.Excel;
public class OneDynamicAssembly
{
private readonly List<SyntaxTree> _syntaxTreeList = new List<SyntaxTree>();
public void Load(string file)
{
using var fileStream = new StreamReader(file);
var cSharp = CSharpSyntaxTree.ParseText(fileStream.ReadToEnd());
_syntaxTreeList.Add(cSharp);
}
public Assembly Assembly
{
get
{
AssemblyMetadata assemblyMetadata;
MetadataReference metadataReference;
var currentDomain = AppDomain.CurrentDomain;
var assemblyName = Path.GetRandomFileName();
var assemblyArray = currentDomain.GetAssemblies();
var metadataReferenceList = new List<MetadataReference>();
// 注册引用
foreach (var domainAssembly in assemblyArray)
{
if (string.IsNullOrEmpty(domainAssembly.Location))
{
continue;
}
assemblyMetadata = AssemblyMetadata.CreateFromFile(domainAssembly.Location);
metadataReference = assemblyMetadata.GetReference();
metadataReferenceList.Add(metadataReference);
}
// 添加ProtoEntity支持
assemblyMetadata = AssemblyMetadata.CreateFromFile(typeof(ASerialize).Assembly.Location);
metadataReference = assemblyMetadata.GetReference();
metadataReferenceList.Add(metadataReference);
// 添加MessagePack支持
assemblyMetadata = AssemblyMetadata.CreateFromFile(typeof(ProtoMemberAttribute).Assembly.Location);
metadataReference = assemblyMetadata.GetReference();
metadataReferenceList.Add(metadataReference);
CSharpCompilation compilation = CSharpCompilation.Create(assemblyName, _syntaxTreeList, metadataReferenceList, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using var ms = new MemoryStream();
var result = compilation.Emit(ms);
if (!result.Success)
{
foreach (var resultDiagnostic in result.Diagnostics)
{
Log.Error(resultDiagnostic.GetMessage());
}
throw new Exception("failures");
}
ms.Seek(0, SeekOrigin.Begin);
return Assembly.Load(ms.ToArray());
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,47 @@
using OfficeOpenXml;
namespace Fantasy.Tools.ConfigTable;
/// <summary>
/// 提供操作 Excel 文件的辅助方法。
/// </summary>
public static class ExcelHelper
{
/// <summary>
/// 加载 Excel 文件并返回 ExcelPackage 实例。
/// </summary>
/// <param name="name">Excel 文件的路径。</param>
/// <returns>ExcelPackage 实例。</returns>
public static ExcelPackage LoadExcel(string name)
{
return new ExcelPackage(name);
}
/// <summary>
/// 获取指定工作表中指定行列位置的单元格值。
/// </summary>
/// <param name="sheet">Excel 工作表。</param>
/// <param name="row">行索引。</param>
/// <param name="column">列索引。</param>
/// <returns>单元格值。</returns>
public static string GetCellValue(this ExcelWorksheet sheet, int row, int column)
{
ExcelRange cell = sheet.Cells[row, column];
try
{
if (cell.Value == null)
{
return "";
}
string s = cell.GetValue<string>();
return s.Trim();
}
catch (Exception e)
{
throw new Exception($"Rows {row} Columns {column} Content {cell.Text} {e}");
}
}
}

View File

@@ -0,0 +1,28 @@
namespace Fantasy.Tools.ConfigTable;
/// <summary>
/// Excel表格类用于存储表格的名称和列信息。
/// </summary>
public sealed class ExcelTable
{
/// <summary>
/// 表格的名称。
/// </summary>
public readonly string Name;
/// <summary>
/// 客户端列信息,使用排序字典存储列名和列索引列表。
/// </summary>
public readonly SortedDictionary<string, List<int>> ClientColInfos = new();
/// <summary>
/// 服务器端列信息,使用排序字典存储列名和列索引列表。
/// </summary>
public readonly SortedDictionary<string, List<int>> ServerColInfos = new();
/// <summary>
/// 构造函数初始化Excel表格对象并设置表格名称。
/// </summary>
/// <param name="name">表格名称。</param>
public ExcelTable(string name)
{
Name = name;
}
}

View File

@@ -0,0 +1,98 @@
namespace Fantasy.Tools.ConfigTable;
public static class ExcelTemplate
{
public static readonly string Template = """
using System;
using ProtoBuf;
using Fantasy;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.Collections.Concurrent;
using Fantasy.ConfigTable;
using Fantasy.Serialize;
// ReSharper disable CollectionNeverUpdated.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
#pragma warning disable CS0169
#pragma warning disable CS8618
#pragma warning disable CS8625
#pragma warning disable CS8603
namespace (namespace)
{
[ProtoContract]
public sealed partial class (ConfigName)Data : ASerialize, IConfigTable, IProto
{
[ProtoMember(1)]
public List<(ConfigName)> List { get; set; } = new List<(ConfigName)>();
#if FANTASY_NET
[ProtoIgnore]
private readonly ConcurrentDictionary<uint, (ConfigName)> _configs = new ConcurrentDictionary<uint, (ConfigName)>();
#else
[ProtoIgnore]
private readonly Dictionary<uint, (ConfigName)> _configs = new Dictionary<uint, (ConfigName)>();
#endif
private static (ConfigName)Data _instance = null;
public static (ConfigName)Data Instance
{
get { return _instance ??= ConfigTableHelper.Load<(ConfigName)Data>(); }
private set => _instance = value;
}
public (ConfigName) Get(uint id, bool check = true)
{
if (_configs.ContainsKey(id))
{
return _configs[id];
}
if (check)
{
throw new Exception($"(ConfigName) not find {id} Id");
}
return null;
}
public bool TryGet(uint id, out (ConfigName) config)
{
config = null;
if (!_configs.ContainsKey(id))
{
return false;
}
config = _configs[id];
return true;
}
public override void AfterDeserialization()
{
foreach (var config in List)
{
#if FANTASY_NET
_configs.TryAdd(config.Id, config);
#else
_configs.Add(config.Id, config);
#endif
config.AfterDeserialization();
}
EndInit();
}
public override void Dispose()
{
Instance = null;
}
}
[ProtoContract]
public sealed partial class (ConfigName) : ASerialize, IProto
{(Fields)
}
}
""";
}

View File

@@ -0,0 +1,25 @@
using Fantasy.Exporter;
using Fantasy.Helper;
using OfficeOpenXml;
#pragma warning disable CS8601 // Possible null reference assignment.
namespace Fantasy.Tools.ConfigTable;
public sealed class ExcelWorksheets(ExcelExporter excelExporter)
{
public bool TryGetValue(string worksheetName, out ExcelWorksheet excelWorksheet)
{
if (excelExporter.Worksheets.TryGetValue(worksheetName, out excelWorksheet))
{
return true;
}
var computeHash64 = HashCodeHelper.ComputeHash64(worksheetName);
if (!excelExporter.VersionInfo.WorksheetNames.Contains(computeHash64))
{
Log.Info($"{worksheetName} is not exist!");
}
return false;
}
}

View File

@@ -0,0 +1,17 @@
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
namespace Fantasy.Tools.ConfigTable;
/// <summary>
/// 导出信息类,用于存储导出操作的名称和文件信息。
/// </summary>
public class ExportInfo
{
/// <summary>
/// 导出操作的名称。
/// </summary>
public string Name;
/// <summary>
/// 导出操作生成的文件信息。
/// </summary>
public FileInfo FileInfo;
}

View File

@@ -0,0 +1,148 @@
using Fantasy.Exporter;
using Fantasy.Helper;
// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
namespace Fantasy.Tools.ConfigTable;
/// <summary>
/// 自定义导出接口
/// </summary>
public interface ICustomExport
{
/// <summary>
/// 执行导出操作
/// </summary>
void Run();
/// <summary>
/// 内部操作用于初始化、不明白原理不要修改这里和调用这个方法
/// </summary>
/// <param name="excelExporter"></param>
/// <param name="worksheets"></param>
void Init(ExcelExporter excelExporter, ExcelWorksheets worksheets);
}
/// <summary>
/// 抽象自定义导出基类
/// </summary>
public abstract class ACustomExport : ICustomExport
{
protected ExcelExporter ExcelExporter;
protected ExcelWorksheets Worksheets;
/// <summary>
/// 自定义导出类型枚举:客户端、服务器
/// </summary>
protected enum CustomExportType
{
/// <summary>
/// 客户端
/// </summary>
Client,
/// <summary>
/// 服务器
/// </summary>
Server
}
/// <summary>
/// 内部操作用于初始化、不明白原理不要修改这里
/// </summary>
/// <param name="excelExporter"></param>
/// <param name="worksheets"></param>
public void Init(ExcelExporter excelExporter, ExcelWorksheets worksheets)
{
ExcelExporter = excelExporter;
Worksheets = worksheets;
}
/// <summary>
/// 执行导出操作的抽象方法
/// </summary>
public abstract void Run();
/// <summary>
/// 写入文件内容到指定位置
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="fileContent">文件内容</param>
/// <param name="filePath">相对的导出的目录</param>
/// <param name="customExportType">自定义导出类型</param>
protected void Write(string fileName, string fileContent, string filePath, CustomExportType customExportType)
{
if (filePath == null)
{
Log.Error($" {nameof(filePath)} is null");
return;
}
filePath = FileHelper.GetFullPath(filePath);
if (!Directory.Exists(filePath))
{
FileHelper.CreateDirectory(filePath);
}
var combine = Path.Combine(filePath, fileName);
File.WriteAllText(combine, fileContent);
switch (customExportType)
{
case CustomExportType.Client:
{
Log.Info($"导出客户端自定义文件:{filePath}/{fileName}");
return;
}
case CustomExportType.Server:
{
Log.Info($"导出服务器自定义文件:{filePath}/{fileName}");
return;
}
}
}
/// <summary>
/// 写入文件内容到指定位置
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="fileContent">文件内容</param>
/// <param name="customExportType">自定义导出类型</param>
protected void Write(string fileName, string fileContent, CustomExportType customExportType)
{
switch (customExportType)
{
case CustomExportType.Client:
{
if (string.IsNullOrEmpty(ExcelExporter.ClientCustomExportDirectory))
{
return;
}
if (!Directory.Exists(ExcelExporter.ClientCustomExportDirectory))
{
Directory.CreateDirectory(ExcelExporter.ClientCustomExportDirectory);
}
File.WriteAllText($"{ExcelExporter.ClientCustomExportDirectory}/{fileName}", fileContent);
Log.Info($"导出客户端自定义文件:{ExcelExporter.ClientCustomExportDirectory}/{fileName}");
return;
}
case CustomExportType.Server:
{
if (string.IsNullOrEmpty(ExcelExporter.ServerCustomExportDirectory))
{
return;
}
if (!Directory.Exists(ExcelExporter.ServerCustomExportDirectory))
{
Directory.CreateDirectory(ExcelExporter.ServerCustomExportDirectory);
}
File.WriteAllText($"{ExcelExporter.ServerCustomExportDirectory}/{fileName}", fileContent);
Log.Info($"导出服务器自定义文件:{ExcelExporter.ServerCustomExportDirectory}/{fileName}");
return;
}
}
}
}

View File

@@ -0,0 +1,7 @@
namespace Fantasy.Tools.ConfigTable;
public class VersionInfo
{
public SortedSet<long> WorksheetNames = [];
public SortedDictionary<long, long> Tables = new();
}

View File

@@ -0,0 +1,21 @@
using CommandLine;
using Fantasy.Tools.ConfigTable;
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
namespace Fantasy.Tools;
public class ExporterAges
{
public static ExporterAges Instance;
/// <summary>
/// 导出目标平台枚举,用于标识导出到哪个平台
/// </summary>
[Option('p',"ExportPlatform", Required = false, Default = ExportPlatform.None, HelpText = "Export target platform:\n/// Client target platform \nClient = 1\n/// Server target platform\nServer = 2\n/// Client and Server target platform\nAll = 3")]
public ExportPlatform ExportPlatform { get; set; }
/// <summary>
/// 导出类型
/// </summary>
[Option('e',"ExportType", Required = false, Default = ExportType.None, HelpText = "Export Type:\n/// Incremental export of all data in Excel format.\nAllExcelIncrement = 1\n/// Export all data to Excel format.\nAllExcel = 2")]
public ExportType ExportType { get; set; }
}

View File

@@ -0,0 +1,44 @@
{
"Export": {
"ExcelProgramPath": {
"Value": "../../../Examples/Config/Excel/",
"Comment": "Excel文件夹的根目录"
},
"ExcelVersionFile": {
"Value": "../../../Examples/Config/Excel/Version.txt",
"Comment": "Excel的Version文件位置、这个文件用于记录每次导出对比是否需要再次导出的文件"
},
"ExcelServerFileDirectory": {
"Value": "../../../Examples/Server/Entity/Generate/ConfigTable/Entity/",
"Comment": "Excel生成的代码文件、在服务端文件夹位置"
},
"ExcelClientFileDirectory": {
"Value": "../../../Examples/Client/Unity/Assets/Scripts/Hotfix/Generate/ConfigTable/Entity/",
"Comment": "Excel生成的代码文件、在客户端文件夹位置"
},
"ExcelServerBinaryDirectory": {
"Value": "../../../Examples/Config/Binary/",
"Comment": "Excel生成服务器二进制数据文件夹位置"
},
"ExcelClientBinaryDirectory": {
"Value": "../../../Examples/Client/Unity/Assets/Bundles/Config/",
"Comment": "Excel生成在客户端的二进制数据文件夹位置"
},
"ExcelServerJsonDirectory": {
"Value": "../../../Examples/Config/Json/Server/",
"Comment": "Excel生成在服务端的Json数据文件夹位置"
},
"ExcelClientJsonDirectory": {
"Value": "../../../Examples/Config/Json/Client/",
"Comment": "Excel生成在客户端的Json数据文件夹位置"
},
"ServerCustomExportDirectory": {
"Value": "../../../Examples/Server/Entity/Generate/CustomExport/",
"Comment": "Excel在服务端生成自定义代码的文件夹位置"
},
"ClientCustomExportDirectory": {
"Value": "../../../Examples/Client/Unity/Assets/Scripts/Hotfix/Generate/CustomExport",
"Comment": "Excel在客户端端生成自定义代码的文件夹位置"
}
}
}

View File

@@ -0,0 +1,43 @@
using Fantasy.Helper;
using Microsoft.Extensions.Configuration;
#pragma warning disable CS8604 // Possible null reference argument.
namespace Fantasy.Tools.ConfigTable;
public class ExporterSettingsHelper
{
public static string? ExcelProgramPath { get; private set; }
public static string? ExcelVersionFile { get; private set; }
public static string? ExcelServerFileDirectory { get; private set; }
public static string? ExcelClientFileDirectory { get; private set; }
public static string? ExcelServerBinaryDirectory { get; private set; }
public static string? ExcelClientBinaryDirectory { get; private set; }
public static string? ExcelServerJsonDirectory { get; private set; }
public static string? ExcelClientJsonDirectory { get; private set; }
public static string? ServerCustomExportDirectory { get; private set; }
public static string? ClientCustomExportDirectory { get; private set; }
public static void Initialize()
{
const string settingsName = "ExporterSettings.json";
var currentDirectory = Directory.GetCurrentDirectory();
if (!File.Exists(Path.Combine(currentDirectory, settingsName)))
{
throw new FileNotFoundException($"not found {settingsName} in OutputDirectory");
}
var root = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(settingsName).Build();
ExcelProgramPath = FileHelper.GetFullPath(root["Export:ExcelProgramPath:Value"]);
ExcelVersionFile = FileHelper.GetFullPath(root["Export:ExcelVersionFile:Value"]);
ExcelServerFileDirectory = FileHelper.GetFullPath(root["Export:ExcelServerFileDirectory:Value"]);
ExcelClientFileDirectory = FileHelper.GetFullPath(root["Export:ExcelClientFileDirectory:Value"]);
ExcelServerBinaryDirectory = FileHelper.GetFullPath(root["Export:ExcelServerBinaryDirectory:Value"]);
ExcelClientBinaryDirectory = FileHelper.GetFullPath(root["Export:ExcelClientBinaryDirectory:Value"]);
ExcelServerJsonDirectory = FileHelper.GetFullPath(root["Export:ExcelServerJsonDirectory:Value"]);
ExcelClientJsonDirectory = FileHelper.GetFullPath(root["Export:ExcelClientJsonDirectory:Value"]);
ServerCustomExportDirectory = FileHelper.GetFullPath(root["Export:ServerCustomExportDirectory:Value"]);
ClientCustomExportDirectory = FileHelper.GetFullPath(root["Export:ClientCustomExportDirectory:Value"]);
}
}

View File

@@ -0,0 +1,118 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>default</LangVersion>
<TargetFrameworks>net8.0;net9.0</TargetFrameworks>
</PropertyGroup>
<PropertyGroup>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<DefineConstants>TRACE;FANTASY_EXPORTER</DefineConstants>
<OutputPath>../../Exporter/ConfigTable/</OutputPath>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<DefineConstants>TRACE;FANTASY_EXPORTER</DefineConstants>
<OutputPath>../../Exporter/ConfigTable/</OutputPath>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CommandLineParser" Version="2.9.1" />
<PackageReference Include="EPPlus" Version="8.0.5" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.14.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.6" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="protobuf-net" Version="3.2.52" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\..\Fantasy.Net\Fantasy.Net\Runtime\Core\Pool\Normal\Pool.cs">
<Link>Core\Base\Pool.cs</Link>
</Compile>
<Compile Include="..\..\..\Fantasy.Packages\Fantasy.ConfigTable\Net\Dictionary\IntDictionaryConfig.cs">
<Link>Core\Dictionary\IntDictionaryConfig.cs</Link>
</Compile>
<Compile Include="..\..\..\Fantasy.Packages\Fantasy.ConfigTable\Net\Dictionary\StringDictionaryConfig.cs">
<Link>Core\Dictionary\StringDictionaryConfig.cs</Link>
</Compile>
<Compile Include="..\..\..\Fantasy.Packages\Fantasy.ConfigTable\Net\Interface\IConfigTable.cs">
<Link>Core\Interface\IConfigTable.cs</Link>
</Compile>
<Compile Include="..\..\..\Fantasy.Net\Fantasy.Net\Runtime\Core\Serialize\ProtoBufPackHelper\IProto.cs">
<Link>Core\Serialize\ProtoBufPackHelper\IProto.cs</Link>
</Compile>
<Compile Include="..\..\..\Fantasy.Net\Fantasy.Net\Runtime\Core\Helper\TimeHelper.cs">
<Link>Excel\Base\TimeHelper.cs</Link>
</Compile>
<Compile Include="..\..\..\Fantasy.Net\Fantasy.Net\Runtime\Core\Pool\Interface\IPool.cs">
<Link>Excel\Base\IPool.cs</Link>
</Compile>
<Compile Include="..\..\..\Fantasy.Net\Fantasy.Net\Runtime\Core\Assembly\AssemblyInfo.cs">
<Link>Excel\Base\AssemblyInfo.cs</Link>
</Compile>
<Compile Include="..\..\..\Fantasy.Net\Fantasy.Net\Runtime\Core\DataStructure\Collection\OneToManyListPool.cs">
<Link>Excel\Base\OneToManyList.cs</Link>
</Compile>
<Compile Include="..\Fantasy.Tools.NetworkProtocol\Core\Base\ConsoleLog.cs">
<Link>Core\ConsoleLog.cs</Link>
</Compile>
<Compile Include="..\Fantasy.Tools.NetworkProtocol\Core\Base\ExportPlatform.cs">
<Link>Core\ExportPlatform.cs</Link>
</Compile>
<Compile Include="..\..\..\Fantasy.Net\Fantasy.Net\Runtime\Core\Helper\FileHelper.cs">
<Link>Core\FileHelper.cs</Link>
</Compile>
<Compile Include="..\..\..\Fantasy.Net\Fantasy.Net\Runtime\Core\Helper\HashCodeHelper.cs">
<Link>Core\HashCodeHelper.cs</Link>
</Compile>
<Compile Include="..\..\..\Fantasy.Net\Fantasy.Net\Runtime\Core\Helper\JsonHelper.cs">
<Link>Core\JsonHelper.cs</Link>
</Compile>
<Compile Include="..\..\..\Fantasy.Net\Fantasy.Net\Runtime\Core\Serialize\BsonPack\BsonPackHelperNet.cs">
<Link>Core\Serialize\BsonPack\BsonPackHelperNet.cs</Link>
</Compile>
<Compile Include="..\..\..\Fantasy.Net\Fantasy.Net\Runtime\Core\Serialize\BsonPack\StructBsonSerialize.cs">
<Link>Core\Serialize\BsonPack\StructBsonSerialize.cs</Link>
</Compile>
<Compile Include="..\..\..\Fantasy.Net\Fantasy.Net\Runtime\Core\Serialize\BsonPack\SupportInitializeChecker.cs">
<Link>Core\Serialize\BsonPack\SupportInitializeChecker.cs</Link>
</Compile>
<Compile Include="..\..\..\Fantasy.Net\Fantasy.Net\Runtime\Core\Serialize\Interface\ASerialize.cs">
<Link>Core\Serialize\Interface\ASerialize.cs</Link>
</Compile>
<Compile Include="..\..\..\Fantasy.Net\Fantasy.Net\Runtime\Core\Serialize\Interface\ISerialize.cs">
<Link>Core\Serialize\Interface\ISerialize.cs</Link>
</Compile>
<Compile Include="..\..\..\Fantasy.Net\Fantasy.Net\Runtime\Core\Serialize\SerializerManager.cs">
<Link>Core\Serialize\SerializerManager.cs</Link>
</Compile>
<Compile Include="..\..\..\Fantasy.Net\Fantasy.Net\Runtime\Core\Serialize\ProtoBufPackHelper\ProtoBufPackHelperNet.cs">
<Link>Core\Serialize\ProtoBufPackHelper\ProtoBufPackHelperNet.cs</Link>
</Compile>
<Compile Include="..\..\..\Fantasy.Net\Fantasy.Net\Runtime\Core\Serialize\MemoryStreamBuffer.cs">
<Link>Excel\Base\MemoryStreamBuffer.cs</Link>
</Compile>
</ItemGroup>
<ItemGroup>
<None Update="ExporterSettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Run.bat">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Run.sh">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,67 @@
using System.Text;
using CommandLine;
using Fantasy.Exporter;
using Fantasy.Tools;
using Fantasy.Tools.ConfigTable;
try
{
Parser.Default.ParseArguments<ExporterAges>(Environment.GetCommandLineArgs())
.WithNotParsed(error => throw new Exception("Command line format error!"))
.WithParsed(ages => ExporterAges.Instance = ages);
// 初始化配置
ExporterSettingsHelper.Initialize();
// 加载配置
Console.OutputEncoding = Encoding.UTF8;
// 判断启动参数,如果没有选择目标平台就让用户选择
if (ExporterAges.Instance.ExportPlatform == ExportPlatform.None)
{
Log.Info("请输入你想要导出的目标平台:");
Log.Info("1:Client客户端");
Log.Info("2:Server服务器");
Log.Info("3:All客户端和服务器");
var inputKeyChar = Console.ReadKey().KeyChar;
if (!int.TryParse(inputKeyChar.ToString(), out var exportPlatformKey) || exportPlatformKey is < 1 or >= (int)ExportPlatform.All)
{
Console.WriteLine("");
Log.Error("无法识别的导出类型请,输入正确导出的目标平台。");
return;
}
ExporterAges.Instance.ExportPlatform = (ExportPlatform)exportPlatformKey;
}
var selectExportType = ExporterAges.Instance.ExportType;
if (selectExportType == ExportType.None)
{
// 检查启动参数
Log.Info("请输入你想要做的操作:");
Log.Info("1:所有增量导出Excel包含常量枚举");
Log.Info("2:所有全量导出Excel包含常量枚举");
// 获取用户输入
var keyChar = Console.ReadKey().KeyChar;
// 判断用户输入
if (!int.TryParse(keyChar.ToString(), out var key) || key is < 1 or >= (int)ExportType.Max)
{
Console.WriteLine("");
Log.Error("无法识别的导出类型请,输入正确的操作类型。");
return;
}
selectExportType = (ExportType)key;
}
Log.Info($"selectExportType:{selectExportType} ExportPlatform:{ExporterAges.Instance.ExportPlatform}");
// 转换用户输入
Log.Info("");
new ExcelExporter(selectExportType).Run();
}
catch (Exception e)
{
Log.Error(e);
}
finally
{
Log.Info("按任意键退出程序");
Console.ReadKey();
Environment.Exit(0);
}

View File

@@ -0,0 +1,10 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"Fantasy.Tools.ConfigTable": {
"commandName": "Project",
"environmentVariables": {},
"commandLineArgs": "--ExportPlatform 3"
}
}
}

View File

@@ -0,0 +1,33 @@
@echo off
echo Please select an option:
echo 1. Client Increment
echo 2. Client all
echo 3. Server Increment
echo 4. Server all
echo 5. Client and Server Increment
echo 6. Client and Server all
set /p choice=Please select an option:
if "%choice%"=="1" (
echo Client Increment
dotnet Fantasy.Tools.ConfigTable.dll --p 1 --e 1
) else if "%choice%"=="2" (
echo Client all
dotnet Fantasy.Tools.ConfigTable.dll --p 1 --e 2
) else if "%choice%"=="3" (
echo Server Increment
dotnet Fantasy.Tools.ConfigTable.dll --p 2 --e 1
) else if "%choice%"=="4" (
echo Server all
dotnet Fantasy.Tools.ConfigTable.dll --p 2 --e 2
) else if "%choice%"=="5" (
echo Client and Server Increment
dotnet Fantasy.Tools.ConfigTable.dll --p 3 --e 1
) else if "%choice%"=="6" (
echo Client and Server all
dotnet Fantasy.Tools.ConfigTable.dll --p 3 --e 2
) else (
echo Invalid option
)

View File

@@ -0,0 +1,34 @@
#!/bin/bash
echo "1. Client Increment"
echo "2. Client all"
echo "3. Server Increment"
echo "4. Server all"
echo "5. Client and Server Increment"
echo "6. Client and Server all"
read -n 1 -p "Please select an option:" choice
echo ""
case $choice in
1)
dotnet Fantasy.Tools.ConfigTable.dll --p 1 --e 1
;;
2)
dotnet Fantasy.Tools.ConfigTable.dll --p 1 --e 2
;;
3)
dotnet Fantasy.Tools.ConfigTable.dll --p 2 --e 1
;;
4)
dotnet Fantasy.Tools.ConfigTable.dll --p 2 --e 2
;;
5)
dotnet Fantasy.Tools.ConfigTable.dll --p 3 --e 1
;;
6)
dotnet Fantasy.Tools.ConfigTable.dll --p 3 --e 2
;;
*)
echo "Invalid option"
;;
esac