HotPatchAssemblySelection.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Text;
  5. using Newtonsoft.Json.Linq;
  6. using UnityEditor;
  7. using UnityEditorInternal;
  8. public static class HotPatchAssemblySelection
  9. {
  10. public static Action<AssemblyDefinitionAsset> ApplyHybridCLRSettings;
  11. static readonly string[] RequiredReferences = { "AppRuntimes.Base", "Unity.Advertisement.IosSupport" };
  12. public static AssemblyDefinitionAsset Find(string name)
  13. {
  14. if (string.IsNullOrWhiteSpace(name)) return null;
  15. var paths = AssetDatabase.FindAssets("t:AssemblyDefinitionAsset", new[] { "Assets" })
  16. .Select(AssetDatabase.GUIDToAssetPath)
  17. .Where(p => (string)JObject.Parse(File.ReadAllText(p))["name"] == name).ToArray();
  18. return paths.Length == 1 ? AssetDatabase.LoadAssetAtPath<AssemblyDefinitionAsset>(paths[0]) : null;
  19. }
  20. public static string Validate(AssemblyDefinitionAsset assembly)
  21. {
  22. var path = AssetDatabase.GetAssetPath(assembly);
  23. if (assembly == null || !path.StartsWith("Assets/", StringComparison.Ordinal) || !path.EndsWith(".asmdef", StringComparison.Ordinal))
  24. throw new InvalidOperationException("请选择 Assets 中的游戏运行时 asmdef。");
  25. var definition = JObject.Parse(File.ReadAllText(path));
  26. var name = (string)definition["name"];
  27. if (string.IsNullOrWhiteSpace(name) || name.IndexOfAny(new[] { '/', '\\', ':', ',' }) >= 0 || name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
  28. throw new InvalidOperationException("热补丁程序集名称不正确。");
  29. var platforms = definition["includePlatforms"] as JArray;
  30. if (platforms != null && platforms.Count > 0 && platforms.All(p => (string)p == "Editor"))
  31. throw new InvalidOperationException("不能选择 Editor 专用程序集。");
  32. if (name == "AppRuntimes" || name == "AppRuntimes.Base" || name == "HotPatch.Runtime" ||
  33. name == "AppRuntimes.Sources.Editor" || ((JArray)definition["references"] ?? new JArray()).Values<string>().Any(IsLoaderReference))
  34. throw new InvalidOperationException("宿主或热补丁加载器程序集不能作为热更目标。");
  35. return name;
  36. }
  37. static bool IsLoaderReference(string reference)
  38. {
  39. return ResolveReferenceName(reference) == "HotPatch.Runtime";
  40. }
  41. static string ResolveReferenceName(string reference)
  42. {
  43. if (reference != null && reference.StartsWith("GUID:", StringComparison.Ordinal))
  44. {
  45. var path = AssetDatabase.GUIDToAssetPath(reference.Substring(5));
  46. if (File.Exists(path)) reference = (string)JObject.Parse(File.ReadAllText(path))["name"];
  47. }
  48. return reference;
  49. }
  50. public static bool HasRequiredReferences(AssemblyDefinitionAsset assembly)
  51. {
  52. if (assembly == null) return false;
  53. var definition = JObject.Parse(File.ReadAllText(AssetDatabase.GetAssetPath(assembly)));
  54. var references = ((JArray)definition["references"] ?? new JArray()).Values<string>().Select(ResolveReferenceName).ToArray();
  55. return RequiredReferences.All(references.Contains);
  56. }
  57. public static void EnsureRequiredReferences(AssemblyDefinitionAsset assembly)
  58. {
  59. Validate(assembly);
  60. var path = AssetDatabase.GetAssetPath(assembly);
  61. var definition = JObject.Parse(File.ReadAllText(path));
  62. var references = (JArray)definition["references"] ?? new JArray();
  63. var names = references.Values<string>().Select(ResolveReferenceName).ToArray();
  64. var missing = RequiredReferences.Where(name => !names.Contains(name)).ToArray();
  65. if (missing.Length == 0) return;
  66. bool useGuids = references.Values<string>().Any(reference => reference != null && reference.StartsWith("GUID:", StringComparison.Ordinal));
  67. foreach (var name in missing)
  68. {
  69. var reference = name;
  70. if (useGuids)
  71. {
  72. var dependency = UnityEditor.Compilation.CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(name);
  73. var guid = string.IsNullOrEmpty(dependency) ? "" : AssetDatabase.AssetPathToGUID(dependency);
  74. if (string.IsNullOrEmpty(guid)) throw new InvalidOperationException("找不到必需程序集:" + name + ",请等待依赖包导入完成。");
  75. reference = "GUID:" + guid;
  76. }
  77. references.Add(reference);
  78. }
  79. definition["references"] = references;
  80. File.WriteAllText(path, definition.ToString() + "\n", new UTF8Encoding(false));
  81. AssetDatabase.ImportAsset(path);
  82. if (!HasRequiredReferences(assembly)) throw new InvalidOperationException("程序集引用补全失败,请检查 asmdef 后重新 Save。");
  83. }
  84. public static string BuildBlockReason(AppSettings settings, AssemblyDefinitionAsset assembly, string sceneName)
  85. {
  86. if (settings == null || assembly == null || string.IsNullOrWhiteSpace(sceneName))
  87. return "请设置 Hot Patch Assembly、Game Scene Name 并点击 Save。";
  88. try
  89. {
  90. var name = Validate(assembly);
  91. if (!HasRequiredReferences(assembly))
  92. return "程序集缺少 AppRuntimes.Base 或 Unity.Advertisement.IosSupport 引用,请点击 Save 自动补全。";
  93. if (settings.HotPatchAssemblyName != name || string.IsNullOrWhiteSpace(settings.GameSceneName) || settings.GameSceneName.Trim() != sceneName.Trim())
  94. return "程序集或场景设置尚未保存,请点击 Save。";
  95. if (ApplyHybridCLRSettings == null) return "请等待 HybridCLR 安装和编译完成。";
  96. return null;
  97. }
  98. catch (Exception exception) { return exception.Message; }
  99. }
  100. public static string BuildBlockReason(AppSettings settings)
  101. {
  102. if (settings == null) return "请先配置 AppSettings 并点击 Save。";
  103. try { return BuildBlockReason(settings, Find(settings.HotPatchAssemblyName), settings.GameSceneName); }
  104. catch (Exception exception) { return exception.Message; }
  105. }
  106. public static void Save(AppSettings settings, AssemblyDefinitionAsset assembly)
  107. {
  108. if (settings == null) throw new ArgumentNullException(nameof(settings));
  109. var name = assembly != null ? Validate(assembly) : string.Empty;
  110. if (assembly != null)
  111. {
  112. EnsureRequiredReferences(assembly);
  113. if (ApplyHybridCLRSettings == null)
  114. throw new InvalidOperationException("HybridCLR 编辑器集成未就绪,请安装 HybridCLR 并等待编译完成。");
  115. }
  116. ApplyHybridCLRSettings?.Invoke(assembly);
  117. Undo.RecordObject(settings, "Select hot-patch assembly");
  118. settings.HotPatchAssemblyName = name;
  119. EditorUtility.SetDirty(settings);
  120. }
  121. }