HotPatchResourcePackage.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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, string manifestFileName = HotPatchResourceStore.ManifestFileName)
  60. {
  61. if (manifestFileName != HotPatchResourceStore.ManifestFileName && manifestFileName != HotManifestFileName)
  62. throw new ArgumentException("资源清单名称不正确。", nameof(manifestFileName));
  63. if (Directory.Exists(destination) && Directory.EnumerateFileSystemEntries(destination).Any())
  64. throw new IOException("资源输出目录必须为空: " + destination);
  65. var json = File.ReadAllText(RequireChild(sourceDirectory, Path.Combine(sourceDirectory, manifestFileName)));
  66. var original = HotPatchResourceStore.Parse(json);
  67. original.Validate(original.assemblyName, original.platform, original.gameSceneName);
  68. if (original.aotBundle == null || (original.aotMetadata?.Length ?? 0) == 0)
  69. throw new InvalidDataException("原始资源缺少完整 AOT 清单。");
  70. var resources = original.resources.Concat(new[] { original.aotBundle }).ToArray();
  71. foreach (var resource in resources)
  72. if (!HotPatchResourceStore.IsVerified(RequireChild(sourceDirectory, Path.Combine(sourceDirectory, resource.RelativePath)), resource))
  73. throw new InvalidDataException("原始资源缺失或损坏: " + resource.name);
  74. foreach (var resource in resources)
  75. {
  76. var output = RequireChild(destination, Path.Combine(destination, resource.RelativePath));
  77. Directory.CreateDirectory(Path.GetDirectoryName(output));
  78. File.Copy(Path.Combine(sourceDirectory, resource.RelativePath), output);
  79. if (!HotPatchResourceStore.IsVerified(output, resource)) throw new IOException("原始资源复制失败: " + resource.name);
  80. }
  81. File.WriteAllText(Path.Combine(destination, HotPatchResourceStore.ManifestFileName), json, new UTF8Encoding(false));
  82. }
  83. public static void AppendUpdate(string originalDirectory, string updateDirectory)
  84. {
  85. var original = HotPatchResourceStore.Parse(File.ReadAllText(Path.Combine(originalDirectory, HotPatchResourceStore.ManifestFileName)));
  86. var updateJson = File.ReadAllText(Path.Combine(updateDirectory, HotPatchResourceStore.ManifestFileName));
  87. var update = HotPatchResourceStore.Parse(updateJson);
  88. original.Validate(original.assemblyName, original.platform, original.gameSceneName);
  89. update.ValidateAgainst(original);
  90. if (original.aotBundle == null || update.aotBundle == null ||
  91. (original.aotMetadata?.Length ?? 0) == 0 || update.aotMetadata?.Length != original.aotMetadata.Length)
  92. throw new InvalidDataException("合并资源需要两份完整且一致的 AOT 清单。");
  93. var hotManifest = RequireChild(originalDirectory, Path.Combine(originalDirectory, HotManifestFileName));
  94. if (File.Exists(hotManifest)) throw new IOException("原始资源暂存目录已包含更新清单。");
  95. foreach (var resource in original.resources.Concat(new[] { original.aotBundle }))
  96. if (!HotPatchResourceStore.IsVerified(RequireChild(originalDirectory, Path.Combine(originalDirectory, resource.RelativePath)), resource))
  97. throw new InvalidDataException("原始资源缺失或损坏: " + resource.name);
  98. foreach (var resource in update.resources)
  99. if (!HotPatchResourceStore.IsVerified(RequireChild(updateDirectory, Path.Combine(updateDirectory, resource.RelativePath)), resource))
  100. throw new InvalidDataException("更新资源缺失或损坏: " + resource.name);
  101. foreach (var resource in update.resources)
  102. {
  103. var destination = RequireChild(originalDirectory, Path.Combine(originalDirectory, resource.RelativePath));
  104. if (File.Exists(destination))
  105. {
  106. if (!HotPatchResourceStore.IsVerified(destination, resource)) throw new InvalidDataException("资源哈希路径冲突: " + resource.name);
  107. continue;
  108. }
  109. File.Copy(Path.Combine(updateDirectory, resource.RelativePath), destination);
  110. if (!HotPatchResourceStore.IsVerified(destination, resource)) throw new IOException("更新资源复制失败: " + resource.name);
  111. }
  112. File.WriteAllText(hotManifest, updateJson, new UTF8Encoding(false));
  113. }
  114. public static HotPatchResource Describe(string name, string kind, string source)
  115. {
  116. if (!File.Exists(source)) throw new FileNotFoundException("资源源文件不存在。", source);
  117. return new HotPatchResource { name = name, kind = kind, size = new FileInfo(source).Length, sha256 = HotPatchHash.OfFile(source) };
  118. }
  119. public static void ClearDirectory(string directory, string allowedParent)
  120. {
  121. directory = RequireChild(allowedParent, directory);
  122. if (!Directory.Exists(directory)) return;
  123. RejectLinks(directory);
  124. foreach (var entry in Directory.GetFileSystemEntries(directory))
  125. {
  126. var path = RequireChild(directory, entry);
  127. if (Directory.Exists(path)) Directory.Delete(path, true);
  128. else File.Delete(path);
  129. }
  130. }
  131. public static void DeleteDirectory(string directory, string allowedParent)
  132. {
  133. directory = RequireChild(allowedParent, directory);
  134. ClearDirectory(directory, allowedParent);
  135. if (Directory.Exists(directory)) Directory.Delete(directory);
  136. var meta = RequireChild(allowedParent, directory + ".meta");
  137. if (File.Exists(meta)) File.Delete(meta);
  138. }
  139. public static void ReplaceDirectory(string staging, string destination, string stagingParent, string destinationParent)
  140. {
  141. staging = RequireChild(stagingParent, staging);
  142. destination = RequireChild(destinationParent, destination);
  143. if (!Directory.Exists(staging)) throw new DirectoryNotFoundException(staging);
  144. RejectLinks(staging);
  145. if (Directory.Exists(destination)) RejectLinks(destination);
  146. var backup = RequireChild(stagingParent, Path.Combine(stagingParent, "replaced-" + Guid.NewGuid().ToString("N")));
  147. bool hadOld = Directory.Exists(destination);
  148. if (hadOld) Directory.Move(destination, backup);
  149. try { Directory.Move(staging, destination); }
  150. catch
  151. {
  152. if (hadOld) Directory.Move(backup, destination);
  153. throw;
  154. }
  155. if (hadOld) Directory.Delete(backup, true);
  156. }
  157. public static string RequireChild(string parent, string path)
  158. {
  159. var root = Path.GetFullPath(parent).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
  160. var full = Path.GetFullPath(path);
  161. if (!full.StartsWith(root, StringComparison.OrdinalIgnoreCase)) throw new IOException("资源路径超出指定目录: " + full);
  162. for (var ancestor = new DirectoryInfo(Path.GetDirectoryName(full)); ancestor != null; ancestor = ancestor.Parent)
  163. if (ancestor.Exists && (ancestor.Attributes & FileAttributes.ReparsePoint) != 0)
  164. throw new IOException("资源路径包含符号链接目录: " + ancestor.FullName);
  165. return full;
  166. }
  167. static void RejectLinks(string directory)
  168. {
  169. if ((File.GetAttributes(directory) & FileAttributes.ReparsePoint) != 0)
  170. throw new IOException("资源构建目录不能是符号链接: " + directory);
  171. foreach (var child in Directory.GetFileSystemEntries(directory))
  172. {
  173. if ((File.GetAttributes(child) & FileAttributes.ReparsePoint) != 0)
  174. throw new IOException("资源构建目录包含符号链接: " + child);
  175. if (Directory.Exists(child)) RejectLinks(child);
  176. }
  177. }
  178. }
  179. }