HotPatchResourcePackage.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using UnityEngine;
  7. namespace HotPatch.Editor
  8. {
  9. public static class HotPatchResourcePackage
  10. {
  11. public const string HotManifestFileName = "manifest_hot.json";
  12. public static HotPatchManifest Write(string destination, string assemblyBundle, string sceneBundle, string aotBundle,
  13. IReadOnlyDictionary<string, string> aotFiles, string assemblyName, string sceneName, string scenePath,
  14. string platform, string buildId, bool development, HotPatchManifest original = null)
  15. {
  16. if (Directory.Exists(destination) && Directory.EnumerateFileSystemEntries(destination).Any())
  17. throw new IOException("资源输出目录必须为空: " + destination);
  18. var inputs = new List<KeyValuePair<HotPatchResource, string>>
  19. {
  20. new KeyValuePair<HotPatchResource, string>(Describe(HotPatchResource.AssemblyBundleName(assemblyName), HotPatchResource.AssemblyKind, assemblyBundle), assemblyBundle),
  21. new KeyValuePair<HotPatchResource, string>(Describe(HotPatchResource.SceneBundleName(sceneName), HotPatchResource.SceneKind, sceneBundle), sceneBundle)
  22. };
  23. var manifest = new HotPatchManifest
  24. {
  25. assemblyName = assemblyName, gameSceneName = sceneName, gameScenePath = scenePath,
  26. platform = platform, playerBuildId = buildId, developmentBuild = development,
  27. resources = inputs.Select(p => p.Key).ToArray(),
  28. aotMetadata = aotFiles.OrderBy(p => p.Key, StringComparer.Ordinal)
  29. .Select(p => Describe(p.Key, HotPatchResource.AotKind, p.Value)).ToArray()
  30. };
  31. if (aotBundle != null)
  32. {
  33. manifest.aotBundle = Describe("aot.bundle", HotPatchResource.AotBundleKind, aotBundle);
  34. inputs.Add(new KeyValuePair<HotPatchResource, string>(manifest.aotBundle, aotBundle));
  35. }
  36. else
  37. {
  38. if (original?.aotBundle == null || (original.aotMetadata?.Length ?? 0) == 0)
  39. throw new InvalidDataException("更新资源必须继承原始资源的完整 AOT 清单。");
  40. var copy = HotPatchResourceStore.Parse(JsonUtility.ToJson(original));
  41. copy.Validate(assemblyName, platform, sceneName);
  42. manifest.aotBundles = copy.aotBundles;
  43. manifest.aotMetadata = copy.aotMetadata;
  44. }
  45. manifest.version = HotPatchHash.Of(Encoding.UTF8.GetBytes(scenePath + "\n" + string.Join("\n",
  46. manifest.resources.Select(r => r.kind + ":" + r.name + ":" + r.sha256))));
  47. manifest.Validate(assemblyName, platform, sceneName);
  48. if (original != null) manifest.ValidateAgainst(original);
  49. Directory.CreateDirectory(Path.Combine(destination, "files"));
  50. foreach (var input in inputs)
  51. {
  52. var output = Path.Combine(destination, input.Key.RelativePath);
  53. File.Copy(input.Value, output, true);
  54. if (!HotPatchResourceStore.IsVerified(output, input.Key)) throw new IOException("资源复制期间发生变化: " + input.Value);
  55. }
  56. File.WriteAllText(Path.Combine(destination, HotPatchResourceStore.ManifestFileName), JsonUtility.ToJson(manifest, true), new UTF8Encoding(false));
  57. return manifest;
  58. }
  59. public static void CopyOriginal(string sourceDirectory, string destination)
  60. {
  61. if (Directory.Exists(destination) && Directory.EnumerateFileSystemEntries(destination).Any())
  62. throw new IOException("资源输出目录必须为空: " + destination);
  63. var json = File.ReadAllText(Path.Combine(sourceDirectory, HotPatchResourceStore.ManifestFileName));
  64. var original = HotPatchResourceStore.Parse(json);
  65. original.Validate(original.assemblyName, original.platform, original.gameSceneName);
  66. if (original.aotBundle == null || (original.aotMetadata?.Length ?? 0) == 0)
  67. throw new InvalidDataException("原始资源缺少完整 AOT 清单。");
  68. var resources = original.resources.Concat(new[] { original.aotBundle }).ToArray();
  69. foreach (var resource in resources)
  70. if (!HotPatchResourceStore.IsVerified(RequireChild(sourceDirectory, Path.Combine(sourceDirectory, resource.RelativePath)), resource))
  71. throw new InvalidDataException("原始资源缺失或损坏: " + resource.name);
  72. foreach (var resource in resources)
  73. {
  74. var output = RequireChild(destination, Path.Combine(destination, resource.RelativePath));
  75. Directory.CreateDirectory(Path.GetDirectoryName(output));
  76. File.Copy(Path.Combine(sourceDirectory, resource.RelativePath), output);
  77. if (!HotPatchResourceStore.IsVerified(output, resource)) throw new IOException("原始资源复制失败: " + resource.name);
  78. }
  79. File.WriteAllText(Path.Combine(destination, HotPatchResourceStore.ManifestFileName), json, new UTF8Encoding(false));
  80. }
  81. public static void AppendUpdate(string originalDirectory, string updateDirectory)
  82. {
  83. var original = HotPatchResourceStore.Parse(File.ReadAllText(Path.Combine(originalDirectory, HotPatchResourceStore.ManifestFileName)));
  84. var updateJson = File.ReadAllText(Path.Combine(updateDirectory, HotPatchResourceStore.ManifestFileName));
  85. var update = HotPatchResourceStore.Parse(updateJson);
  86. original.Validate(original.assemblyName, original.platform, original.gameSceneName);
  87. update.ValidateAgainst(original);
  88. if (original.aotBundle == null || update.aotBundle == null ||
  89. (original.aotMetadata?.Length ?? 0) == 0 || update.aotMetadata?.Length != original.aotMetadata.Length)
  90. throw new InvalidDataException("合并资源需要两份完整且一致的 AOT 清单。");
  91. var hotManifest = RequireChild(originalDirectory, Path.Combine(originalDirectory, HotManifestFileName));
  92. if (File.Exists(hotManifest)) throw new IOException("原始资源暂存目录已包含更新清单。");
  93. foreach (var resource in original.resources.Concat(new[] { original.aotBundle }))
  94. if (!HotPatchResourceStore.IsVerified(RequireChild(originalDirectory, Path.Combine(originalDirectory, resource.RelativePath)), resource))
  95. throw new InvalidDataException("原始资源缺失或损坏: " + resource.name);
  96. foreach (var resource in update.resources)
  97. if (!HotPatchResourceStore.IsVerified(RequireChild(updateDirectory, Path.Combine(updateDirectory, resource.RelativePath)), resource))
  98. throw new InvalidDataException("更新资源缺失或损坏: " + resource.name);
  99. foreach (var resource in update.resources)
  100. {
  101. var destination = RequireChild(originalDirectory, Path.Combine(originalDirectory, resource.RelativePath));
  102. if (File.Exists(destination))
  103. {
  104. if (!HotPatchResourceStore.IsVerified(destination, resource)) throw new InvalidDataException("资源哈希路径冲突: " + resource.name);
  105. continue;
  106. }
  107. File.Copy(Path.Combine(updateDirectory, resource.RelativePath), destination);
  108. if (!HotPatchResourceStore.IsVerified(destination, resource)) throw new IOException("更新资源复制失败: " + resource.name);
  109. }
  110. File.WriteAllText(hotManifest, updateJson, new UTF8Encoding(false));
  111. }
  112. public static HotPatchResource Describe(string name, string kind, string source)
  113. {
  114. if (!File.Exists(source)) throw new FileNotFoundException("资源源文件不存在。", source);
  115. return new HotPatchResource { name = name, kind = kind, size = new FileInfo(source).Length, sha256 = HotPatchHash.OfFile(source) };
  116. }
  117. public static void ClearDirectory(string directory, string allowedParent)
  118. {
  119. directory = RequireChild(allowedParent, directory);
  120. if (!Directory.Exists(directory)) return;
  121. RejectLinks(directory);
  122. foreach (var entry in Directory.GetFileSystemEntries(directory))
  123. {
  124. var path = RequireChild(directory, entry);
  125. if (Directory.Exists(path)) Directory.Delete(path, true);
  126. else File.Delete(path);
  127. }
  128. }
  129. public static void DeleteDirectory(string directory, string allowedParent)
  130. {
  131. directory = RequireChild(allowedParent, directory);
  132. ClearDirectory(directory, allowedParent);
  133. if (Directory.Exists(directory)) Directory.Delete(directory);
  134. var meta = RequireChild(allowedParent, directory + ".meta");
  135. if (File.Exists(meta)) File.Delete(meta);
  136. }
  137. public static void ReplaceDirectory(string staging, string destination, string stagingParent, string destinationParent)
  138. {
  139. staging = RequireChild(stagingParent, staging);
  140. destination = RequireChild(destinationParent, destination);
  141. if (!Directory.Exists(staging)) throw new DirectoryNotFoundException(staging);
  142. RejectLinks(staging);
  143. if (Directory.Exists(destination)) RejectLinks(destination);
  144. var backup = RequireChild(stagingParent, Path.Combine(stagingParent, "replaced-" + Guid.NewGuid().ToString("N")));
  145. bool hadOld = Directory.Exists(destination);
  146. if (hadOld) Directory.Move(destination, backup);
  147. try { Directory.Move(staging, destination); }
  148. catch
  149. {
  150. if (hadOld) Directory.Move(backup, destination);
  151. throw;
  152. }
  153. if (hadOld) Directory.Delete(backup, true);
  154. }
  155. public static string RequireChild(string parent, string path)
  156. {
  157. var root = Path.GetFullPath(parent).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
  158. var full = Path.GetFullPath(path);
  159. if (!full.StartsWith(root, StringComparison.OrdinalIgnoreCase)) throw new IOException("资源路径超出指定目录: " + full);
  160. for (var ancestor = new DirectoryInfo(Path.GetDirectoryName(full)); ancestor != null; ancestor = ancestor.Parent)
  161. if (ancestor.Exists && (ancestor.Attributes & FileAttributes.ReparsePoint) != 0)
  162. throw new IOException("资源路径包含符号链接目录: " + ancestor.FullName);
  163. return full;
  164. }
  165. static void RejectLinks(string directory)
  166. {
  167. if ((File.GetAttributes(directory) & FileAttributes.ReparsePoint) != 0)
  168. throw new IOException("资源构建目录不能是符号链接: " + directory);
  169. foreach (var child in Directory.GetFileSystemEntries(directory))
  170. {
  171. if ((File.GetAttributes(child) & FileAttributes.ReparsePoint) != 0)
  172. throw new IOException("资源构建目录包含符号链接: " + child);
  173. if (Directory.Exists(child)) RejectLinks(child);
  174. }
  175. }
  176. }
  177. }