GitExecutors.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  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 System.Text;
  11. using LibGit2Sharp;
  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. using System.Text.RegularExpressions;
  19. namespace Terra.Arbitrator.Services
  20. {
  21. /// <summary>
  22. /// A simple data container for branch information.
  23. /// </summary>
  24. [Preserve]
  25. public class BranchData
  26. {
  27. public string CurrentBranch { get; set; }
  28. public List<string> AllBranches { get; set; }
  29. }
  30. /// <summary>
  31. /// Contains the promise executor methods for all Git operations.
  32. /// This is an internal implementation detail and is not exposed publicly.
  33. /// </summary>
  34. [Preserve]
  35. internal static class GitExecutors
  36. {
  37. private static string _projectRoot;
  38. private static string ProjectRoot => _projectRoot ??= MainThreadDataCache.ProjectRoot;
  39. private const string StashMessage = "Better Git Stash";
  40. private static string GetAuthenticatedRemoteUrl()
  41. {
  42. var authUsername = BetterGitSettings.AuthUsername;
  43. var authPassword = BetterGitSettings.AuthPassword;
  44. if (string.IsNullOrEmpty(authUsername) || string.IsNullOrEmpty(authPassword))
  45. {
  46. return "origin";
  47. }
  48. using var repo = new Repository(ProjectRoot);
  49. var remote = repo.Network.Remotes["origin"];
  50. if (remote == null) throw new Exception("No remote named 'origin' found.");
  51. var originalUrl = remote.Url;
  52. var authenticatedUrl = Regex.Replace(originalUrl,
  53. "://",
  54. $"://{Uri.EscapeDataString(authUsername)}:{Uri.EscapeDataString(authPassword)}@");
  55. return authenticatedUrl;
  56. }
  57. public static void HasStashExecutor(Action<bool> resolve, Action<Exception> reject)
  58. {
  59. try
  60. {
  61. using var repo = new Repository(ProjectRoot);
  62. var stashExists = repo.Stashes.Any(s => s.Message.Contains(StashMessage));
  63. resolve(stashExists);
  64. }
  65. catch (Exception ex)
  66. {
  67. reject(ex);
  68. }
  69. }
  70. public static async void CreateOrOverwriteStashExecutor(Action<string> resolve, Action<Exception> reject, List<GitChange> changes)
  71. {
  72. try
  73. {
  74. var log = new StringBuilder();
  75. using (var repo = new Repository(ProjectRoot))
  76. {
  77. var existingStash = repo.Stashes.FirstOrDefault(s => s.Message.Contains(StashMessage));
  78. if (existingStash != null)
  79. {
  80. repo.Stashes.Remove(repo.Stashes.ToList().IndexOf(existingStash));
  81. log.AppendLine("Dropped existing 'Better Git Stash'.");
  82. }
  83. }
  84. var untrackedFiles = new List<string>();
  85. using (var repo = new Repository(ProjectRoot))
  86. {
  87. foreach (var change in changes)
  88. {
  89. var statusEntry = repo.RetrieveStatus(change.FilePath);
  90. if (statusEntry == FileStatus.NewInWorkdir)
  91. {
  92. untrackedFiles.Add(change.FilePath);
  93. }
  94. }
  95. }
  96. if (untrackedFiles.Any())
  97. {
  98. foreach (var file in untrackedFiles)
  99. {
  100. await GitCommand.RunGitAsync(log, new[] { "add", file });
  101. }
  102. log.AppendLine($"Staged {untrackedFiles.Count} untracked files.");
  103. }
  104. var allFiles = changes.Select(c => c.FilePath).ToList();
  105. if (allFiles.Any())
  106. {
  107. var stashArgs = new List<string> { "stash", "push", "-m", StashMessage, "--" };
  108. stashArgs.AddRange(allFiles);
  109. await GitCommand.RunGitAsync(log, stashArgs.ToArray());
  110. }
  111. else
  112. {
  113. throw new Exception("No files to stash.");
  114. }
  115. resolve("Successfully created new 'Better Git Stash'.");
  116. }
  117. catch (Exception ex)
  118. {
  119. Debug.LogException(ex);
  120. reject(ex);
  121. }
  122. }
  123. public static void DropStashExecutor(Action<string> resolve, Action<Exception> reject)
  124. {
  125. try
  126. {
  127. using var repo = new Repository(ProjectRoot);
  128. var stash = repo.Stashes.FirstOrDefault(s => s.Message.Contains(StashMessage));
  129. if (stash != null)
  130. {
  131. repo.Stashes.Remove(repo.Stashes.ToList().IndexOf(stash));
  132. resolve("'Better Git Stash' has been discarded.");
  133. }
  134. else
  135. {
  136. resolve("No 'Better Git Stash' found to discard.");
  137. }
  138. }
  139. catch (Exception ex)
  140. {
  141. reject(ex);
  142. }
  143. }
  144. public static void GetStashedFilesExecutor(Action<List<GitChange>> resolve, Action<Exception> reject)
  145. {
  146. try
  147. {
  148. using var repo = new Repository(ProjectRoot);
  149. var stash = repo.Stashes.FirstOrDefault(s => s.Message.Contains(StashMessage));
  150. if (stash == null)
  151. {
  152. resolve(new List<GitChange>());
  153. return;
  154. }
  155. var changes = new List<GitChange>();
  156. var stashChanges = repo.Diff.Compare<TreeChanges>(stash.Base.Tree, stash.WorkTree.Tree);
  157. foreach (var change in stashChanges)
  158. {
  159. changes.Add(new GitChange(change.Path, change.OldPath, change.Status));
  160. }
  161. var indexChanges = repo.Diff.Compare<TreeChanges>(stash.Base.Tree, stash.Index.Tree);
  162. foreach (var change in indexChanges)
  163. {
  164. if (changes.All(c => c.FilePath != change.Path))
  165. {
  166. changes.Add(new GitChange(change.Path, change.OldPath, change.Status));
  167. }
  168. }
  169. resolve(changes);
  170. }
  171. catch(Exception ex)
  172. {
  173. reject(ex);
  174. }
  175. }
  176. public static async void DiffStashedFileExecutor(Action<string> resolve, Action<Exception> reject, GitChange change)
  177. {
  178. string fileAPath = null;
  179. string fileBPath = null;
  180. try
  181. {
  182. using var repo = new Repository(ProjectRoot);
  183. var stash = repo.Stashes.FirstOrDefault(s => s.Message.Contains(StashMessage));
  184. if (stash == null) throw new Exception("'Better Git Stash' not found.");
  185. var stashedTree = stash.WorkTree.Tree;
  186. var baseTree = stash.Base.Tree;
  187. switch (change.Status)
  188. {
  189. case ChangeKind.Added:
  190. fileAPath = CreateTempFileWithContent("", "empty");
  191. fileBPath = CreateTempFileFromBlob(stashedTree[change.FilePath]?.Target as Blob, change.FilePath);
  192. break;
  193. case ChangeKind.Deleted:
  194. fileAPath = CreateTempFileFromBlob(baseTree[change.FilePath]?.Target as Blob, change.FilePath);
  195. fileBPath = CreateTempFileWithContent("", change.FilePath);
  196. break;
  197. case ChangeKind.Renamed:
  198. fileAPath = CreateTempFileFromBlob(baseTree[change.OldFilePath]?.Target as Blob, change.OldFilePath);
  199. fileBPath = Path.Combine(ProjectRoot, change.FilePath);
  200. break;
  201. default:
  202. fileAPath = CreateTempFileFromBlob(stashedTree[change.FilePath]?.Target as Blob, change.FilePath);
  203. fileBPath = Path.Combine(ProjectRoot, change.FilePath);
  204. break;
  205. }
  206. if (!File.Exists(fileBPath))
  207. {
  208. fileBPath = CreateTempFileWithContent("", Path.GetFileName(fileBPath));
  209. }
  210. await GitCommand.RunVsCodeAsync(new StringBuilder(), new[] { "--diff", fileAPath, fileBPath });
  211. resolve("Launched external diff tool.");
  212. }
  213. catch (Exception ex)
  214. {
  215. reject(ex);
  216. }
  217. finally
  218. {
  219. if (fileAPath != null && fileAPath.Contains(Path.GetTempPath())) File.Delete(fileAPath);
  220. if (fileBPath != null && fileBPath.Contains(Path.GetTempPath())) File.Delete(fileBPath);
  221. }
  222. }
  223. public static void AnalyzeStashConflictsExecutor(Action<PullAnalysisResult> resolve, Action<Exception> reject)
  224. {
  225. try
  226. {
  227. using var repo = new Repository(ProjectRoot);
  228. var stash = repo.Stashes.FirstOrDefault(s => s.Message.Contains(StashMessage));
  229. if (stash == null)
  230. {
  231. resolve(new PullAnalysisResult(new List<string>()));
  232. return;
  233. }
  234. var stashedChanges = new HashSet<string>(repo.Diff.Compare<TreeChanges>(stash.Base.Tree, stash.Index.Tree).Select(c => c.Path));
  235. var localChanges = new HashSet<string>(repo.RetrieveStatus().Where(s => s.State != FileStatus.Ignored).Select(s => s.FilePath));
  236. var conflictingFiles = stashedChanges.Intersect(localChanges).ToList();
  237. resolve(new PullAnalysisResult(conflictingFiles));
  238. }
  239. catch (Exception ex)
  240. {
  241. reject(ex);
  242. }
  243. }
  244. public static async void ApplyStashAndOverwriteExecutor(Action<string> resolve, Action<Exception> reject, List<GitChange> resolutions)
  245. {
  246. var tempFiles = new Dictionary<string, string>();
  247. var log = new StringBuilder();
  248. try
  249. {
  250. foreach (var resolution in resolutions.Where(r => r.Resolution == GitChange.ConflictResolution.Mine))
  251. {
  252. var fullPath = Path.Combine(ProjectRoot, resolution.FilePath);
  253. if (File.Exists(fullPath))
  254. {
  255. var tempPath = Path.GetTempFileName();
  256. File.Copy(fullPath, tempPath, true);
  257. tempFiles[resolution.FilePath] = tempPath;
  258. }
  259. }
  260. using (var repo = new Repository(ProjectRoot))
  261. {
  262. var filesToReset = resolutions.Where(r => r.Resolution != GitChange.ConflictResolution.None).Select(r => r.FilePath).ToArray();
  263. if (filesToReset.Any())
  264. {
  265. repo.CheckoutPaths(repo.Head.Tip.Sha, filesToReset, new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force });
  266. }
  267. }
  268. await GitCommand.RunGitAsync(log, new[] { "stash", "apply" });
  269. foreach (var entry in tempFiles)
  270. {
  271. var finalPath = Path.Combine(ProjectRoot, entry.Key);
  272. File.Copy(entry.Value, finalPath, true);
  273. await GitCommand.RunGitAsync(log, new[] { "add", entry.Key });
  274. }
  275. await GitCommand.RunGitAsync(log, new[] { "stash", "drop" });
  276. resolve("Stash applied successfully and has been dropped.");
  277. }
  278. catch (Exception ex)
  279. {
  280. reject(new Exception($"Failed to apply stash. You may need to resolve conflicts manually. Details: {ex.Message}"));
  281. }
  282. finally
  283. {
  284. foreach (var tempFile in tempFiles.Values.Where(File.Exists))
  285. {
  286. File.Delete(tempFile);
  287. }
  288. }
  289. }
  290. public static void GetBranchDataExecutor(Action<BranchData> resolve, Action<Exception> reject)
  291. {
  292. try
  293. {
  294. using var repo = new Repository(ProjectRoot);
  295. var data = new BranchData
  296. {
  297. CurrentBranch = repo.Head.FriendlyName,
  298. AllBranches = repo.Branches
  299. .Where(b => !b.FriendlyName.Contains("HEAD"))
  300. .Select(b => b.FriendlyName.Replace("origin/", ""))
  301. .Distinct()
  302. .OrderBy(name => name)
  303. .ToList()
  304. };
  305. resolve(data);
  306. }
  307. catch(Exception ex)
  308. {
  309. reject(ex);
  310. }
  311. }
  312. public static async void SwitchBranchExecutor(Action<string> resolve, Action<Exception> reject, string branchName)
  313. {
  314. try
  315. {
  316. var log = new StringBuilder();
  317. await GitCommand.RunGitAsync(log, new[] { "checkout", branchName });
  318. resolve($"Successfully switched to branch '{branchName}'.");
  319. }
  320. catch (Exception ex)
  321. {
  322. reject(ex);
  323. }
  324. }
  325. public static async void ResetAndSwitchBranchExecutor(Action<string> resolve, Action<Exception> reject, string branchName)
  326. {
  327. try
  328. {
  329. var log = new StringBuilder();
  330. await GitCommand.RunGitAsync(log, new[] { "reset", "--hard", "HEAD" });
  331. await GitCommand.RunGitAsync(log, new[] { "clean", "-fd" });
  332. await GitCommand.RunGitAsync(log, new[] { "checkout", branchName });
  333. resolve($"Discarded local changes and switched to branch '{branchName}'.");
  334. }
  335. catch (Exception ex)
  336. {
  337. reject(ex);
  338. }
  339. }
  340. /// <summary>
  341. /// Synchronous helper to get a GitChange object for a single file.
  342. /// This is public so it can be called by the GitService wrapper.
  343. /// </summary>
  344. public static GitChange GetChangeForFile(string filePath)
  345. {
  346. try
  347. {
  348. using var repo = new Repository(ProjectRoot);
  349. if (repo.Index.Conflicts.Any(c => c.Ours.Path == filePath))
  350. {
  351. return new GitChange(filePath, null, ChangeKind.Conflicted);
  352. }
  353. var statusEntry = repo.RetrieveStatus(filePath);
  354. return statusEntry switch
  355. {
  356. FileStatus.NewInWorkdir or FileStatus.NewInIndex => new GitChange(filePath, null, ChangeKind.Added),
  357. FileStatus.ModifiedInWorkdir or FileStatus.ModifiedInIndex => new GitChange(filePath, null, ChangeKind.Modified),
  358. FileStatus.DeletedFromWorkdir or FileStatus.DeletedFromIndex => new GitChange(filePath, null, ChangeKind.Deleted),
  359. FileStatus.RenamedInWorkdir or FileStatus.RenamedInIndex =>
  360. new GitChange(filePath, null, ChangeKind.Renamed),
  361. _ => null
  362. };
  363. }
  364. catch { return null; } // Suppress errors if repo is in a unique state
  365. }
  366. // --- Promise Executor Implementations ---
  367. public static async void GetUpstreamAheadByExecutor(Action<int?> resolve, Action<Exception> reject, Action<float, string> onProgress)
  368. {
  369. try
  370. {
  371. string refSpec;
  372. using (var tempRepo = new Repository(ProjectRoot))
  373. {
  374. var currentBranch = tempRepo.Head;
  375. if (currentBranch.TrackedBranch == null)
  376. {
  377. resolve(0);
  378. return;
  379. }
  380. var branchName = currentBranch.FriendlyName;
  381. var remoteName = currentBranch.TrackedBranch.RemoteName;
  382. refSpec = $"{branchName}:refs/remotes/{remoteName}/{branchName}";
  383. }
  384. var authenticatedUrl = GetAuthenticatedRemoteUrl();
  385. var progressReporter = new Progress<string>(line => ParseProgress(line, onProgress));
  386. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "fetch", authenticatedUrl, refSpec, "--progress" }, progressReporter);
  387. using var repo = new Repository(ProjectRoot);
  388. resolve(repo.Head.TrackingDetails.BehindBy);
  389. }
  390. catch (Exception ex)
  391. {
  392. if (ex.Message.Contains("is not tracking a remote branch"))
  393. {
  394. resolve(null);
  395. }
  396. else
  397. {
  398. reject(ex);
  399. }
  400. }
  401. }
  402. public static void GetLocalStatusExecutor(Action<List<GitChange>> resolve, Action<Exception> reject)
  403. {
  404. try
  405. {
  406. var changes = new List<GitChange>();
  407. using var repo = new Repository(ProjectRoot);
  408. var conflictedPaths = new HashSet<string>(repo.Index.Conflicts.Select(c => c.Ours.Path));
  409. var statusOptions = new StatusOptions
  410. {
  411. IncludeUntracked = true,
  412. RecurseUntrackedDirs = true,
  413. DetectRenamesInIndex = true,
  414. DetectRenamesInWorkDir = true
  415. };
  416. foreach (var entry in repo.RetrieveStatus(statusOptions))
  417. {
  418. if (conflictedPaths.Contains(entry.FilePath))
  419. {
  420. if (changes.All(c => c.FilePath != entry.FilePath))
  421. {
  422. changes.Add(new GitChange(entry.FilePath, null, ChangeKind.Conflicted));
  423. }
  424. continue;
  425. }
  426. switch(entry.State)
  427. {
  428. case FileStatus.NewInWorkdir:
  429. case FileStatus.NewInIndex:
  430. changes.Add(new GitChange(entry.FilePath, null, ChangeKind.Added));
  431. break;
  432. case FileStatus.ModifiedInWorkdir:
  433. case FileStatus.ModifiedInIndex:
  434. changes.Add(new GitChange(entry.FilePath, null, ChangeKind.Modified));
  435. break;
  436. case FileStatus.DeletedFromWorkdir:
  437. case FileStatus.DeletedFromIndex:
  438. changes.Add(new GitChange(entry.FilePath, null, ChangeKind.Deleted));
  439. break;
  440. case FileStatus.RenamedInWorkdir:
  441. case FileStatus.RenamedInIndex:
  442. var renameDetails = entry.HeadToIndexRenameDetails ?? entry.IndexToWorkDirRenameDetails;
  443. changes.Add(renameDetails != null ? new GitChange(renameDetails.NewFilePath, renameDetails.OldFilePath, ChangeKind.Renamed)
  444. : new GitChange(entry.FilePath, "Unknown", ChangeKind.Renamed));
  445. break;
  446. }
  447. }
  448. resolve(changes);
  449. }
  450. catch (Exception ex)
  451. {
  452. reject(ex);
  453. }
  454. }
  455. public static async void CommitAndPushExecutor(Action<string> resolve, Action<Exception> reject, List<GitChange> changesToCommit, string commitMessage, string username, string email, Action<float, string> onProgress)
  456. {
  457. try
  458. {
  459. if (string.IsNullOrWhiteSpace(email))
  460. {
  461. throw new Exception("Author email is missing. Please set your email address in Project Settings > Better Git.");
  462. }
  463. var authenticatedUrl = GetAuthenticatedRemoteUrl();
  464. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "fetch", authenticatedUrl });
  465. using (var repo = new Repository(ProjectRoot))
  466. {
  467. var remote = repo.Network.Remotes["origin"];
  468. if (remote == null) throw new Exception("No remote named 'origin' found.");
  469. var trackingDetails = repo.Head.TrackingDetails;
  470. if (trackingDetails.BehindBy > 0)
  471. {
  472. throw new Exception($"Push aborted. There are {trackingDetails.BehindBy.Value} incoming changes on the remote. Please pull first.");
  473. }
  474. var pathsToStage = new List<string>();
  475. foreach (var change in changesToCommit)
  476. {
  477. switch (change.Status)
  478. {
  479. case ChangeKind.Deleted:
  480. Commands.Remove(repo, change.FilePath);
  481. break;
  482. case ChangeKind.Renamed:
  483. Commands.Remove(repo, change.OldFilePath);
  484. pathsToStage.Add(change.FilePath);
  485. break;
  486. default:
  487. pathsToStage.Add(change.FilePath);
  488. break;
  489. }
  490. }
  491. if (pathsToStage.Any()) Commands.Stage(repo, pathsToStage);
  492. var status = repo.RetrieveStatus();
  493. if (!status.IsDirty) throw new Exception("No effective changes were staged to commit.");
  494. var author = new Signature(username, email, DateTimeOffset.Now);
  495. repo.Commit(commitMessage, author, author);
  496. }
  497. var progressReporter = new Progress<string>(line => ParseProgress(line, onProgress));
  498. using var tempRepo = new Repository(ProjectRoot);
  499. var currentBranch = tempRepo.Head.FriendlyName;
  500. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "push", "--progress", authenticatedUrl, $"HEAD:{currentBranch}" }, progressReporter, 0, 141);
  501. resolve("Successfully committed and pushed changes!");
  502. }
  503. catch (Exception ex)
  504. {
  505. var errorMessage = ex.InnerException?.Message ?? ex.Message;
  506. reject(new Exception(errorMessage));
  507. }
  508. }
  509. private static void ParseProgress(string line, Action<float, string> onProgress)
  510. {
  511. if (onProgress == null || string.IsNullOrWhiteSpace(line)) return;
  512. line = line.Trim();
  513. var parts = line.Split(new[] { ':' }, 2);
  514. if (parts.Length < 2) return;
  515. var action = parts[0];
  516. var progressPart = parts[1];
  517. var percentIndex = progressPart.IndexOf('%');
  518. if (percentIndex == -1) return;
  519. var percentString = progressPart[..percentIndex].Trim();
  520. if (!float.TryParse(percentString, NumberStyles.Any, CultureInfo.InvariantCulture, out var percentage)) return;
  521. var progressValue = percentage / 100.0f;
  522. onProgress(progressValue, $"{action}...");
  523. }
  524. public static void ResetFileExecutor(Action<string> resolve, Action<Exception> reject, GitChange changeToReset)
  525. {
  526. try
  527. {
  528. using var repo = new Repository(ProjectRoot);
  529. switch (changeToReset.Status)
  530. {
  531. case ChangeKind.Added:
  532. {
  533. Commands.Unstage(repo, changeToReset.FilePath);
  534. var fullPath = Path.Combine(ProjectRoot, changeToReset.FilePath);
  535. if (File.Exists(fullPath))
  536. {
  537. File.Delete(fullPath);
  538. }
  539. break;
  540. }
  541. case ChangeKind.Renamed:
  542. {
  543. Commands.Unstage(repo, changeToReset.FilePath);
  544. var newFullPath = Path.Combine(ProjectRoot, changeToReset.FilePath);
  545. if (File.Exists(newFullPath)) File.Delete(newFullPath);
  546. repo.CheckoutPaths(repo.Head.Tip.Sha, new[] { changeToReset.OldFilePath }, new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force });
  547. break;
  548. }
  549. default:
  550. repo.CheckoutPaths(repo.Head.Tip.Sha, new[] { changeToReset.FilePath }, new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force });
  551. break;
  552. }
  553. resolve($"Successfully reset changes for '{changeToReset.FilePath}'");
  554. }
  555. catch (Exception ex)
  556. {
  557. reject(ex);
  558. }
  559. }
  560. public static async void LaunchExternalDiffExecutor(Action<string> resolve, Action<Exception> reject, GitChange change)
  561. {
  562. string fileAPath = null; // Before
  563. string fileBPath = null; // After
  564. try
  565. {
  566. using var repo = new Repository(ProjectRoot);
  567. string GetFileContentFromHead(string path)
  568. {
  569. var blob = repo.Head.Tip[path]?.Target as Blob;
  570. return blob?.GetContentText() ?? "";
  571. }
  572. string CreateTempFile(string originalPath, string content)
  573. {
  574. var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + Path.GetExtension(originalPath));
  575. File.WriteAllText(tempPath, content);
  576. return tempPath;
  577. }
  578. switch (change.Status)
  579. {
  580. case ChangeKind.Added:
  581. fileAPath = CreateTempFile(change.FilePath, "");
  582. fileBPath = Path.Combine(ProjectRoot, change.FilePath);
  583. break;
  584. case ChangeKind.Deleted:
  585. fileAPath = CreateTempFile(change.FilePath, GetFileContentFromHead(change.FilePath));
  586. fileBPath = CreateTempFile(change.FilePath, "");
  587. break;
  588. case ChangeKind.Renamed:
  589. fileAPath = CreateTempFile(change.OldFilePath, GetFileContentFromHead(change.OldFilePath));
  590. fileBPath = Path.Combine(ProjectRoot, change.FilePath);
  591. break;
  592. default: // Modified
  593. fileAPath = CreateTempFile(change.FilePath, GetFileContentFromHead(change.FilePath));
  594. fileBPath = Path.Combine(ProjectRoot, change.FilePath);
  595. break;
  596. }
  597. await GitCommand.RunVsCodeAsync(new StringBuilder(), new[] { "--diff", fileAPath, fileBPath });
  598. resolve("Launched external diff tool.");
  599. }
  600. catch(Win32Exception ex)
  601. {
  602. reject(new Exception("Could not launch VS Code. Ensure it is installed and the 'code' command is available in your system's PATH.", ex));
  603. }
  604. catch(Exception ex)
  605. {
  606. reject(ex);
  607. }
  608. finally
  609. {
  610. try
  611. {
  612. if (fileAPath != null && fileAPath.Contains(Path.GetTempPath()) && File.Exists(fileAPath)) File.Delete(fileAPath);
  613. if (fileBPath != null && fileBPath.Contains(Path.GetTempPath()) && File.Exists(fileBPath)) File.Delete(fileBPath);
  614. }
  615. catch(Exception cleanupEx)
  616. {
  617. Debug.LogError($"Failed to clean up temporary diff files: {cleanupEx.Message}");
  618. }
  619. }
  620. }
  621. public static void FileLevelConflictCheckExecutor(Action<PullAnalysisResult> resolve, Action<Exception> reject)
  622. {
  623. try
  624. {
  625. using var repo = new Repository(ProjectRoot);
  626. var result = AnalyzePullConflictsInternal(repo).Result;
  627. resolve(result);
  628. }
  629. catch (Exception ex)
  630. {
  631. reject(ex);
  632. }
  633. }
  634. private static Task<PullAnalysisResult> AnalyzePullConflictsInternal(Repository repo)
  635. {
  636. var remote = repo.Network.Remotes["origin"];
  637. if (remote == null) throw new Exception("No remote named 'origin' was found.");
  638. var localBranch = repo.Head;
  639. var remoteBranch = repo.Head.TrackedBranch;
  640. if (remoteBranch == null) throw new Exception("Current branch is not tracking a remote branch.");
  641. var mergeBase = repo.ObjectDatabase.FindMergeBase(localBranch.Tip, remoteBranch.Tip);
  642. if (mergeBase == null) throw new Exception("Could not find a common ancestor.");
  643. var theirChanges = new HashSet<string>(repo.Diff.Compare<TreeChanges>(mergeBase.Tree, remoteBranch.Tip.Tree).Select(c => c.Path));
  644. var ourChanges = new HashSet<string>(repo.Diff.Compare<TreeChanges>(mergeBase.Tree, localBranch.Tip.Tree).Select(c => c.Path));
  645. foreach (var statusEntry in repo.RetrieveStatus()) ourChanges.Add(statusEntry.FilePath);
  646. return Task.FromResult(new PullAnalysisResult(ourChanges.Where(theirChanges.Contains).ToList()));
  647. }
  648. public static async void SafePullExecutor(Action<string> resolve, Action<Exception> reject)
  649. {
  650. try
  651. {
  652. var authenticatedUrl = GetAuthenticatedRemoteUrl();
  653. var log = new StringBuilder();
  654. string currentBranchName;
  655. using (var repo = new Repository(ProjectRoot))
  656. {
  657. currentBranchName = repo.Head.FriendlyName;
  658. }
  659. await GitCommand.RunGitAsync(log, new[] { "pull", "--no-rebase", authenticatedUrl, currentBranchName }, 0, 141);
  660. resolve(log.ToString());
  661. }
  662. catch (Exception ex)
  663. {
  664. reject(ex);
  665. }
  666. }
  667. public static async void PullAndOverwriteExecutor(Action<string> resolve, Action<Exception> reject, List<GitChange> resolutions)
  668. {
  669. var tempFiles = new Dictionary<string, string>();
  670. var log = new StringBuilder();
  671. try
  672. {
  673. foreach (var resolution in resolutions.Where(r => r.Resolution == GitChange.ConflictResolution.Mine))
  674. {
  675. var fullPath = Path.Combine(ProjectRoot, resolution.FilePath);
  676. var tempPath = Path.GetTempFileName();
  677. File.Copy(fullPath, tempPath, true);
  678. tempFiles[resolution.FilePath] = tempPath;
  679. }
  680. using (var repo = new Repository(ProjectRoot))
  681. {
  682. var filesToReset = resolutions.Where(r => r.Resolution != GitChange.ConflictResolution.None).Select(r => r.FilePath).ToArray();
  683. if(filesToReset.Length > 0)
  684. {
  685. repo.CheckoutPaths(repo.Head.Tip.Sha, filesToReset, new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force });
  686. }
  687. }
  688. await GitCommand.RunGitAsync(log, new[] { "pull", "--no-rebase" }, 0, 1, 141);
  689. foreach (var entry in tempFiles)
  690. {
  691. var finalPath = Path.Combine(ProjectRoot, entry.Key);
  692. File.Copy(entry.Value, finalPath, true);
  693. await GitCommand.RunGitAsync(log, new[] { "add", entry.Key });
  694. }
  695. var unresolvedFiles = resolutions.Where(r => r.Resolution == GitChange.ConflictResolution.None).ToList();
  696. if (unresolvedFiles.Any())
  697. {
  698. var fileList = string.Join(", ", unresolvedFiles.Select(f => f.FilePath));
  699. resolve($"Pull completed with unresolved conflicts in: {fileList}. Please resolve them manually.");
  700. }
  701. else
  702. {
  703. resolve("Pull successful. Your chosen local changes have been preserved.");
  704. }
  705. }
  706. catch (Exception ex)
  707. {
  708. reject(ex);
  709. }
  710. finally
  711. {
  712. foreach (var tempFile in tempFiles.Values.Where(File.Exists))
  713. {
  714. File.Delete(tempFile);
  715. }
  716. }
  717. }
  718. public static async void LaunchMergeToolExecutor(Action<string> resolve, Action<Exception> reject, GitChange change)
  719. {
  720. try
  721. {
  722. if (change.FilePath == null)
  723. {
  724. reject(new Exception("Could not find file path."));
  725. return;
  726. }
  727. var fileExtension = Path.GetExtension(change.FilePath).ToLower();
  728. if (fileExtension is ".prefab" or ".unity")
  729. {
  730. reject(new Exception("Cannot auto-resolve conflicts for binary files. Please use an external merge tool."));
  731. return;
  732. }
  733. await GitCommand.RunVsCodeAsync(new StringBuilder(), new[] { "--wait", change.FilePath }, 0, 141);
  734. var fullPath = Path.Combine(ProjectRoot, change.FilePath);
  735. var fileContent = await File.ReadAllTextAsync(fullPath);
  736. if (fileContent.Contains("<<<<<<<"))
  737. {
  738. resolve($"Conflict in '{change.FilePath}' was not resolved. Please try again.");
  739. return;
  740. }
  741. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "add", change.FilePath });
  742. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "reset", "HEAD", change.FilePath });
  743. resolve($"Successfully resolved conflict in '{change.FilePath}'. The file is now modified and ready for review.");
  744. }
  745. catch (Win32Exception ex)
  746. {
  747. reject(new Exception("Could not launch VS Code. Ensure it is installed and the 'code' command is available in your system's PATH.", ex));
  748. }
  749. catch (Exception ex)
  750. {
  751. reject(ex);
  752. }
  753. }
  754. public static async void UnstageAllFilesIfSafeExecutor(Action<bool> resolve, Action<Exception> reject)
  755. {
  756. try
  757. {
  758. using var repo = new Repository(ProjectRoot);
  759. if (repo.Index.Conflicts.Any())
  760. {
  761. resolve(false);
  762. return;
  763. }
  764. var stagedFiles = repo.RetrieveStatus().Count(s => s.State is
  765. FileStatus.NewInIndex or
  766. FileStatus.ModifiedInIndex or
  767. FileStatus.DeletedFromIndex or
  768. FileStatus.RenamedInIndex or
  769. FileStatus.TypeChangeInIndex);
  770. if (stagedFiles == 0)
  771. {
  772. resolve(false);
  773. return;
  774. }
  775. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "reset" });
  776. resolve(true);
  777. }
  778. catch (Exception ex)
  779. {
  780. reject(ex);
  781. }
  782. }
  783. private static string CreateTempFileFromBlob(Blob blob, string fallbackFileName)
  784. {
  785. var content = blob?.GetContentText() ?? "";
  786. return CreateTempFileWithContent(content, fallbackFileName);
  787. }
  788. private static string CreateTempFileWithContent(string content, string originalFileName)
  789. {
  790. var tempFileName = $"{Path.GetFileName(originalFileName)}-{Path.GetRandomFileName()}";
  791. var tempPath = Path.Combine(Path.GetTempPath(), tempFileName);
  792. File.WriteAllText(tempPath, content);
  793. return tempPath;
  794. }
  795. }
  796. }