using System.Diagnostics; using System.IO; using UnityEditor; using UnityEditor.Build; using UnityEditor.Build.Reporting; using UnityEngine; using Debug = UnityEngine.Debug; // Build 前把 git commit 短碼寫到 Assets/BuildInfo/Resources/build_id.txt (不進 git),執行時由 BuildInfo.Id 讀出、記進 config 的 buildId // 工作區不乾淨 (有未提交的改動) 會在後面加 "-dirty" ; git 執行不了時改讀 .git 檔案並加 "-nogit" ; 都讀不到是 "unknown" // 正式出包前請先全部 commit,出包後對該 commit 打 tag public class BuildIdWriter : IPreprocessBuildWithReport { const string Folder = "Assets/BuildInfo/Resources"; const string FilePath = Folder + "/build_id.txt"; public int callbackOrder => 0; public void OnPreprocessBuild(BuildReport report) { string id = BuildId(); Directory.CreateDirectory(Folder); File.WriteAllText(FilePath, id); AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); Debug.Log($"BuildIdWriter : buildId = {id}"); } // 正式出包應該是乾淨的 7 碼 ; 出現 -dirty、-nogit、unknown 都代表這個 exe 不該發出去 static string BuildId() { string hash = Git("rev-parse --short HEAD"); // git 執行不了 (v1.1.0 出過包) : 改直接讀 .git 裡的檔案,但無法判斷工作區乾不乾淨 if (string.IsNullOrEmpty(hash)) { string fromFiles = ReadHeadFromFiles(); if (string.IsNullOrEmpty(fromFiles)) { Debug.LogWarning("BuildIdWriter : git 與 .git 檔案都讀不到,buildId 會是 unknown。這個 exe 不該發出去。"); return "unknown"; } Debug.LogWarning("BuildIdWriter : git 執行失敗,改從 .git 檔案讀 commit,無法確認工作區是否乾淨,buildId 加上 -nogit。這個 exe 不該發出去,請在 git 能正常執行的環境重新出包。"); return fromFiles + "-nogit"; } bool dirty = false; foreach (string line in Git("status --porcelain").Split('\n')) { string l = line.Trim(); if (l.Length == 0) continue; dirty = true; break; } if (dirty) { Debug.LogWarning("BuildIdWriter : 工作區有未提交的改動,buildId 加上 -dirty。正式出包請先 commit 再 Build。"); return hash + "-dirty"; } return hash; } // 讀 .git/HEAD : 「ref: refs/heads/<分支>」就再讀該分支的檔案 (沒有就找 packed-refs) ; 直接是雜湊 (detached HEAD) 就用它 // 回傳前 7 碼,讀不到回傳空字串 static string ReadHeadFromFiles() { try { string gitDir = Path.Combine(Path.GetDirectoryName(Application.dataPath), ".git"); string head = File.ReadAllText(Path.Combine(gitDir, "HEAD")).Trim(); string hash = head; if (head.StartsWith("ref:")) { string refName = head.Substring(4).Trim(); string refPath = Path.Combine(gitDir, refName.Replace('/', Path.DirectorySeparatorChar)); hash = File.Exists(refPath) ? File.ReadAllText(refPath).Trim() : FindPackedRef(gitDir, refName); } return IsHash(hash) ? hash.Substring(0, 7) : ""; } catch (System.Exception e) { Debug.LogWarning($"BuildIdWriter : 讀取 .git 檔案失敗 ({e.Message})"); return ""; } } // packed-refs 每行是「<雜湊> 」,# 開頭是註解,^ 開頭是 tag 指向的 commit static string FindPackedRef(string gitDir, string refName) { string path = Path.Combine(gitDir, "packed-refs"); if (!File.Exists(path)) return ""; foreach (string raw in File.ReadAllLines(path)) { string line = raw.Trim(); if (line.Length == 0 || line[0] == '#' || line[0] == '^') continue; int space = line.IndexOf(' '); if (space > 0 && line.Substring(space + 1).Trim() == refName) return line.Substring(0, space); } return ""; } static bool IsHash(string s) { if (string.IsNullOrEmpty(s) || s.Length < 40) return false; for (int i = 0; i < 40; i++) { if (!System.Uri.IsHexDigit(s[i])) return false; } return true; } static string Git(string arguments) { try { ProcessStartInfo info = new ProcessStartInfo("git", arguments) { WorkingDirectory = Path.GetDirectoryName(Application.dataPath), RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true, }; using (Process p = Process.Start(info)) { string output = p.StandardOutput.ReadToEnd(); p.WaitForExit(); return p.ExitCode == 0 ? output.Trim() : ""; } } catch (System.Exception e) { Debug.LogWarning($"BuildIdWriter : 執行 git 失敗 ({e.Message}),改讀 .git 檔案"); return ""; } } }