ArbitratorWindow.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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. if (GUILayout.Button(new GUIContent("Reset All", EditorGUIUtility.IconContent("d_TreeEditor.Trash").image, "Discard ALL local changes."), EditorStyles.toolbarButton, GUILayout.Width(100)))
  130. {
  131. // We use delayCall to avoid GUI layout issues from the dialog.
  132. EditorApplication.delayCall += HandleResetAll;
  133. }
  134. }
  135. EditorGUI.EndDisabledGroup();
  136. // This pushes everything that comes after it to the right.
  137. GUILayout.FlexibleSpace();
  138. // The loading message will appear on the right side of the toolbar.
  139. if (_isLoading)
  140. {
  141. GUILayout.Label(_loadingMessage);
  142. }
  143. // Future: Add a dropdown menu for filters or settings here.
  144. // If (GUILayout.Button("Filters", EditorStyles.toolbarDropDown)) { ... }
  145. EditorGUILayout.EndHorizontal();
  146. }
  147. private void SetAllSelection(bool selected)
  148. {
  149. if (_changes == null) return;
  150. foreach (var change in _changes)
  151. {
  152. change.IsSelectedForCommit = selected;
  153. }
  154. }
  155. private void HandleCompare()
  156. {
  157. _isLoading = true;
  158. _loadingMessage = "Comparing with remote repository...";
  159. ClearMessages();
  160. _changes = null;
  161. // First, unstage any files if it's safe to do so.
  162. GitService.UnstageAllFilesIfSafe()
  163. .Then(wasUnstaged =>
  164. {
  165. if(wasUnstaged)
  166. {
  167. _infoMessage = "Found and unstaged files for review.";
  168. }
  169. GitService.CompareLocalToRemote()
  170. .Then(result =>
  171. {
  172. _changes = result;
  173. if (string.IsNullOrEmpty(_infoMessage) && (_changes == null || _changes.Count == 0))
  174. {
  175. _infoMessage = "You are up-to-date! No local changes detected.";
  176. }
  177. })
  178. .Catch(ex =>
  179. {
  180. _errorMessage = $"Comparison Failed: {ex.Message}";
  181. })
  182. .Finally(() =>
  183. {
  184. // This finally block only runs after the *inner* promise is done.
  185. _isLoading = false;
  186. Repaint();
  187. });
  188. })
  189. .Catch(ex =>
  190. {
  191. // This catch block handles errors from the Unstage operation.
  192. _errorMessage = $"Unstaging Failed: {ex.Message}";
  193. _isLoading = false;
  194. Repaint();
  195. });
  196. }
  197. /// <summary>
  198. /// Handles the logic for the Pull button.
  199. /// </summary>
  200. private void HandlePull()
  201. {
  202. if (_isLoading) return;
  203. _isLoading = true;
  204. _loadingMessage = "Analyzing for conflicts...";
  205. ClearMessages();
  206. Repaint();
  207. GitService.AnalyzePullConflicts()
  208. .Then(analysisResult =>
  209. {
  210. if (analysisResult.HasConflicts)
  211. {
  212. // Conflicts found! Open the resolution window.
  213. _isLoading = false; // Stop loading while modal is open
  214. Repaint();
  215. ConflictResolutionWindow.ShowWindow(analysisResult.ConflictingFiles, filesToActOn =>
  216. {
  217. if (filesToActOn == null) return; // User cancelled
  218. if (filesToActOn.Any()) HandleResetMultipleFiles(filesToActOn);
  219. else HandleForcePull(); // User chose "Pull Anyway" (empty list signal)
  220. });
  221. }
  222. else
  223. {
  224. // No conflicts, proceed with a safe pull.
  225. _loadingMessage = "No conflicts found. Pulling changes...";
  226. Repaint();
  227. GitService.PerformSafePull()
  228. .Then(successMessage =>
  229. {
  230. _infoMessage = successMessage;
  231. EditorUtility.DisplayDialog("Pull Complete", successMessage, "OK");
  232. HandleCompare(); // Refresh view after successful pull
  233. })
  234. .Catch(ex =>
  235. {
  236. _errorMessage = $"Pull Failed: {ex.Message}";
  237. _isLoading = false;
  238. Repaint();
  239. });
  240. }
  241. })
  242. .Catch(ex =>
  243. {
  244. _errorMessage = $"Pull Analysis Failed: {ex.Message}";
  245. _isLoading = false;
  246. Repaint();
  247. });
  248. }
  249. private void HandleResetMultipleFiles(List<string> filePaths)
  250. {
  251. _infoMessage = $"Starting reset for {filePaths.Count} file(s)... This may trigger script compilation.";
  252. Repaint();
  253. SessionState.SetString("BetterGit.ResetQueue", string.Join(";", filePaths));
  254. EditorApplication.delayCall += BetterGitStatePersistence.ContinueInterruptedReset;
  255. }
  256. private void HandleResetAll()
  257. {
  258. if (_changes == null || _changes.Count == 0)
  259. {
  260. EditorUtility.DisplayDialog("No Changes", "There are no local changes to reset.", "OK");
  261. return;
  262. }
  263. var userConfirmed = EditorUtility.DisplayDialog(
  264. "Confirm Reset All",
  265. "Are you sure you want to discard ALL local changes (modified, added, and untracked files)?\n\nThis action cannot be undone.",
  266. "Yes, Discard Everything",
  267. "Cancel");
  268. if (!userConfirmed) return;
  269. _isLoading = true;
  270. _loadingMessage = "Discarding all local changes...";
  271. ClearMessages();
  272. Repaint();
  273. GitService.ResetAllChanges()
  274. .Then(successMessage => {
  275. _infoMessage = successMessage;
  276. HandleCompare(); // Refresh the view to confirm everything is clean
  277. })
  278. .Catch(ex => {
  279. _errorMessage = $"Reset All Failed: {ex.Message}";
  280. _isLoading = false;
  281. Repaint();
  282. });
  283. }
  284. private void HandleForcePull()
  285. {
  286. _isLoading = true;
  287. _loadingMessage = "Attempting to pull and create conflicts...";
  288. ClearMessages();
  289. Repaint();
  290. EditorApplication.LockReloadAssemblies();
  291. GitService.ForcePull()
  292. .Then(_ =>
  293. {
  294. _infoMessage = "Pull resulted in conflicts. Please resolve them below.";
  295. HandleCompare();
  296. })
  297. .Catch(ex =>
  298. {
  299. _errorMessage = $"Forced Pull Failed: {ex.Message}";
  300. _isLoading = false;
  301. Repaint();
  302. })
  303. .Finally(() =>
  304. {
  305. EditorApplication.UnlockReloadAssemblies();
  306. AssetDatabase.Refresh();
  307. });
  308. }
  309. private void HandleCommitAndPush()
  310. {
  311. _isLoading = true;
  312. _loadingMessage = "Staging, committing, and pushing files...";
  313. ClearMessages();
  314. var selectedFiles = _changes.Where(c => c.IsSelectedForCommit).ToList();
  315. var username = BetterGitSettings.Username;
  316. var email = BetterGitSettings.Email;
  317. GitService.CommitAndPush(selectedFiles, _commitMessage, username, email)
  318. .Then(successMessage => {
  319. _commitMessage = ""; // Clear message on success
  320. _changes = null; // Clear the list, forcing a refresh
  321. HandleCompare(); // Automatically refresh to confirm
  322. EditorUtility.DisplayDialog("Commit and Push Complete", successMessage, "OK");
  323. })
  324. .Catch(ex => {
  325. _errorMessage = $"Push Failed: {ex.Message}";
  326. })
  327. .Finally(() => {
  328. _isLoading = false;
  329. // Repaint is handled by the chained HandleCompare call on success
  330. if (!string.IsNullOrEmpty(_errorMessage)) Repaint();
  331. });
  332. }
  333. private void HandleResetFile(GitChange change)
  334. {
  335. if (_isLoading) return;
  336. 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");
  337. if (!userConfirmed) return;
  338. _isLoading = true;
  339. _loadingMessage = $"Resetting {change.FilePath}...";
  340. ClearMessages();
  341. Repaint();
  342. GitService.ResetFileChanges(change)
  343. .Then(successMessage => {
  344. _infoMessage = successMessage;
  345. HandleCompare();
  346. })
  347. .Catch(ex => {
  348. _errorMessage = $"Reset Failed: {ex.Message}";
  349. _isLoading = false;
  350. Repaint();
  351. });
  352. }
  353. private void HandleDiffFile(GitChange change)
  354. {
  355. if (_isLoading) return;
  356. _isLoading = true;
  357. _loadingMessage = $"Launching diff for {change.FilePath}...";
  358. ClearMessages();
  359. Repaint();
  360. GitService.LaunchExternalDiff(change)
  361. .Catch(ex => _errorMessage = ex.Message)
  362. .Finally(() => { _isLoading = false; HandleCompare(); });
  363. }
  364. private void HandleResolveConflict(GitChange change)
  365. {
  366. if (_isLoading) return;
  367. _isLoading = true;
  368. _loadingMessage = $"Opening merge tool for {change.FilePath}...";
  369. ClearMessages();
  370. Repaint();
  371. GitService.LaunchMergeTool(change)
  372. .Then(successMessage =>
  373. {
  374. _infoMessage = successMessage;
  375. })
  376. .Catch(ex =>
  377. {
  378. _errorMessage = $"Resolve Failed: {ex.Message}";
  379. })
  380. .Finally(() =>
  381. {
  382. _isLoading = false;
  383. HandleCompare(); // Always refresh to show the new state
  384. });
  385. }
  386. /// <summary>
  387. /// Draws the multi-column list of changed files.
  388. /// </summary>
  389. private void DrawChangesList()
  390. {
  391. // --- Draw Header ---
  392. EditorGUILayout.BeginHorizontal(EditorStyles.helpBox);
  393. var isConflictMode = _changes.Any(c => c.Status == LibGit2Sharp.ChangeKind.Conflicted);
  394. if (!isConflictMode) EditorGUILayout.LabelField("Commit", GUILayout.Width(45));
  395. else GUILayout.Space(45); // Keep layout consistent
  396. EditorGUILayout.LabelField("Status", GUILayout.Width(50));
  397. EditorGUILayout.LabelField("File Path");
  398. EditorGUILayout.LabelField("Actions", GUILayout.Width(55));
  399. EditorGUILayout.EndHorizontal();
  400. // --- Draw Scrollable List ---
  401. _scrollPosition = EditorGUILayout.BeginScrollView(_scrollPosition, GUILayout.ExpandHeight(true));
  402. for (var i = 0; i < _changes.Count; i++)
  403. {
  404. var change = _changes[i];
  405. // Use the evenRowStyle for every second row (i % 2 == 0), otherwise use no style.
  406. var rowStyle = i % 2 == 0 ? _evenRowStyle : GUIStyle.none;
  407. EditorGUILayout.BeginHorizontal(rowStyle);
  408. change.IsSelectedForCommit = EditorGUILayout.Toggle(change.IsSelectedForCommit, GUILayout.Width(45));
  409. string status;
  410. Color statusColor;
  411. string filePathDisplay;
  412. switch (change.Status)
  413. {
  414. case LibGit2Sharp.ChangeKind.Added:
  415. status = "[+]"; statusColor = Color.green; filePathDisplay = change.FilePath; break;
  416. case LibGit2Sharp.ChangeKind.Deleted:
  417. status = "[-]"; statusColor = Color.red; filePathDisplay = change.FilePath; break;
  418. case LibGit2Sharp.ChangeKind.Modified:
  419. status = "[M]"; statusColor = new Color(1.0f, 0.6f, 0.0f); filePathDisplay = change.FilePath; break;
  420. case LibGit2Sharp.ChangeKind.Renamed:
  421. status = "[R]"; statusColor = new Color(0.6f, 0.6f, 1.0f);
  422. filePathDisplay = $"{change.OldFilePath} -> {change.FilePath}"; break;
  423. case LibGit2Sharp.ChangeKind.Conflicted:
  424. status = "[C]"; statusColor = Color.magenta; filePathDisplay = change.FilePath; break;
  425. case LibGit2Sharp.ChangeKind.Unmodified:
  426. case LibGit2Sharp.ChangeKind.Copied:
  427. case LibGit2Sharp.ChangeKind.Ignored:
  428. case LibGit2Sharp.ChangeKind.Untracked:
  429. case LibGit2Sharp.ChangeKind.TypeChanged:
  430. case LibGit2Sharp.ChangeKind.Unreadable:
  431. default:
  432. status = "[?]"; statusColor = Color.white; filePathDisplay = change.FilePath; break;
  433. }
  434. var originalColor = UnityEngine.GUI.color;
  435. UnityEngine.GUI.color = statusColor;
  436. EditorGUILayout.LabelField(new GUIContent(status, change.Status.ToString()), GUILayout.Width(50));
  437. UnityEngine.GUI.color = originalColor;
  438. EditorGUILayout.LabelField(new GUIContent(filePathDisplay, filePathDisplay));
  439. EditorGUI.BeginDisabledGroup(_isLoading);
  440. if (status == "[C]")
  441. {
  442. if (GUILayout.Button("Resolve", GUILayout.Width(70))) { EditorApplication.delayCall += () => HandleResolveConflict(change); }
  443. }
  444. else
  445. {
  446. if (GUILayout.Button("Diff", GUILayout.Width(45))) EditorApplication.delayCall += () => HandleDiffFile(change);
  447. }
  448. if (GUILayout.Button(new GUIContent("Reset", "Revert changes for this file"), GUILayout.Width(55)))
  449. {
  450. EditorApplication.delayCall += () => HandleResetFile(change);
  451. }
  452. EditorGUI.EndDisabledGroup();
  453. EditorGUILayout.EndHorizontal();
  454. }
  455. EditorGUILayout.EndScrollView();
  456. }
  457. private void DrawCommitSection()
  458. {
  459. EditorGUILayout.Space(10);
  460. var isConflictMode = _changes.Any(c => c.Status == LibGit2Sharp.ChangeKind.Conflicted);
  461. if (isConflictMode)
  462. {
  463. EditorGUILayout.HelpBox("You must resolve all conflicts before you can commit.", MessageType.Warning);
  464. return;
  465. }
  466. EditorGUILayout.LabelField("Commit & Push", EditorStyles.boldLabel);
  467. _commitMessage = EditorGUILayout.TextArea(_commitMessage, GUILayout.Height(60), GUILayout.ExpandWidth(true));
  468. var isPushDisabled = string.IsNullOrWhiteSpace(_commitMessage) || !_changes.Any(c => c.IsSelectedForCommit);
  469. EditorGUI.BeginDisabledGroup(isPushDisabled);
  470. if (GUILayout.Button("Commit & Push Selected Files", GUILayout.Height(40)))
  471. {
  472. HandleCommitAndPush();
  473. }
  474. EditorGUI.EndDisabledGroup();
  475. if (isPushDisabled)
  476. {
  477. EditorGUILayout.HelpBox("Please enter a commit message and select at least one file.", MessageType.Warning);
  478. }
  479. }
  480. }
  481. }