HotPatchSourceSync.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. using Newtonsoft.Json.Linq;
  8. using UnityEditor;
  9. using UnityEditor.Compilation;
  10. using UnityEngine;
  11. public static class HotPatchSourceSync
  12. {
  13. public static string AssemblyName => AppSettings.RequireHotPatchAssemblyName();
  14. public const string Begin = "#if UNITY_EDITOR";
  15. public const string End = "#endif";
  16. const string ManifestPath = "ProjectSettings/HotPatchSources.json";
  17. public static void SyncMenu()
  18. {
  19. try { Synchronize(); Debug.Log("[热补丁] 源码同步完成,等待 Unity 编译。"); }
  20. catch (Exception e) { Debug.LogException(e); }
  21. }
  22. public static string FindAssemblyPath()
  23. {
  24. var assembly = HotPatchAssemblySelection.Find(AssemblyName);
  25. HotPatchAssemblySelection.Validate(assembly);
  26. return AssetDatabase.GetAssetPath(assembly);
  27. }
  28. public static string RemoveEditorEnvelope(string source)
  29. {
  30. var text = source.TrimStart('\uFEFF').Replace("\r\n", "\n").Trim();
  31. if (!text.StartsWith(Begin + "\n", StringComparison.Ordinal) || !text.EndsWith("\n" + End, StringComparison.Ordinal))
  32. throw new InvalidDataException("Sources 脚本缺少热补丁最外层 UNITY_EDITOR 包装。");
  33. var body = text.Substring(Begin.Length + 1, text.Length - Begin.Length - End.Length - 2);
  34. int depth = 0;
  35. foreach (var line in body.Split('\n'))
  36. {
  37. var directive = line.TrimStart();
  38. if (directive.StartsWith("#if ", StringComparison.Ordinal)) depth++;
  39. else if (directive.StartsWith("#endif", StringComparison.Ordinal))
  40. { if (--depth < 0) throw new InvalidDataException("Sources 条件编译嵌套不正确。"); }
  41. }
  42. if (depth != 0) throw new InvalidDataException("Sources 条件编译未闭合。");
  43. return body + "\n";
  44. }
  45. public static string PackageRoot => UnityEditor.PackageManager.PackageInfo.FindForAssembly(typeof(AppSettings).Assembly)?.resolvedPath
  46. ?? throw new InvalidOperationException("找不到 AppRuntimes 包。");
  47. public static bool Synchronize(bool refresh = true)
  48. {
  49. if (EditorApplication.isPlayingOrWillChangePlaymode) throw new InvalidOperationException("请先退出 Play Mode。");
  50. var asmPath = FindAssemblyPath();
  51. var root = (Path.GetDirectoryName(asmPath) + "/HotPatch").Replace('\\', '/');
  52. var sourceRoot = Path.Combine(PackageRoot, "Runtime/Sources");
  53. var desired = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  54. foreach (var source in Directory.GetFiles(sourceRoot, "*.cs", SearchOption.AllDirectories))
  55. {
  56. var relative = source.Substring(sourceRoot.Length + 1).Replace('\\', '/');
  57. desired.Add(root + "/" + relative, RemoveEditorEnvelope(File.ReadAllText(source)));
  58. }
  59. if (desired.Count == 0) throw new InvalidOperationException("Sources 没有可复制的脚本。");
  60. var previous = File.Exists(ManifestPath) ? JObject.Parse(File.ReadAllText(ManifestPath)) : new JObject();
  61. var oldRoot = (string)previous["root"] ?? root;
  62. RequireChild("Assets", oldRoot);
  63. if (!oldRoot.EndsWith("/HotPatch", StringComparison.Ordinal) && !oldRoot.EndsWith("/Generated/HotPatch/Sources", StringComparison.Ordinal))
  64. throw new InvalidDataException("旧生成目录不是热补丁目录。");
  65. var owned = previous["files"] as JObject ?? new JObject();
  66. foreach (var item in owned.Properties())
  67. {
  68. RequireChild(oldRoot, item.Name);
  69. if (!item.Name.EndsWith(".cs", StringComparison.Ordinal)) throw new InvalidDataException("生成记录包含非脚本路径。");
  70. if (File.Exists(item.Name) && Hash(File.ReadAllText(item.Name)) != (string)item.Value)
  71. throw new InvalidOperationException("生成文件被手工修改,请先合并到 Sources: " + item.Name);
  72. }
  73. foreach (var item in desired)
  74. if (File.Exists(item.Key) && owned[item.Key] == null && File.ReadAllText(item.Key) != item.Value)
  75. throw new InvalidOperationException("热补丁目标文件冲突: " + item.Key);
  76. var targetFolder = Path.GetDirectoryName(asmPath);
  77. var names = new[] { "AppRuntimes", "ClientCrypto", "Https", "FBHandler", "DictionaryExtensions", "NativeAppInfo", "DeviceTimeZone" };
  78. foreach (var file in Directory.GetFiles(targetFolder, "*.cs", SearchOption.AllDirectories))
  79. {
  80. if (owned[file.Replace('\\', '/')] != null) continue;
  81. if (Path.GetFullPath(file).StartsWith(Path.GetFullPath(root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) continue;
  82. if (CompilationPipeline.GetAssemblyNameFromScriptPath(file.Replace('\\', '/')) != AssemblyName) continue;
  83. var text = File.ReadAllText(file);
  84. if (names.Any(n => System.Text.RegularExpressions.Regex.IsMatch(text, @"\bclass\s+" + n + @"\b")))
  85. throw new InvalidOperationException("发现重复业务类型,请移除旧副本: " + file);
  86. }
  87. var asm = JObject.Parse(File.ReadAllText(asmPath));
  88. var references = ((JArray)asm["references"] ?? new JArray()).Values<string>().Where(r => !IsOldRuntimeReference(r)).ToList();
  89. foreach (var reference in new[] { "AppRuntimes.Base", "UniTask", "UnityEngine.UI", "UniWebView-CSharp", "Unity.Advertisement.IosSupport" })
  90. if (!references.Contains(reference)) references.Add(reference);
  91. asm["references"] = new JArray(references); asm["autoReferenced"] = false;
  92. desired[asmPath] = asm.ToString() + "\n";
  93. var generatedManifest = new JObject();
  94. foreach (var item in desired.Where(p => p.Key != asmPath)) generatedManifest[item.Key] = Hash(item.Value);
  95. if (oldRoot != root)
  96. {
  97. foreach (var item in owned.Properties())
  98. {
  99. var destination = root + item.Name.Substring(oldRoot.Length);
  100. if (!desired.ContainsKey(destination) || !File.Exists(item.Name + ".meta")) continue;
  101. if (File.Exists(destination + ".meta")) throw new InvalidOperationException("迁移目标已有 GUID,请先处理冲突: " + destination);
  102. desired[destination + ".meta"] = File.ReadAllText(item.Name + ".meta");
  103. }
  104. }
  105. desired[ManifestPath] = new JObject { ["root"] = root, ["assemblyName"] = AssemblyName, ["files"] = generatedManifest }.ToString() + "\n";
  106. var removed = owned.Properties().Select(p => p.Name).Where(p => !desired.ContainsKey(p)).ToArray();
  107. var changes = desired.Where(p => !File.Exists(p.Key) || File.ReadAllText(p.Key) != p.Value).ToArray();
  108. if (changes.Length == 0 && removed.Length == 0) return false;
  109. var touched = changes.Select(p => p.Key).Concat(removed.SelectMany(p => new[] { p, p + ".meta" })).Distinct().ToArray();
  110. var backups = touched.ToDictionary(p => p, p => File.Exists(p) ? File.ReadAllBytes(p) : null);
  111. AssetDatabase.StartAssetEditing();
  112. try
  113. {
  114. foreach (var change in changes)
  115. { Directory.CreateDirectory(Path.GetDirectoryName(change.Key)); File.WriteAllText(change.Key, change.Value, new UTF8Encoding(false)); }
  116. foreach (var path in removed)
  117. { if (File.Exists(path)) File.Delete(path); if (File.Exists(path + ".meta")) File.Delete(path + ".meta"); }
  118. }
  119. catch
  120. {
  121. foreach (var backup in backups)
  122. if (backup.Value == null) { if (File.Exists(backup.Key)) File.Delete(backup.Key); }
  123. else File.WriteAllBytes(backup.Key, backup.Value);
  124. throw;
  125. }
  126. finally { AssetDatabase.StopAssetEditing(); }
  127. if (refresh) AssetDatabase.Refresh();
  128. return true;
  129. }
  130. public static void VerifySynchronized()
  131. {
  132. var path = FindAssemblyPath();
  133. var root = Path.GetDirectoryName(path) + "/HotPatch";
  134. var sources = Path.Combine(PackageRoot, "Runtime/Sources");
  135. var expected = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
  136. foreach (var source in Directory.GetFiles(sources, "*.cs", SearchOption.AllDirectories))
  137. {
  138. var output = Path.Combine(root, source.Substring(sources.Length + 1));
  139. expected.Add(Path.GetFullPath(output));
  140. if (!File.Exists(output) || File.ReadAllText(output) != RemoveEditorEnvelope(File.ReadAllText(source)))
  141. throw new InvalidOperationException("热补丁源码未同步,请执行 资源构建/一键打包资源。");
  142. }
  143. if (Directory.GetFiles(root, "*.cs", SearchOption.AllDirectories).Any(p => !expected.Contains(Path.GetFullPath(p))))
  144. throw new InvalidOperationException("HotPatch 目录包含过期或未托管脚本,请执行同步并处理冲突。");
  145. }
  146. static bool IsOldRuntimeReference(string value)
  147. {
  148. if (value == "AppRuntimes" || value == "AppRuntimes.Sources.Editor") return true;
  149. if (!value.StartsWith("GUID:", StringComparison.Ordinal)) return false;
  150. var path = AssetDatabase.GUIDToAssetPath(value.Substring(5));
  151. if (!File.Exists(path)) return false;
  152. var name = (string)JObject.Parse(File.ReadAllText(path))["name"];
  153. return name == "AppRuntimes" || name == "AppRuntimes.Sources.Editor";
  154. }
  155. static void RequireChild(string root, string file)
  156. {
  157. if (!Path.GetFullPath(file).StartsWith(Path.GetFullPath(root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
  158. throw new InvalidDataException("生成记录包含目录外路径。");
  159. }
  160. public static string Hash(string text)
  161. {
  162. using var hash = SHA256.Create();
  163. return BitConverter.ToString(hash.ComputeHash(Encoding.UTF8.GetBytes(text))).Replace("-", "").ToLowerInvariant();
  164. }
  165. }