GitExecutors.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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. if (changeToReset.Status == ChangeKind.Added)
  153. {
  154. Commands.Unstage(repo, changeToReset.FilePath);
  155. var fullPath = Path.Combine(ProjectRoot, changeToReset.FilePath);
  156. if (File.Exists(fullPath))
  157. {
  158. File.Delete(fullPath);
  159. }
  160. }
  161. else if (changeToReset.Status == ChangeKind.Renamed)
  162. {
  163. Commands.Unstage(repo, changeToReset.FilePath);
  164. var newFullPath = Path.Combine(ProjectRoot, changeToReset.FilePath);
  165. if (File.Exists(newFullPath)) File.Delete(newFullPath);
  166. repo.CheckoutPaths(repo.Head.Tip.Sha, new[] { changeToReset.OldFilePath }, new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force });
  167. }
  168. else
  169. {
  170. repo.CheckoutPaths(repo.Head.Tip.Sha, new[] { changeToReset.FilePath }, new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force });
  171. }
  172. resolve($"Successfully reset changes for '{changeToReset.FilePath}'");
  173. }
  174. catch (Exception ex)
  175. {
  176. reject(ex);
  177. }
  178. }
  179. public static async void LaunchExternalDiffExecutor(Action<string> resolve, Action<Exception> reject, GitChange change)
  180. {
  181. string fileAPath = null; // Before
  182. string fileBPath = null; // After
  183. try
  184. {
  185. using var repo = new Repository(ProjectRoot);
  186. string GetFileContentFromHead(string path)
  187. {
  188. var blob = repo.Head.Tip[path]?.Target as Blob;
  189. return blob?.GetContentText() ?? "";
  190. }
  191. string CreateTempFile(string originalPath, string content)
  192. {
  193. var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + Path.GetExtension(originalPath));
  194. File.WriteAllText(tempPath, content);
  195. return tempPath;
  196. }
  197. switch (change.Status)
  198. {
  199. case ChangeKind.Added:
  200. fileAPath = CreateTempFile(change.FilePath, "");
  201. fileBPath = Path.Combine(ProjectRoot, change.FilePath);
  202. break;
  203. case ChangeKind.Deleted:
  204. fileAPath = CreateTempFile(change.FilePath, GetFileContentFromHead(change.FilePath));
  205. fileBPath = CreateTempFile(change.FilePath, "");
  206. break;
  207. case ChangeKind.Renamed:
  208. fileAPath = CreateTempFile(change.OldFilePath, GetFileContentFromHead(change.OldFilePath));
  209. fileBPath = Path.Combine(ProjectRoot, change.FilePath);
  210. break;
  211. default: // Modified
  212. fileAPath = CreateTempFile(change.FilePath, GetFileContentFromHead(change.FilePath));
  213. fileBPath = Path.Combine(ProjectRoot, change.FilePath);
  214. break;
  215. }
  216. await Cli.Wrap(GitCommand.FindVsCodeExecutable())
  217. .WithArguments(args => args.Add("--diff").Add(fileAPath).Add(fileBPath))
  218. .ExecuteAsync();
  219. resolve("Launched external diff tool.");
  220. }
  221. catch(Win32Exception ex)
  222. {
  223. reject(new Exception("Could not launch VS Code. Ensure it is installed and the 'code' command is available in your system's PATH.", ex));
  224. }
  225. catch(Exception ex)
  226. {
  227. reject(ex);
  228. }
  229. finally
  230. {
  231. try
  232. {
  233. if (fileAPath != null && fileAPath.Contains(Path.GetTempPath()) && File.Exists(fileAPath)) File.Delete(fileAPath);
  234. if (fileBPath != null && fileBPath.Contains(Path.GetTempPath()) && File.Exists(fileBPath)) File.Delete(fileBPath);
  235. }
  236. catch(Exception cleanupEx)
  237. {
  238. Debug.LogError($"Failed to clean up temporary diff files: {cleanupEx.Message}");
  239. }
  240. }
  241. }
  242. public static void FileLevelConflictCheckExecutor(Action<PullAnalysisResult> resolve, Action<Exception> reject)
  243. {
  244. try
  245. {
  246. using var repo = new Repository(ProjectRoot);
  247. var result = AnalyzePullConflictsInternal(repo).Result;
  248. resolve(result);
  249. }
  250. catch (Exception ex)
  251. {
  252. reject(ex);
  253. }
  254. }
  255. private static Task<PullAnalysisResult> AnalyzePullConflictsInternal(Repository repo)
  256. {
  257. var remote = repo.Network.Remotes["origin"];
  258. if (remote == null) throw new Exception("No remote named 'origin' was found.");
  259. Commands.Fetch(repo, remote.Name, Array.Empty<string>(), new FetchOptions { CertificateCheck = (_,_,_) => true }, null);
  260. var localBranch = repo.Head;
  261. var remoteBranch = repo.Head.TrackedBranch;
  262. if (remoteBranch == null) throw new Exception("Current branch is not tracking a remote branch.");
  263. var mergeBase = repo.ObjectDatabase.FindMergeBase(localBranch.Tip, remoteBranch.Tip);
  264. if (mergeBase == null) throw new Exception("Could not find a common ancestor.");
  265. var theirChanges = new HashSet<string>(repo.Diff.Compare<TreeChanges>(mergeBase.Tree, remoteBranch.Tip.Tree).Select(c => c.Path));
  266. var ourChanges = new HashSet<string>(repo.Diff.Compare<TreeChanges>(mergeBase.Tree, localBranch.Tip.Tree).Select(c => c.Path));
  267. foreach (var statusEntry in repo.RetrieveStatus()) ourChanges.Add(statusEntry.FilePath);
  268. return Task.FromResult(new PullAnalysisResult(ourChanges.Where(theirChanges.Contains).ToList()));
  269. }
  270. public static void SafePullExecutor(Action<string> resolve, Action<Exception> reject)
  271. {
  272. try
  273. {
  274. using var repo = new Repository(ProjectRoot);
  275. var signature = new Signature("Better Git Tool", "bettergit@example.com", DateTimeOffset.Now);
  276. var pullOptions = new PullOptions { FetchOptions = new FetchOptions { CertificateCheck = (_,_,_) => true } };
  277. var mergeResult = Commands.Pull(repo, signature, pullOptions);
  278. resolve(mergeResult.Status == MergeStatus.UpToDate ? "Already up-to-date." : $"Pull successful. Status: {mergeResult.Status}");
  279. }
  280. catch (Exception ex)
  281. {
  282. reject(ex);
  283. }
  284. }
  285. public static async void ForcePullExecutor(Action<string> resolve, Action<Exception> reject)
  286. {
  287. var log = new StringBuilder();
  288. var hasStashed = false;
  289. try
  290. {
  291. using (var repo = new Repository(ProjectRoot))
  292. {
  293. if (repo.RetrieveStatus().IsDirty)
  294. {
  295. await GitCommand.RunAsync(log, new[] { "stash", "push", "-u", "-m", "BetterGit-WIP-Pull" }, 0, 141);
  296. hasStashed = true;
  297. }
  298. }
  299. await GitCommand.RunAsync(log, new[] { "pull", "--no-rebase" }, 0, 1, 141);
  300. if (hasStashed)
  301. {
  302. await GitCommand.RunAsync(log, new[] { "stash", "pop" }, 0, 1, 141);
  303. }
  304. resolve(log.ToString());
  305. }
  306. catch (Exception ex)
  307. {
  308. if (hasStashed)
  309. {
  310. try
  311. {
  312. await GitCommand.RunAsync(new StringBuilder(), new[] { "stash", "pop" }, 0, 1, 141);
  313. }
  314. catch (Exception exception)
  315. {
  316. log.AppendLine($"Fatal Error trying to pop stash after a failed pull: {exception.Message}");
  317. }
  318. }
  319. log.AppendLine("\n--- PULL FAILED ---");
  320. log.AppendLine(ex.ToString());
  321. reject(new Exception(log.ToString()));
  322. }
  323. }
  324. public static async void LaunchMergeToolExecutor(Action<string> resolve, Action<Exception> reject, GitChange change)
  325. {
  326. try
  327. {
  328. if (change.FilePath == null)
  329. {
  330. reject(new Exception("Could not find file path."));
  331. return;
  332. }
  333. var fileExtension = Path.GetExtension(change.FilePath).ToLower();
  334. if (fileExtension is ".prefab" or ".unity")
  335. {
  336. reject(new Exception("Cannot auto-resolve conflicts for binary files. Please use an external merge tool."));
  337. return;
  338. }
  339. await Cli.Wrap(GitCommand.FindVsCodeExecutable())
  340. .WithArguments(args => args.Add("--wait").Add(change.FilePath))
  341. .WithWorkingDirectory(ProjectRoot)
  342. .ExecuteAsync();
  343. var fullPath = Path.Combine(ProjectRoot, change.FilePath);
  344. var fileContent = await File.ReadAllTextAsync(fullPath);
  345. if (fileContent.Contains("<<<<<<<"))
  346. {
  347. resolve($"Conflict in '{change.FilePath}' was not resolved. Please try again.");
  348. return;
  349. }
  350. await GitCommand.RunAsync(new StringBuilder(), new[] { "add", change.FilePath });
  351. await GitCommand.RunAsync(new StringBuilder(), new[] { "reset", "HEAD", change.FilePath });
  352. resolve($"Successfully resolved conflict in '{change.FilePath}'. The file is now modified and ready for review.");
  353. }
  354. catch (Win32Exception ex)
  355. {
  356. reject(new Exception("Could not launch VS Code. Ensure it is installed and the 'code' command is available in your system's PATH.", ex));
  357. }
  358. catch (Exception ex)
  359. {
  360. reject(ex);
  361. }
  362. }
  363. public static async void UnstageAllFilesIfSafeExecutor(Action<bool> resolve, Action<Exception> reject)
  364. {
  365. try
  366. {
  367. using var repo = new Repository(ProjectRoot);
  368. if (repo.Index.Conflicts.Any())
  369. {
  370. resolve(false);
  371. return;
  372. }
  373. var stagedFiles = repo.RetrieveStatus().Count(s => s.State is
  374. FileStatus.NewInIndex or
  375. FileStatus.ModifiedInIndex or
  376. FileStatus.DeletedFromIndex or
  377. FileStatus.RenamedInIndex or
  378. FileStatus.TypeChangeInIndex);
  379. if (stagedFiles == 0)
  380. {
  381. resolve(false);
  382. return;
  383. }
  384. await GitCommand.RunAsync(new StringBuilder(), new[] { "reset" });
  385. resolve(true);
  386. }
  387. catch (Exception ex)
  388. {
  389. reject(ex);
  390. }
  391. }
  392. public static async void ResetAllChangesExecutor(Action<string> resolve, Action<Exception> reject)
  393. {
  394. try
  395. {
  396. var log = new StringBuilder();
  397. await GitCommand.RunAsync(log, new[] { "reset", "--hard", "HEAD" });
  398. await GitCommand.RunAsync(log, new[] { "clean", "-fd" });
  399. resolve("Successfully discarded all local changes.");
  400. }
  401. catch (Exception ex)
  402. {
  403. reject(ex);
  404. }
  405. }
  406. }
  407. }