GitExecutors.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. // Copyright (c) 2025 TerraByte Inc.
  2. //
  3. // A new internal class that contains the concrete implementation logic for
  4. // all Git operations. This separates the "how" from the "what" defined
  5. // in the public GitService API.
  6. using System;
  7. using System.IO;
  8. using System.Linq;
  9. using UnityEngine;
  10. using LibGit2Sharp;
  11. using System.Text;
  12. using System.Globalization;
  13. using System.ComponentModel;
  14. using UnityEngine.Scripting;
  15. using System.Threading.Tasks;
  16. using Terra.Arbitrator.Settings;
  17. using System.Collections.Generic;
  18. namespace Terra.Arbitrator.Services
  19. {
  20. /// <summary>
  21. /// A simple data container for branch information.
  22. /// </summary>
  23. [Preserve]
  24. public class BranchData
  25. {
  26. public string CurrentBranch { get; set; }
  27. public List<string> AllBranches { get; set; }
  28. }
  29. /// <summary>
  30. /// Contains the promise executor methods for all Git operations.
  31. /// This is an internal implementation detail and is not exposed publicly.
  32. /// </summary>
  33. [Preserve]
  34. internal static class GitExecutors
  35. {
  36. private static string _projectRoot;
  37. private static string ProjectRoot => _projectRoot ??= MainThreadDataCache.ProjectRoot;
  38. public static void GetBranchDataExecutor(Action<BranchData> resolve, Action<Exception> reject)
  39. {
  40. try
  41. {
  42. using var repo = new Repository(ProjectRoot);
  43. var data = new BranchData
  44. {
  45. CurrentBranch = repo.Head.FriendlyName,
  46. AllBranches = repo.Branches
  47. .Where(b => !b.FriendlyName.Contains("HEAD"))
  48. .Select(b => b.FriendlyName.Replace("origin/", ""))
  49. .Distinct()
  50. .OrderBy(name => name)
  51. .ToList()
  52. };
  53. resolve(data);
  54. }
  55. catch(Exception ex)
  56. {
  57. reject(ex);
  58. }
  59. }
  60. public static async void SwitchBranchExecutor(Action<string> resolve, Action<Exception> reject, string branchName)
  61. {
  62. try
  63. {
  64. var log = new StringBuilder();
  65. await GitCommand.RunGitAsync(log, new[] { "checkout", branchName });
  66. resolve($"Successfully switched to branch '{branchName}'.");
  67. }
  68. catch (Exception ex)
  69. {
  70. reject(ex);
  71. }
  72. }
  73. public static async void ResetAndSwitchBranchExecutor(Action<string> resolve, Action<Exception> reject, string branchName)
  74. {
  75. try
  76. {
  77. var log = new StringBuilder();
  78. await GitCommand.RunGitAsync(log, new[] { "reset", "--hard", "HEAD" });
  79. await GitCommand.RunGitAsync(log, new[] { "clean", "-fd" });
  80. await GitCommand.RunGitAsync(log, new[] { "checkout", branchName });
  81. resolve($"Discarded local changes and switched to branch '{branchName}'.");
  82. }
  83. catch (Exception ex)
  84. {
  85. reject(ex);
  86. }
  87. }
  88. /// <summary>
  89. /// Synchronous helper to get a GitChange object for a single file.
  90. /// This is public so it can be called by the GitService wrapper.
  91. /// </summary>
  92. public static GitChange GetChangeForFile(string filePath)
  93. {
  94. try
  95. {
  96. using var repo = new Repository(ProjectRoot);
  97. if (repo.Index.Conflicts.Any(c => c.Ours.Path == filePath))
  98. {
  99. return new GitChange(filePath, null, ChangeKind.Conflicted);
  100. }
  101. var statusEntry = repo.RetrieveStatus(filePath);
  102. return statusEntry switch
  103. {
  104. FileStatus.NewInWorkdir or FileStatus.NewInIndex => new GitChange(filePath, null, ChangeKind.Added),
  105. FileStatus.ModifiedInWorkdir or FileStatus.ModifiedInIndex => new GitChange(filePath, null, ChangeKind.Modified),
  106. FileStatus.DeletedFromWorkdir or FileStatus.DeletedFromIndex => new GitChange(filePath, null, ChangeKind.Deleted),
  107. FileStatus.RenamedInWorkdir or FileStatus.RenamedInIndex =>
  108. new GitChange(filePath, null, ChangeKind.Renamed),
  109. _ => null
  110. };
  111. }
  112. catch { return null; } // Suppress errors if repo is in a unique state
  113. }
  114. // --- Promise Executor Implementations ---
  115. public static async void GetUpstreamAheadByExecutor(Action<int?> resolve, Action<Exception> reject, Action<float, string> onProgress)
  116. {
  117. try
  118. {
  119. var progressReporter = new Progress<string>(line => ParseProgress(line, onProgress));
  120. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "fetch", "--progress" }, progressReporter);
  121. using var repo = new Repository(ProjectRoot);
  122. resolve(repo.Head.TrackingDetails.BehindBy);
  123. }
  124. catch (Exception ex)
  125. {
  126. if (ex.Message.Contains("is not tracking a remote branch"))
  127. {
  128. resolve(null);
  129. }
  130. else
  131. {
  132. reject(ex);
  133. }
  134. }
  135. }
  136. public static void GetLocalStatusExecutor(Action<List<GitChange>> resolve, Action<Exception> reject)
  137. {
  138. try
  139. {
  140. var changes = new List<GitChange>();
  141. using var repo = new Repository(ProjectRoot);
  142. var conflictedPaths = new HashSet<string>(repo.Index.Conflicts.Select(c => c.Ours.Path));
  143. var statusOptions = new StatusOptions
  144. {
  145. IncludeUntracked = true,
  146. RecurseUntrackedDirs = true,
  147. DetectRenamesInIndex = true,
  148. DetectRenamesInWorkDir = true
  149. };
  150. foreach (var entry in repo.RetrieveStatus(statusOptions))
  151. {
  152. if (conflictedPaths.Contains(entry.FilePath))
  153. {
  154. if (changes.All(c => c.FilePath != entry.FilePath))
  155. {
  156. changes.Add(new GitChange(entry.FilePath, null, ChangeKind.Conflicted));
  157. }
  158. continue;
  159. }
  160. switch(entry.State)
  161. {
  162. case FileStatus.NewInWorkdir:
  163. case FileStatus.NewInIndex:
  164. changes.Add(new GitChange(entry.FilePath, null, ChangeKind.Added));
  165. break;
  166. case FileStatus.ModifiedInWorkdir:
  167. case FileStatus.ModifiedInIndex:
  168. changes.Add(new GitChange(entry.FilePath, null, ChangeKind.Modified));
  169. break;
  170. case FileStatus.DeletedFromWorkdir:
  171. case FileStatus.DeletedFromIndex:
  172. changes.Add(new GitChange(entry.FilePath, null, ChangeKind.Deleted));
  173. break;
  174. case FileStatus.RenamedInWorkdir:
  175. case FileStatus.RenamedInIndex:
  176. var renameDetails = entry.HeadToIndexRenameDetails ?? entry.IndexToWorkDirRenameDetails;
  177. changes.Add(renameDetails != null ? new GitChange(renameDetails.NewFilePath, renameDetails.OldFilePath, ChangeKind.Renamed)
  178. : new GitChange(entry.FilePath, "Unknown", ChangeKind.Renamed));
  179. break;
  180. }
  181. }
  182. resolve(changes);
  183. }
  184. catch (Exception ex)
  185. {
  186. reject(ex);
  187. }
  188. }
  189. public static async void CommitAndPushExecutor(Action<string> resolve, Action<Exception> reject, List<GitChange> changesToCommit, string commitMessage, string username, string email, Action<float, string> onProgress)
  190. {
  191. try
  192. {
  193. if (string.IsNullOrWhiteSpace(email))
  194. {
  195. throw new Exception("Author email is missing. Please set your email address in Project Settings > Better Git.");
  196. }
  197. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "fetch" });
  198. using (var repo = new Repository(ProjectRoot))
  199. {
  200. var remote = repo.Network.Remotes["origin"];
  201. if (remote == null) throw new Exception("No remote named 'origin' found.");
  202. var fetchOptions = new FetchOptions { CertificateCheck = (_, _, _) => true };
  203. Commands.Fetch(repo, remote.Name, Array.Empty<string>(), fetchOptions, "Arbitrator pre-push fetch");
  204. var trackingDetails = repo.Head.TrackingDetails;
  205. if (trackingDetails.BehindBy > 0)
  206. {
  207. throw new Exception($"Push aborted. There are {trackingDetails.BehindBy.Value} incoming changes on the remote. Please pull first.");
  208. }
  209. var pathsToStage = new List<string>();
  210. foreach (var change in changesToCommit)
  211. {
  212. switch (change.Status)
  213. {
  214. case ChangeKind.Deleted:
  215. Commands.Remove(repo, change.FilePath);
  216. break;
  217. case ChangeKind.Renamed:
  218. Commands.Remove(repo, change.OldFilePath);
  219. pathsToStage.Add(change.FilePath);
  220. break;
  221. default:
  222. pathsToStage.Add(change.FilePath);
  223. break;
  224. }
  225. }
  226. if (pathsToStage.Any()) Commands.Stage(repo, pathsToStage);
  227. var status = repo.RetrieveStatus();
  228. if (!status.IsDirty) throw new Exception("No effective changes were staged to commit.");
  229. var author = new Signature(username, email, DateTimeOffset.Now);
  230. repo.Commit(commitMessage, author, author);
  231. }
  232. var progressReporter = new Progress<string>(line => ParseProgress(line, onProgress));
  233. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "push", "--progress" }, progressReporter, 0, 141);
  234. resolve("Successfully committed and pushed changes!");
  235. }
  236. catch (Exception ex)
  237. {
  238. var errorMessage = ex.InnerException?.Message ?? ex.Message;
  239. reject(new Exception(errorMessage));
  240. }
  241. }
  242. private static void ParseProgress(string line, Action<float, string> onProgress)
  243. {
  244. if (onProgress == null || string.IsNullOrWhiteSpace(line)) return;
  245. line = line.Trim();
  246. var parts = line.Split(new[] { ':' }, 2);
  247. if (parts.Length < 2) return;
  248. var action = parts[0];
  249. var progressPart = parts[1];
  250. var percentIndex = progressPart.IndexOf('%');
  251. if (percentIndex == -1) return;
  252. var percentString = progressPart[..percentIndex].Trim();
  253. if (!float.TryParse(percentString, NumberStyles.Any, CultureInfo.InvariantCulture, out var percentage)) return;
  254. var progressValue = percentage / 100.0f;
  255. onProgress(progressValue, $"{action}...");
  256. }
  257. public static void ResetFileExecutor(Action<string> resolve, Action<Exception> reject, GitChange changeToReset)
  258. {
  259. try
  260. {
  261. using var repo = new Repository(ProjectRoot);
  262. switch (changeToReset.Status)
  263. {
  264. case ChangeKind.Added:
  265. {
  266. Commands.Unstage(repo, changeToReset.FilePath);
  267. var fullPath = Path.Combine(ProjectRoot, changeToReset.FilePath);
  268. if (File.Exists(fullPath))
  269. {
  270. File.Delete(fullPath);
  271. }
  272. break;
  273. }
  274. case ChangeKind.Renamed:
  275. {
  276. Commands.Unstage(repo, changeToReset.FilePath);
  277. var newFullPath = Path.Combine(ProjectRoot, changeToReset.FilePath);
  278. if (File.Exists(newFullPath)) File.Delete(newFullPath);
  279. repo.CheckoutPaths(repo.Head.Tip.Sha, new[] { changeToReset.OldFilePath }, new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force });
  280. break;
  281. }
  282. default:
  283. repo.CheckoutPaths(repo.Head.Tip.Sha, new[] { changeToReset.FilePath }, new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force });
  284. break;
  285. }
  286. resolve($"Successfully reset changes for '{changeToReset.FilePath}'");
  287. }
  288. catch (Exception ex)
  289. {
  290. reject(ex);
  291. }
  292. }
  293. public static async void LaunchExternalDiffExecutor(Action<string> resolve, Action<Exception> reject, GitChange change)
  294. {
  295. string fileAPath = null; // Before
  296. string fileBPath = null; // After
  297. try
  298. {
  299. using var repo = new Repository(ProjectRoot);
  300. string GetFileContentFromHead(string path)
  301. {
  302. var blob = repo.Head.Tip[path]?.Target as Blob;
  303. return blob?.GetContentText() ?? "";
  304. }
  305. string CreateTempFile(string originalPath, string content)
  306. {
  307. var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + Path.GetExtension(originalPath));
  308. File.WriteAllText(tempPath, content);
  309. return tempPath;
  310. }
  311. switch (change.Status)
  312. {
  313. case ChangeKind.Added:
  314. fileAPath = CreateTempFile(change.FilePath, "");
  315. fileBPath = Path.Combine(ProjectRoot, change.FilePath);
  316. break;
  317. case ChangeKind.Deleted:
  318. fileAPath = CreateTempFile(change.FilePath, GetFileContentFromHead(change.FilePath));
  319. fileBPath = CreateTempFile(change.FilePath, "");
  320. break;
  321. case ChangeKind.Renamed:
  322. fileAPath = CreateTempFile(change.OldFilePath, GetFileContentFromHead(change.OldFilePath));
  323. fileBPath = Path.Combine(ProjectRoot, change.FilePath);
  324. break;
  325. default: // Modified
  326. fileAPath = CreateTempFile(change.FilePath, GetFileContentFromHead(change.FilePath));
  327. fileBPath = Path.Combine(ProjectRoot, change.FilePath);
  328. break;
  329. }
  330. await GitCommand.RunVsCodeAsync(new StringBuilder(), new[] { "--diff", fileAPath, fileBPath });
  331. resolve("Launched external diff tool.");
  332. }
  333. catch(Win32Exception ex)
  334. {
  335. reject(new Exception("Could not launch VS Code. Ensure it is installed and the 'code' command is available in your system's PATH.", ex));
  336. }
  337. catch(Exception ex)
  338. {
  339. reject(ex);
  340. }
  341. finally
  342. {
  343. try
  344. {
  345. if (fileAPath != null && fileAPath.Contains(Path.GetTempPath()) && File.Exists(fileAPath)) File.Delete(fileAPath);
  346. if (fileBPath != null && fileBPath.Contains(Path.GetTempPath()) && File.Exists(fileBPath)) File.Delete(fileBPath);
  347. }
  348. catch(Exception cleanupEx)
  349. {
  350. Debug.LogError($"Failed to clean up temporary diff files: {cleanupEx.Message}");
  351. }
  352. }
  353. }
  354. public static void FileLevelConflictCheckExecutor(Action<PullAnalysisResult> resolve, Action<Exception> reject)
  355. {
  356. try
  357. {
  358. using var repo = new Repository(ProjectRoot);
  359. var result = AnalyzePullConflictsInternal(repo).Result;
  360. resolve(result);
  361. }
  362. catch (Exception ex)
  363. {
  364. reject(ex);
  365. }
  366. }
  367. private static Task<PullAnalysisResult> AnalyzePullConflictsInternal(Repository repo)
  368. {
  369. var remote = repo.Network.Remotes["origin"];
  370. if (remote == null) throw new Exception("No remote named 'origin' was found.");
  371. Commands.Fetch(repo, remote.Name, Array.Empty<string>(), new FetchOptions { CertificateCheck = (_,_,_) => true }, null);
  372. var localBranch = repo.Head;
  373. var remoteBranch = repo.Head.TrackedBranch;
  374. if (remoteBranch == null) throw new Exception("Current branch is not tracking a remote branch.");
  375. var mergeBase = repo.ObjectDatabase.FindMergeBase(localBranch.Tip, remoteBranch.Tip);
  376. if (mergeBase == null) throw new Exception("Could not find a common ancestor.");
  377. var theirChanges = new HashSet<string>(repo.Diff.Compare<TreeChanges>(mergeBase.Tree, remoteBranch.Tip.Tree).Select(c => c.Path));
  378. var ourChanges = new HashSet<string>(repo.Diff.Compare<TreeChanges>(mergeBase.Tree, localBranch.Tip.Tree).Select(c => c.Path));
  379. foreach (var statusEntry in repo.RetrieveStatus()) ourChanges.Add(statusEntry.FilePath);
  380. return Task.FromResult(new PullAnalysisResult(ourChanges.Where(theirChanges.Contains).ToList()));
  381. }
  382. public static void SafePullExecutor(Action<string> resolve, Action<Exception> reject)
  383. {
  384. try
  385. {
  386. using var repo = new Repository(ProjectRoot);
  387. var signature = new Signature("Better Git Tool", "bettergit@letsterra.com", DateTimeOffset.Now);
  388. var pullOptions = new PullOptions { FetchOptions = new FetchOptions { CertificateCheck = (_,_,_) => true } };
  389. var mergeResult = Commands.Pull(repo, signature, pullOptions);
  390. resolve(mergeResult.Status == MergeStatus.UpToDate ? "Already up-to-date." : $"Pull successful. Status: {mergeResult.Status}");
  391. }
  392. catch (Exception ex)
  393. {
  394. reject(ex);
  395. }
  396. }
  397. public static async void ForcePullExecutor(Action<string> resolve, Action<Exception> reject)
  398. {
  399. var log = new StringBuilder();
  400. var hasStashed = false;
  401. try
  402. {
  403. using (var repo = new Repository(ProjectRoot))
  404. {
  405. if (repo.RetrieveStatus().IsDirty)
  406. {
  407. await GitCommand.RunGitAsync(log, new[] { "stash", "push", "-u", "-m", "BetterGit-WIP-Pull" }, 0, 141);
  408. hasStashed = true;
  409. }
  410. }
  411. await GitCommand.RunGitAsync(log, new[] { "pull", "--no-rebase" }, 0, 1, 141);
  412. if (hasStashed)
  413. {
  414. await GitCommand.RunGitAsync(log, new[] { "stash", "pop" }, 0, 1, 141);
  415. await GitCommand.RunGitAsync(log, new[] { "stash", "drop" }, 0, 141);
  416. }
  417. resolve(log.ToString());
  418. }
  419. catch (Exception ex)
  420. {
  421. if (hasStashed)
  422. {
  423. try
  424. {
  425. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "stash", "pop" }, 0, 1, 141);
  426. }
  427. catch (Exception exception)
  428. {
  429. log.AppendLine($"Fatal Error trying to pop stash after a failed pull: {exception.Message}");
  430. }
  431. }
  432. log.AppendLine("\n--- PULL FAILED ---");
  433. log.AppendLine(ex.ToString());
  434. reject(new Exception(log.ToString()));
  435. }
  436. }
  437. public static async void LaunchMergeToolExecutor(Action<string> resolve, Action<Exception> reject, GitChange change)
  438. {
  439. try
  440. {
  441. if (change.FilePath == null)
  442. {
  443. reject(new Exception("Could not find file path."));
  444. return;
  445. }
  446. var fileExtension = Path.GetExtension(change.FilePath).ToLower();
  447. if (fileExtension is ".prefab" or ".unity")
  448. {
  449. reject(new Exception("Cannot auto-resolve conflicts for binary files. Please use an external merge tool."));
  450. return;
  451. }
  452. await GitCommand.RunVsCodeAsync(new StringBuilder(), new[] { "--wait", change.FilePath }, 0, 141);
  453. var fullPath = Path.Combine(ProjectRoot, change.FilePath);
  454. var fileContent = await File.ReadAllTextAsync(fullPath);
  455. if (fileContent.Contains("<<<<<<<"))
  456. {
  457. resolve($"Conflict in '{change.FilePath}' was not resolved. Please try again.");
  458. return;
  459. }
  460. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "add", change.FilePath });
  461. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "reset", "HEAD", change.FilePath });
  462. resolve($"Successfully resolved conflict in '{change.FilePath}'. The file is now modified and ready for review.");
  463. }
  464. catch (Win32Exception ex)
  465. {
  466. reject(new Exception("Could not launch VS Code. Ensure it is installed and the 'code' command is available in your system's PATH.", ex));
  467. }
  468. catch (Exception ex)
  469. {
  470. reject(ex);
  471. }
  472. }
  473. public static async void UnstageAllFilesIfSafeExecutor(Action<bool> resolve, Action<Exception> reject)
  474. {
  475. try
  476. {
  477. using var repo = new Repository(ProjectRoot);
  478. if (repo.Index.Conflicts.Any())
  479. {
  480. resolve(false);
  481. return;
  482. }
  483. var stagedFiles = repo.RetrieveStatus().Count(s => s.State is
  484. FileStatus.NewInIndex or
  485. FileStatus.ModifiedInIndex or
  486. FileStatus.DeletedFromIndex or
  487. FileStatus.RenamedInIndex or
  488. FileStatus.TypeChangeInIndex);
  489. if (stagedFiles == 0)
  490. {
  491. resolve(false);
  492. return;
  493. }
  494. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "reset" });
  495. resolve(true);
  496. }
  497. catch (Exception ex)
  498. {
  499. reject(ex);
  500. }
  501. }
  502. public static async void ResetAllChangesExecutor(Action<string> resolve, Action<Exception> reject)
  503. {
  504. try
  505. {
  506. var log = new StringBuilder();
  507. await GitCommand.RunGitAsync(log, new[] { "reset", "--hard", "HEAD" });
  508. await GitCommand.RunGitAsync(log, new[] { "clean", "-fd" });
  509. resolve("Successfully discarded all local changes.");
  510. }
  511. catch (Exception ex)
  512. {
  513. reject(ex);
  514. }
  515. }
  516. }
  517. }