GitExecutors.cs 20 KB

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