ArbitratorWindow.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. // Copyright (c) 2025 TerraByte Inc.
  2. //
  3. // This script creates a custom Unity Editor window called "Arbitrator" to compare
  4. // local Git changes with the tracked remote branch using the LibGit2Sharp library.
  5. //
  6. // HOW TO USE:
  7. // 1. Ensure you have manually installed the LibGit2Sharp v0.27.0 package.
  8. // 2. Create an "Editor" folder in your Assets directory if you don't have one.
  9. // 3. Save this script as "Arbitrator.cs" inside the "Editor" folder.
  10. // 4. In Unity, open the window from the top menu: Terra > Arbitrator.
  11. // 5. Click the "Compare with Cloud" button. Results will appear in the console.
  12. using System.Linq;
  13. using UnityEngine;
  14. using UnityEditor;
  15. using Terra.Arbitrator.Services;
  16. using Terra.Arbitrator.Settings;
  17. using System.Collections.Generic;
  18. namespace Terra.Arbitrator.GUI
  19. {
  20. public class ArbitratorWindow : EditorWindow
  21. {
  22. private List<GitChange> _changes;
  23. private string _commitMessage = "";
  24. private Vector2 _scrollPosition;
  25. private string _infoMessage;
  26. private string _errorMessage;
  27. private bool _isLoading;
  28. private string _loadingMessage = "";
  29. private GUIStyle _evenRowStyle;
  30. private bool _stylesInitialized;
  31. [MenuItem("Version Control/Better Git")]
  32. public static void ShowWindow()
  33. {
  34. var window = GetWindow<ArbitratorWindow>();
  35. window.titleContent = new GUIContent("Better Git", EditorGUIUtility.IconContent("d_UnityEditor.VersionControl").image);
  36. }
  37. /// <summary>
  38. /// Called when the window is enabled. This triggers an automatic refresh
  39. /// when the window is opened or after scripts are recompiled.
  40. /// </summary>
  41. private void OnEnable()
  42. {
  43. // Check if we just finished a reset operation and need to show a message.
  44. if (SessionState.GetBool(BetterGitStatePersistence.ResetQueueKey, false))
  45. {
  46. SessionState.EraseString(BetterGitStatePersistence.ResetQueueKey);
  47. _infoMessage = "Multi-file reset complete. Pulling again to confirm...";
  48. // After a successful reset, we should automatically try to pull again.
  49. HandlePull();
  50. }
  51. else
  52. {
  53. HandleCompare();
  54. }
  55. }
  56. /// <summary>
  57. /// Initializes custom GUIStyles. We do this here to avoid creating new
  58. /// styles and textures on every OnGUI call, which is inefficient.
  59. /// </summary>
  60. private void InitializeStyles()
  61. {
  62. if (_stylesInitialized) return;
  63. _evenRowStyle = new GUIStyle();
  64. // Create a 1x1 texture with a subtle gray color
  65. var texture = new Texture2D(1, 1);
  66. // Use a slightly different color depending on the editor skin (light/dark)
  67. var color = EditorGUIUtility.isProSkin
  68. ? new Color(0.3f, 0.3f, 0.3f, 0.3f)
  69. : new Color(0.8f, 0.8f, 0.8f, 0.5f);
  70. texture.SetPixel(0, 0, color);
  71. texture.Apply();
  72. _evenRowStyle.normal.background = texture;
  73. _stylesInitialized = true;
  74. }
  75. private void OnGUI()
  76. {
  77. InitializeStyles();
  78. // --- Top Toolbar ---
  79. DrawToolbar();
  80. EditorGUILayout.Space();
  81. // --- Message Display Area ---
  82. if (!string.IsNullOrEmpty(_errorMessage))
  83. {
  84. EditorGUILayout.HelpBox(_errorMessage, MessageType.Error);
  85. }
  86. else if (!string.IsNullOrEmpty(_infoMessage) && !_isLoading)
  87. {
  88. // Only show an info message if not loading, to prevent flicker
  89. EditorGUILayout.HelpBox(_infoMessage, MessageType.Info);
  90. }
  91. // --- Main Content ---
  92. else if (!_isLoading && _changes is { Count: > 0 })
  93. {
  94. DrawChangesList();
  95. DrawCommitSection();
  96. }
  97. }
  98. private void ClearMessages()
  99. {
  100. _errorMessage = null;
  101. _infoMessage = null;
  102. }
  103. /// <summary>
  104. /// Draws the top menu bar for actions like refreshing.
  105. /// </summary>
  106. private void DrawToolbar()
  107. {
  108. EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
  109. EditorGUI.BeginDisabledGroup(_isLoading);
  110. // The refresh button is now on the toolbar
  111. if (GUILayout.Button(new GUIContent("Refresh", EditorGUIUtility.IconContent("Refresh").image, "Fetches the latest status from the remote."), EditorStyles.toolbarButton, GUILayout.Width(80)))
  112. {
  113. HandleCompare();
  114. }
  115. if (GUILayout.Button(new GUIContent("Pull", EditorGUIUtility.IconContent("CollabPull").image, "Fetch and merge changes from the remote."), EditorStyles.toolbarButton, GUILayout.Width(80)))
  116. {
  117. HandlePull();
  118. }
  119. if (_changes is { Count: > 0 })
  120. {
  121. if (GUILayout.Button("Select All", EditorStyles.toolbarButton, GUILayout.Width(80)))
  122. {
  123. SetAllSelection(true);
  124. }
  125. if (GUILayout.Button("Deselect All", EditorStyles.toolbarButton, GUILayout.Width(80)))
  126. {
  127. SetAllSelection(false);
  128. }
  129. }
  130. EditorGUI.EndDisabledGroup();
  131. // This pushes everything that comes after it to the right.
  132. GUILayout.FlexibleSpace();
  133. // The loading message will appear on the right side of the toolbar.
  134. if (_isLoading)
  135. {
  136. GUILayout.Label(_loadingMessage);
  137. }
  138. // Future: Add a dropdown menu for filters or settings here.
  139. // If (GUILayout.Button("Filters", EditorStyles.toolbarDropDown)) { ... }
  140. EditorGUILayout.EndHorizontal();
  141. }
  142. private void SetAllSelection(bool selected)
  143. {
  144. if (_changes == null) return;
  145. foreach (var change in _changes)
  146. {
  147. change.IsSelectedForCommit = selected;
  148. }
  149. }
  150. private void HandleCompare()
  151. {
  152. _isLoading = true;
  153. _loadingMessage = "Comparing with remote repository...";
  154. ClearMessages();
  155. _changes = null;
  156. // First, unstage any files if it's safe to do so.
  157. GitService.UnstageAllFilesIfSafe()
  158. .Then(wasUnstaged =>
  159. {
  160. if(wasUnstaged)
  161. {
  162. _infoMessage = "Found and unstaged files for review.";
  163. }
  164. GitService.CompareLocalToRemote()
  165. .Then(result =>
  166. {
  167. _changes = result;
  168. if (string.IsNullOrEmpty(_infoMessage) && (_changes == null || _changes.Count == 0))
  169. {
  170. _infoMessage = "You are up-to-date! No local changes detected.";
  171. }
  172. })
  173. .Catch(ex =>
  174. {
  175. _errorMessage = $"Comparison Failed: {ex.Message}";
  176. })
  177. .Finally(() =>
  178. {
  179. // This finally block only runs after the *inner* promise is done.
  180. _isLoading = false;
  181. Repaint();
  182. });
  183. })
  184. .Catch(ex =>
  185. {
  186. // This catch block handles errors from the Unstage operation.
  187. _errorMessage = $"Unstaging Failed: {ex.Message}";
  188. _isLoading = false;
  189. Repaint();
  190. });
  191. }
  192. /// <summary>
  193. /// Handles the logic for the Pull button.
  194. /// </summary>
  195. private void HandlePull()
  196. {
  197. if (_isLoading) return;
  198. _isLoading = true;
  199. _loadingMessage = "Analyzing for conflicts...";
  200. ClearMessages();
  201. Repaint();
  202. GitService.AnalyzePullConflicts()
  203. .Then(analysisResult =>
  204. {
  205. if (analysisResult.HasConflicts)
  206. {
  207. // Conflicts found! Open the resolution window.
  208. _isLoading = false; // Stop loading while modal is open
  209. Repaint();
  210. ConflictResolutionWindow.ShowWindow(analysisResult.ConflictingFiles, filesToActOn =>
  211. {
  212. if (filesToActOn == null) return; // User cancelled
  213. if (filesToActOn.Any()) HandleResetMultipleFiles(filesToActOn);
  214. else HandleForcePull(); // User chose "Pull Anyway" (empty list signal)
  215. });
  216. }
  217. else
  218. {
  219. // No conflicts, proceed with a safe pull.
  220. _loadingMessage = "No conflicts found. Pulling changes...";
  221. Repaint();
  222. GitService.PerformSafePull()
  223. .Then(successMessage =>
  224. {
  225. _infoMessage = successMessage;
  226. EditorUtility.DisplayDialog("Pull Complete", successMessage, "OK");
  227. HandleCompare(); // Refresh view after successful pull
  228. })
  229. .Catch(ex =>
  230. {
  231. _errorMessage = $"Pull Failed: {ex.Message}";
  232. _isLoading = false;
  233. Repaint();
  234. });
  235. }
  236. })
  237. .Catch(ex =>
  238. {
  239. _errorMessage = $"Pull Analysis Failed: {ex.Message}";
  240. _isLoading = false;
  241. Repaint();
  242. });
  243. }
  244. private void HandleResetMultipleFiles(List<string> filePaths)
  245. {
  246. _infoMessage = $"Starting reset for {filePaths.Count} file(s)... This may trigger script compilation.";
  247. Repaint();
  248. SessionState.SetString("BetterGit.ResetQueue", string.Join(";", filePaths));
  249. EditorApplication.delayCall += BetterGitStatePersistence.ContinueInterruptedReset;
  250. }
  251. private void HandleForcePull()
  252. {
  253. _isLoading = true;
  254. _loadingMessage = "Attempting to pull and create conflicts...";
  255. ClearMessages();
  256. Repaint();
  257. EditorApplication.LockReloadAssemblies();
  258. GitService.ForcePull()
  259. .Then(_ =>
  260. {
  261. _infoMessage = "Pull resulted in conflicts. Please resolve them below.";
  262. HandleCompare();
  263. })
  264. .Catch(ex =>
  265. {
  266. _errorMessage = $"Forced Pull Failed: {ex.Message}";
  267. _isLoading = false;
  268. Repaint();
  269. })
  270. .Finally(() =>
  271. {
  272. EditorApplication.UnlockReloadAssemblies();
  273. AssetDatabase.Refresh();
  274. });
  275. }
  276. private void HandleCommitAndPush()
  277. {
  278. _isLoading = true;
  279. _loadingMessage = "Staging, committing, and pushing files...";
  280. ClearMessages();
  281. var selectedFiles = _changes.Where(c => c.IsSelectedForCommit).ToList();
  282. var username = BetterGitSettings.Username;
  283. var email = BetterGitSettings.Email;
  284. GitService.CommitAndPush(selectedFiles, _commitMessage, username, email)
  285. .Then(successMessage => {
  286. _infoMessage = successMessage;
  287. _commitMessage = ""; // Clear message on success
  288. _changes = null; // Clear the list, forcing a refresh
  289. HandleCompare(); // Automatically refresh to confirm
  290. })
  291. .Catch(ex => {
  292. _errorMessage = $"Push Failed: {ex.Message}";
  293. })
  294. .Finally(() => {
  295. _isLoading = false;
  296. // Repaint is handled by the chained HandleCompare call on success
  297. if (!string.IsNullOrEmpty(_errorMessage)) Repaint();
  298. });
  299. }
  300. private void HandleResetFile(GitChange change)
  301. {
  302. if (_isLoading) return;
  303. var userConfirmed = EditorUtility.DisplayDialog("Confirm Reset", $"Are you sure you want to revert all local changes to '{change.FilePath}'? This action cannot be undone.", "Yes, Revert", "Cancel");
  304. if (!userConfirmed) return;
  305. _isLoading = true;
  306. _loadingMessage = $"Resetting {change.FilePath}...";
  307. ClearMessages();
  308. Repaint();
  309. GitService.ResetFileChanges(change)
  310. .Then(successMessage => {
  311. _infoMessage = successMessage;
  312. HandleCompare();
  313. })
  314. .Catch(ex => {
  315. _errorMessage = $"Reset Failed: {ex.Message}";
  316. _isLoading = false;
  317. Repaint();
  318. });
  319. }
  320. private void HandleDiffFile(GitChange change)
  321. {
  322. if (_isLoading) return;
  323. _isLoading = true;
  324. _loadingMessage = $"Launching diff for {change.FilePath}...";
  325. ClearMessages();
  326. Repaint();
  327. GitService.LaunchExternalDiff(change)
  328. .Catch(ex => _errorMessage = ex.Message)
  329. .Finally(() => { _isLoading = false; HandleCompare(); });
  330. }
  331. private void HandleResolveConflict(GitChange change)
  332. {
  333. if (_isLoading) return;
  334. _isLoading = true;
  335. _loadingMessage = $"Opening merge tool for {change.FilePath}...";
  336. ClearMessages();
  337. Repaint();
  338. GitService.LaunchMergeTool(change)
  339. .Then(successMessage =>
  340. {
  341. _infoMessage = successMessage;
  342. })
  343. .Catch(ex =>
  344. {
  345. _errorMessage = $"Resolve Failed: {ex.Message}";
  346. })
  347. .Finally(() =>
  348. {
  349. _isLoading = false;
  350. HandleCompare(); // Always refresh to show the new state
  351. });
  352. }
  353. /// <summary>
  354. /// Draws the multi-column list of changed files.
  355. /// </summary>
  356. private void DrawChangesList()
  357. {
  358. // --- Draw Header ---
  359. EditorGUILayout.BeginHorizontal(EditorStyles.helpBox);
  360. var isConflictMode = _changes.Any(c => c.Status == LibGit2Sharp.ChangeKind.Conflicted);
  361. if (!isConflictMode) EditorGUILayout.LabelField("Commit", GUILayout.Width(45));
  362. else GUILayout.Space(45); // Keep layout consistent
  363. EditorGUILayout.LabelField("Status", GUILayout.Width(50));
  364. EditorGUILayout.LabelField("File Path");
  365. EditorGUILayout.LabelField("Actions", GUILayout.Width(55));
  366. EditorGUILayout.EndHorizontal();
  367. // --- Draw Scrollable List ---
  368. _scrollPosition = EditorGUILayout.BeginScrollView(_scrollPosition, GUILayout.ExpandHeight(true));
  369. for (var i = 0; i < _changes.Count; i++)
  370. {
  371. var change = _changes[i];
  372. // Use the evenRowStyle for every second row (i % 2 == 0), otherwise use no style.
  373. var rowStyle = i % 2 == 0 ? _evenRowStyle : GUIStyle.none;
  374. EditorGUILayout.BeginHorizontal(rowStyle);
  375. change.IsSelectedForCommit = EditorGUILayout.Toggle(change.IsSelectedForCommit, GUILayout.Width(45));
  376. string status;
  377. Color statusColor;
  378. string filePathDisplay;
  379. switch (change.Status)
  380. {
  381. case LibGit2Sharp.ChangeKind.Added:
  382. status = "[+]"; statusColor = Color.green; filePathDisplay = change.FilePath; break;
  383. case LibGit2Sharp.ChangeKind.Deleted:
  384. status = "[-]"; statusColor = Color.red; filePathDisplay = change.FilePath; break;
  385. case LibGit2Sharp.ChangeKind.Modified:
  386. status = "[M]"; statusColor = new Color(1.0f, 0.6f, 0.0f); filePathDisplay = change.FilePath; break;
  387. case LibGit2Sharp.ChangeKind.Renamed:
  388. status = "[R]"; statusColor = new Color(0.6f, 0.6f, 1.0f);
  389. filePathDisplay = $"{change.OldFilePath} -> {change.FilePath}"; break;
  390. case LibGit2Sharp.ChangeKind.Conflicted:
  391. status = "[C]"; statusColor = Color.magenta; filePathDisplay = change.FilePath; break;
  392. case LibGit2Sharp.ChangeKind.Unmodified:
  393. case LibGit2Sharp.ChangeKind.Copied:
  394. case LibGit2Sharp.ChangeKind.Ignored:
  395. case LibGit2Sharp.ChangeKind.Untracked:
  396. case LibGit2Sharp.ChangeKind.TypeChanged:
  397. case LibGit2Sharp.ChangeKind.Unreadable:
  398. default:
  399. status = "[?]"; statusColor = Color.white; filePathDisplay = change.FilePath; break;
  400. }
  401. var originalColor = UnityEngine.GUI.color;
  402. UnityEngine.GUI.color = statusColor;
  403. EditorGUILayout.LabelField(new GUIContent(status, change.Status.ToString()), GUILayout.Width(50));
  404. UnityEngine.GUI.color = originalColor;
  405. EditorGUILayout.LabelField(new GUIContent(filePathDisplay, filePathDisplay));
  406. EditorGUI.BeginDisabledGroup(_isLoading);
  407. if (status == "[C]")
  408. {
  409. if (GUILayout.Button("Resolve", GUILayout.Width(70))) { EditorApplication.delayCall += () => HandleResolveConflict(change); }
  410. }
  411. else
  412. {
  413. if (GUILayout.Button("Diff", GUILayout.Width(45))) EditorApplication.delayCall += () => HandleDiffFile(change);
  414. }
  415. if (GUILayout.Button(new GUIContent("Reset", "Revert changes for this file"), GUILayout.Width(55)))
  416. {
  417. EditorApplication.delayCall += () => HandleResetFile(change);
  418. }
  419. EditorGUI.EndDisabledGroup();
  420. EditorGUILayout.EndHorizontal();
  421. }
  422. EditorGUILayout.EndScrollView();
  423. }
  424. private void DrawCommitSection()
  425. {
  426. EditorGUILayout.Space(10);
  427. var isConflictMode = _changes.Any(c => c.Status == LibGit2Sharp.ChangeKind.Conflicted);
  428. if (isConflictMode)
  429. {
  430. EditorGUILayout.HelpBox("You must resolve all conflicts before you can commit.", MessageType.Warning);
  431. return;
  432. }
  433. EditorGUILayout.LabelField("Commit & Push", EditorStyles.boldLabel);
  434. _commitMessage = EditorGUILayout.TextArea(_commitMessage, GUILayout.Height(60), GUILayout.ExpandWidth(true));
  435. var isPushDisabled = string.IsNullOrWhiteSpace(_commitMessage) || !_changes.Any(c => c.IsSelectedForCommit);
  436. EditorGUI.BeginDisabledGroup(isPushDisabled);
  437. if (GUILayout.Button("Commit & Push Selected Files", GUILayout.Height(40)))
  438. {
  439. HandleCommitAndPush();
  440. }
  441. EditorGUI.EndDisabledGroup();
  442. if (isPushDisabled)
  443. {
  444. EditorGUILayout.HelpBox("Please enter a commit message and select at least one file.", MessageType.Warning);
  445. }
  446. }
  447. }
  448. }