| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Security.Cryptography;
- using System.Text;
- using Newtonsoft.Json.Linq;
- using UnityEditor;
- using UnityEditor.Compilation;
- using UnityEngine;
- public static class HotPatchSourceSync
- {
- public static string AssemblyName => AppSettings.RequireHotPatchAssemblyName();
- public const string Begin = "#if UNITY_EDITOR";
- public const string End = "#endif";
- const string ManifestPath = "ProjectSettings/HotPatchSources.json";
- public static void SyncMenu()
- {
- try { Synchronize(); Debug.Log("[热补丁] 源码同步完成,等待 Unity 编译。"); }
- catch (Exception e) { Debug.LogException(e); }
- }
- public static string FindAssemblyPath()
- {
- var assembly = HotPatchAssemblySelection.Find(AssemblyName);
- HotPatchAssemblySelection.Validate(assembly);
- return AssetDatabase.GetAssetPath(assembly);
- }
- public static string RemoveEditorEnvelope(string source)
- {
- var text = source.TrimStart('\uFEFF').Replace("\r\n", "\n").Trim();
- if (!text.StartsWith(Begin + "\n", StringComparison.Ordinal) || !text.EndsWith("\n" + End, StringComparison.Ordinal))
- throw new InvalidDataException("Sources 脚本缺少热补丁最外层 UNITY_EDITOR 包装。");
- var body = text.Substring(Begin.Length + 1, text.Length - Begin.Length - End.Length - 2);
- int depth = 0;
- foreach (var line in body.Split('\n'))
- {
- var directive = line.TrimStart();
- if (directive.StartsWith("#if ", StringComparison.Ordinal)) depth++;
- else if (directive.StartsWith("#endif", StringComparison.Ordinal))
- { if (--depth < 0) throw new InvalidDataException("Sources 条件编译嵌套不正确。"); }
- }
- if (depth != 0) throw new InvalidDataException("Sources 条件编译未闭合。");
- return body + "\n";
- }
- public static string PackageRoot => UnityEditor.PackageManager.PackageInfo.FindForAssembly(typeof(AppSettings).Assembly)?.resolvedPath
- ?? throw new InvalidOperationException("找不到 AppRuntimes 包。");
- public static bool Synchronize(bool refresh = true)
- {
- if (EditorApplication.isPlayingOrWillChangePlaymode) throw new InvalidOperationException("请先退出 Play Mode。");
- var asmPath = FindAssemblyPath();
- var root = (Path.GetDirectoryName(asmPath) + "/HotPatch").Replace('\\', '/');
- var sourceRoot = Path.Combine(PackageRoot, "Runtime/Sources");
- var desired = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- foreach (var source in Directory.GetFiles(sourceRoot, "*.cs", SearchOption.AllDirectories))
- {
- var relative = source.Substring(sourceRoot.Length + 1).Replace('\\', '/');
- desired.Add(root + "/" + relative, RemoveEditorEnvelope(File.ReadAllText(source)));
- }
- if (desired.Count == 0) throw new InvalidOperationException("Sources 没有可复制的脚本。");
- var previous = File.Exists(ManifestPath) ? JObject.Parse(File.ReadAllText(ManifestPath)) : new JObject();
- var oldRoot = (string)previous["root"] ?? root;
- RequireChild("Assets", oldRoot);
- if (!oldRoot.EndsWith("/HotPatch", StringComparison.Ordinal) && !oldRoot.EndsWith("/Generated/HotPatch/Sources", StringComparison.Ordinal))
- throw new InvalidDataException("旧生成目录不是热补丁目录。");
- var owned = previous["files"] as JObject ?? new JObject();
- foreach (var item in owned.Properties())
- {
- RequireChild(oldRoot, item.Name);
- if (!item.Name.EndsWith(".cs", StringComparison.Ordinal)) throw new InvalidDataException("生成记录包含非脚本路径。");
- if (File.Exists(item.Name) && Hash(File.ReadAllText(item.Name)) != (string)item.Value)
- throw new InvalidOperationException("生成文件被手工修改,请先合并到 Sources: " + item.Name);
- }
- foreach (var item in desired)
- if (File.Exists(item.Key) && owned[item.Key] == null && File.ReadAllText(item.Key) != item.Value)
- throw new InvalidOperationException("热补丁目标文件冲突: " + item.Key);
- var targetFolder = Path.GetDirectoryName(asmPath);
- var names = new[] { "AppRuntimes", "ClientCrypto", "Https", "FBHandler", "DictionaryExtensions", "NativeAppInfo", "DeviceTimeZone" };
- foreach (var file in Directory.GetFiles(targetFolder, "*.cs", SearchOption.AllDirectories))
- {
- if (owned[file.Replace('\\', '/')] != null) continue;
- if (Path.GetFullPath(file).StartsWith(Path.GetFullPath(root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) continue;
- if (CompilationPipeline.GetAssemblyNameFromScriptPath(file.Replace('\\', '/')) != AssemblyName) continue;
- var text = File.ReadAllText(file);
- if (names.Any(n => System.Text.RegularExpressions.Regex.IsMatch(text, @"\bclass\s+" + n + @"\b")))
- throw new InvalidOperationException("发现重复业务类型,请移除旧副本: " + file);
- }
- var asm = JObject.Parse(File.ReadAllText(asmPath));
- var references = ((JArray)asm["references"] ?? new JArray()).Values<string>().Where(r => !IsOldRuntimeReference(r)).ToList();
- foreach (var reference in new[] { "AppRuntimes.Base", "UniTask", "UnityEngine.UI", "UniWebView-CSharp", "Unity.Advertisement.IosSupport" })
- if (!references.Contains(reference)) references.Add(reference);
- asm["references"] = new JArray(references); asm["autoReferenced"] = false;
- desired[asmPath] = asm.ToString() + "\n";
- var generatedManifest = new JObject();
- foreach (var item in desired.Where(p => p.Key != asmPath)) generatedManifest[item.Key] = Hash(item.Value);
- if (oldRoot != root)
- {
- foreach (var item in owned.Properties())
- {
- var destination = root + item.Name.Substring(oldRoot.Length);
- if (!desired.ContainsKey(destination) || !File.Exists(item.Name + ".meta")) continue;
- if (File.Exists(destination + ".meta")) throw new InvalidOperationException("迁移目标已有 GUID,请先处理冲突: " + destination);
- desired[destination + ".meta"] = File.ReadAllText(item.Name + ".meta");
- }
- }
- desired[ManifestPath] = new JObject { ["root"] = root, ["assemblyName"] = AssemblyName, ["files"] = generatedManifest }.ToString() + "\n";
- var removed = owned.Properties().Select(p => p.Name).Where(p => !desired.ContainsKey(p)).ToArray();
- var changes = desired.Where(p => !File.Exists(p.Key) || File.ReadAllText(p.Key) != p.Value).ToArray();
- if (changes.Length == 0 && removed.Length == 0) return false;
- var touched = changes.Select(p => p.Key).Concat(removed.SelectMany(p => new[] { p, p + ".meta" })).Distinct().ToArray();
- var backups = touched.ToDictionary(p => p, p => File.Exists(p) ? File.ReadAllBytes(p) : null);
- AssetDatabase.StartAssetEditing();
- try
- {
- foreach (var change in changes)
- { Directory.CreateDirectory(Path.GetDirectoryName(change.Key)); File.WriteAllText(change.Key, change.Value, new UTF8Encoding(false)); }
- foreach (var path in removed)
- { if (File.Exists(path)) File.Delete(path); if (File.Exists(path + ".meta")) File.Delete(path + ".meta"); }
- }
- catch
- {
- foreach (var backup in backups)
- if (backup.Value == null) { if (File.Exists(backup.Key)) File.Delete(backup.Key); }
- else File.WriteAllBytes(backup.Key, backup.Value);
- throw;
- }
- finally { AssetDatabase.StopAssetEditing(); }
- if (refresh) AssetDatabase.Refresh();
- return true;
- }
- public static void VerifySynchronized()
- {
- var path = FindAssemblyPath();
- var root = Path.GetDirectoryName(path) + "/HotPatch";
- var sources = Path.Combine(PackageRoot, "Runtime/Sources");
- var expected = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
- foreach (var source in Directory.GetFiles(sources, "*.cs", SearchOption.AllDirectories))
- {
- var output = Path.Combine(root, source.Substring(sources.Length + 1));
- expected.Add(Path.GetFullPath(output));
- if (!File.Exists(output) || File.ReadAllText(output) != RemoveEditorEnvelope(File.ReadAllText(source)))
- throw new InvalidOperationException("热补丁源码未同步,请执行 资源构建/一键打包资源。");
- }
- if (Directory.GetFiles(root, "*.cs", SearchOption.AllDirectories).Any(p => !expected.Contains(Path.GetFullPath(p))))
- throw new InvalidOperationException("HotPatch 目录包含过期或未托管脚本,请执行同步并处理冲突。");
- }
- static bool IsOldRuntimeReference(string value)
- {
- if (value == "AppRuntimes" || value == "AppRuntimes.Sources.Editor") return true;
- if (!value.StartsWith("GUID:", StringComparison.Ordinal)) return false;
- var path = AssetDatabase.GUIDToAssetPath(value.Substring(5));
- if (!File.Exists(path)) return false;
- var name = (string)JObject.Parse(File.ReadAllText(path))["name"];
- return name == "AppRuntimes" || name == "AppRuntimes.Sources.Editor";
- }
- static void RequireChild(string root, string file)
- {
- if (!Path.GetFullPath(file).StartsWith(Path.GetFullPath(root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
- throw new InvalidDataException("生成记录包含目录外路径。");
- }
- public static string Hash(string text)
- {
- using var hash = SHA256.Create();
- return BitConverter.ToString(hash.ComputeHash(Encoding.UTF8.GetBytes(text))).Replace("-", "").ToLowerInvariant();
- }
- }
|