GitExecutors.cs 24 KB

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