GitExecutors.cs 22 KB

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