GitExecutors.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  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 workTreeChanges = repo.Diff.Compare<TreeChanges>(stash.Base.Tree, stash.WorkTree.Tree).Select(c => c.Path);
  235. var indexChanges = repo.Diff.Compare<TreeChanges>(stash.Base.Tree, stash.Index.Tree).Select(c => c.Path);
  236. var stashedChanges = new HashSet<string>(workTreeChanges.Union(indexChanges));
  237. var localChanges = new HashSet<string>(repo.RetrieveStatus().Where(s => s.State != FileStatus.Ignored).Select(s => s.FilePath));
  238. var conflictingFiles = stashedChanges.Intersect(localChanges).ToList();
  239. resolve(new PullAnalysisResult(conflictingFiles));
  240. }
  241. catch (Exception ex)
  242. {
  243. reject(ex);
  244. }
  245. }
  246. public static async void ApplyStashAndOverwriteExecutor(Action<string> resolve, Action<Exception> reject, List<GitChange> resolutions)
  247. {
  248. var tempFiles = new Dictionary<string, string>();
  249. var log = new StringBuilder();
  250. try
  251. {
  252. foreach (var resolution in resolutions.Where(r => r.Resolution == GitChange.ConflictResolution.Mine))
  253. {
  254. var fullPath = Path.Combine(ProjectRoot, resolution.FilePath);
  255. if (File.Exists(fullPath))
  256. {
  257. var tempPath = Path.GetTempFileName();
  258. File.Copy(fullPath, tempPath, true);
  259. tempFiles[resolution.FilePath] = tempPath;
  260. }
  261. }
  262. using (var repo = new Repository(ProjectRoot))
  263. {
  264. var filesToReset = resolutions.Where(r => r.Resolution != GitChange.ConflictResolution.None).Select(r => r.FilePath).ToArray();
  265. if (filesToReset.Any())
  266. {
  267. repo.CheckoutPaths(repo.Head.Tip.Sha, filesToReset, new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force });
  268. }
  269. }
  270. await GitCommand.RunGitAsync(log, new[] { "stash", "apply" });
  271. foreach (var entry in tempFiles)
  272. {
  273. var finalPath = Path.Combine(ProjectRoot, entry.Key);
  274. File.Copy(entry.Value, finalPath, true);
  275. await GitCommand.RunGitAsync(log, new[] { "add", entry.Key });
  276. }
  277. await GitCommand.RunGitAsync(log, new[] { "stash", "drop" });
  278. resolve("Stash applied successfully and has been dropped.");
  279. }
  280. catch (Exception ex)
  281. {
  282. reject(new Exception($"Failed to apply stash. You may need to resolve conflicts manually. Details: {ex.Message}"));
  283. }
  284. finally
  285. {
  286. foreach (var tempFile in tempFiles.Values.Where(File.Exists))
  287. {
  288. File.Delete(tempFile);
  289. }
  290. }
  291. }
  292. public static void GetBranchDataExecutor(Action<BranchData> resolve, Action<Exception> reject)
  293. {
  294. try
  295. {
  296. using var repo = new Repository(ProjectRoot);
  297. var data = new BranchData
  298. {
  299. CurrentBranch = repo.Head.FriendlyName,
  300. AllBranches = repo.Branches
  301. .Where(b => !b.FriendlyName.Contains("HEAD"))
  302. .Select(b => b.FriendlyName.Replace("origin/", ""))
  303. .Distinct()
  304. .OrderBy(name => name)
  305. .ToList()
  306. };
  307. resolve(data);
  308. }
  309. catch(Exception ex)
  310. {
  311. reject(ex);
  312. }
  313. }
  314. public static async void SwitchBranchExecutor(Action<string> resolve, Action<Exception> reject, string branchName)
  315. {
  316. try
  317. {
  318. var log = new StringBuilder();
  319. await GitCommand.RunGitAsync(log, new[] { "checkout", branchName });
  320. resolve($"Successfully switched to branch '{branchName}'.");
  321. }
  322. catch (Exception ex)
  323. {
  324. reject(ex);
  325. }
  326. }
  327. public static async void ResetAndSwitchBranchExecutor(Action<string> resolve, Action<Exception> reject, string branchName)
  328. {
  329. try
  330. {
  331. var log = new StringBuilder();
  332. await GitCommand.RunGitAsync(log, new[] { "reset", "--hard", "HEAD" });
  333. await GitCommand.RunGitAsync(log, new[] { "clean", "-fd" });
  334. await GitCommand.RunGitAsync(log, new[] { "checkout", branchName });
  335. resolve($"Discarded local changes and switched to branch '{branchName}'.");
  336. }
  337. catch (Exception ex)
  338. {
  339. reject(ex);
  340. }
  341. }
  342. /// <summary>
  343. /// Synchronous helper to get a GitChange object for a single file.
  344. /// This is public so it can be called by the GitService wrapper.
  345. /// </summary>
  346. public static GitChange GetChangeForFile(string filePath)
  347. {
  348. try
  349. {
  350. using var repo = new Repository(ProjectRoot);
  351. if (repo.Index.Conflicts.Any(c => c.Ours.Path == filePath))
  352. {
  353. return new GitChange(filePath, null, ChangeKind.Conflicted);
  354. }
  355. var statusEntry = repo.RetrieveStatus(filePath);
  356. return statusEntry switch
  357. {
  358. FileStatus.NewInWorkdir or FileStatus.NewInIndex => new GitChange(filePath, null, ChangeKind.Added),
  359. FileStatus.ModifiedInWorkdir or FileStatus.ModifiedInIndex => new GitChange(filePath, null, ChangeKind.Modified),
  360. FileStatus.DeletedFromWorkdir or FileStatus.DeletedFromIndex => new GitChange(filePath, null, ChangeKind.Deleted),
  361. FileStatus.RenamedInWorkdir or FileStatus.RenamedInIndex =>
  362. new GitChange(filePath, null, ChangeKind.Renamed),
  363. _ => null
  364. };
  365. }
  366. catch { return null; } // Suppress errors if repo is in a unique state
  367. }
  368. // --- Promise Executor Implementations ---
  369. public static async void GetUpstreamAheadByExecutor(Action<int?> resolve, Action<Exception> reject, Action<float, string> onProgress)
  370. {
  371. try
  372. {
  373. string refSpec;
  374. using (var tempRepo = new Repository(ProjectRoot))
  375. {
  376. var currentBranch = tempRepo.Head;
  377. if (currentBranch.TrackedBranch == null)
  378. {
  379. resolve(0);
  380. return;
  381. }
  382. var branchName = currentBranch.FriendlyName;
  383. var remoteName = currentBranch.TrackedBranch.RemoteName;
  384. refSpec = $"{branchName}:refs/remotes/{remoteName}/{branchName}";
  385. }
  386. var authenticatedUrl = GetAuthenticatedRemoteUrl();
  387. var progressReporter = new Progress<string>(line => ParseProgress(line, onProgress));
  388. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "fetch", authenticatedUrl, refSpec, "--progress" }, progressReporter);
  389. using var repo = new Repository(ProjectRoot);
  390. resolve(repo.Head.TrackingDetails.BehindBy);
  391. }
  392. catch (Exception ex)
  393. {
  394. if (ex.Message.Contains("is not tracking a remote branch"))
  395. {
  396. resolve(null);
  397. }
  398. else
  399. {
  400. reject(ex);
  401. }
  402. }
  403. }
  404. public static void GetLocalStatusExecutor(Action<List<GitChange>> resolve, Action<Exception> reject)
  405. {
  406. try
  407. {
  408. var changes = new List<GitChange>();
  409. using var repo = new Repository(ProjectRoot);
  410. var conflictedPaths = new HashSet<string>(repo.Index.Conflicts.Select(c => c.Ours.Path));
  411. var statusOptions = new StatusOptions
  412. {
  413. IncludeUntracked = true,
  414. RecurseUntrackedDirs = true,
  415. DetectRenamesInIndex = true,
  416. DetectRenamesInWorkDir = true
  417. };
  418. foreach (var entry in repo.RetrieveStatus(statusOptions))
  419. {
  420. if (conflictedPaths.Contains(entry.FilePath))
  421. {
  422. if (changes.All(c => c.FilePath != entry.FilePath))
  423. {
  424. changes.Add(new GitChange(entry.FilePath, null, ChangeKind.Conflicted));
  425. }
  426. continue;
  427. }
  428. switch(entry.State)
  429. {
  430. case FileStatus.NewInWorkdir:
  431. case FileStatus.NewInIndex:
  432. changes.Add(new GitChange(entry.FilePath, null, ChangeKind.Added));
  433. break;
  434. case FileStatus.ModifiedInWorkdir:
  435. case FileStatus.ModifiedInIndex:
  436. changes.Add(new GitChange(entry.FilePath, null, ChangeKind.Modified));
  437. break;
  438. case FileStatus.DeletedFromWorkdir:
  439. case FileStatus.DeletedFromIndex:
  440. changes.Add(new GitChange(entry.FilePath, null, ChangeKind.Deleted));
  441. break;
  442. case FileStatus.RenamedInWorkdir:
  443. case FileStatus.RenamedInIndex:
  444. var renameDetails = entry.HeadToIndexRenameDetails ?? entry.IndexToWorkDirRenameDetails;
  445. changes.Add(renameDetails != null ? new GitChange(renameDetails.NewFilePath, renameDetails.OldFilePath, ChangeKind.Renamed)
  446. : new GitChange(entry.FilePath, "Unknown", ChangeKind.Renamed));
  447. break;
  448. }
  449. }
  450. resolve(changes);
  451. }
  452. catch (Exception ex)
  453. {
  454. reject(ex);
  455. }
  456. }
  457. public static async void CommitAndPushExecutor(Action<string> resolve, Action<Exception> reject, List<GitChange> changesToCommit, string commitMessage, string username, string email, Action<float, string> onProgress)
  458. {
  459. try
  460. {
  461. if (string.IsNullOrWhiteSpace(email))
  462. {
  463. throw new Exception("Author email is missing. Please set your email address in Project Settings > Better Git.");
  464. }
  465. var authenticatedUrl = GetAuthenticatedRemoteUrl();
  466. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "fetch", authenticatedUrl });
  467. using (var repo = new Repository(ProjectRoot))
  468. {
  469. var remote = repo.Network.Remotes["origin"];
  470. if (remote == null) throw new Exception("No remote named 'origin' found.");
  471. var trackingDetails = repo.Head.TrackingDetails;
  472. if (trackingDetails.BehindBy > 0)
  473. {
  474. throw new Exception($"Push aborted. There are {trackingDetails.BehindBy.Value} incoming changes on the remote. Please pull first.");
  475. }
  476. var pathsToStage = new List<string>();
  477. foreach (var change in changesToCommit)
  478. {
  479. switch (change.Status)
  480. {
  481. case ChangeKind.Deleted:
  482. Commands.Remove(repo, change.FilePath);
  483. break;
  484. case ChangeKind.Renamed:
  485. Commands.Remove(repo, change.OldFilePath);
  486. pathsToStage.Add(change.FilePath);
  487. break;
  488. default:
  489. pathsToStage.Add(change.FilePath);
  490. break;
  491. }
  492. }
  493. if (pathsToStage.Any()) Commands.Stage(repo, pathsToStage);
  494. var status = repo.RetrieveStatus();
  495. if (!status.IsDirty) throw new Exception("No effective changes were staged to commit.");
  496. var author = new Signature(username, email, DateTimeOffset.Now);
  497. repo.Commit(commitMessage, author, author);
  498. }
  499. var progressReporter = new Progress<string>(line => ParseProgress(line, onProgress));
  500. using var tempRepo = new Repository(ProjectRoot);
  501. var currentBranch = tempRepo.Head.FriendlyName;
  502. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "push", "--progress", authenticatedUrl, $"HEAD:{currentBranch}" }, progressReporter, 0, 141);
  503. resolve("Successfully committed and pushed changes!");
  504. }
  505. catch (Exception ex)
  506. {
  507. var errorMessage = ex.InnerException?.Message ?? ex.Message;
  508. reject(new Exception(errorMessage));
  509. }
  510. }
  511. private static void ParseProgress(string line, Action<float, string> onProgress)
  512. {
  513. if (onProgress == null || string.IsNullOrWhiteSpace(line)) return;
  514. line = line.Trim();
  515. var parts = line.Split(new[] { ':' }, 2);
  516. if (parts.Length < 2) return;
  517. var action = parts[0];
  518. var progressPart = parts[1];
  519. var percentIndex = progressPart.IndexOf('%');
  520. if (percentIndex == -1) return;
  521. var percentString = progressPart[..percentIndex].Trim();
  522. if (!float.TryParse(percentString, NumberStyles.Any, CultureInfo.InvariantCulture, out var percentage)) return;
  523. var progressValue = percentage / 100.0f;
  524. onProgress(progressValue, $"{action}...");
  525. }
  526. public static void ResetFileExecutor(Action<string> resolve, Action<Exception> reject, GitChange changeToReset)
  527. {
  528. try
  529. {
  530. using var repo = new Repository(ProjectRoot);
  531. switch (changeToReset.Status)
  532. {
  533. case ChangeKind.Added:
  534. {
  535. Commands.Unstage(repo, changeToReset.FilePath);
  536. var fullPath = Path.Combine(ProjectRoot, changeToReset.FilePath);
  537. if (File.Exists(fullPath))
  538. {
  539. File.Delete(fullPath);
  540. }
  541. break;
  542. }
  543. case ChangeKind.Renamed:
  544. {
  545. Commands.Unstage(repo, changeToReset.FilePath);
  546. var newFullPath = Path.Combine(ProjectRoot, changeToReset.FilePath);
  547. if (File.Exists(newFullPath)) File.Delete(newFullPath);
  548. repo.CheckoutPaths(repo.Head.Tip.Sha, new[] { changeToReset.OldFilePath }, new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force });
  549. break;
  550. }
  551. default:
  552. repo.CheckoutPaths(repo.Head.Tip.Sha, new[] { changeToReset.FilePath }, new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force });
  553. break;
  554. }
  555. resolve($"Successfully reset changes for '{changeToReset.FilePath}'");
  556. }
  557. catch (Exception ex)
  558. {
  559. reject(ex);
  560. }
  561. }
  562. public static async void LaunchExternalDiffExecutor(Action<string> resolve, Action<Exception> reject, GitChange change)
  563. {
  564. string fileAPath = null; // Before
  565. string fileBPath = null; // After
  566. try
  567. {
  568. using var repo = new Repository(ProjectRoot);
  569. string GetFileContentFromHead(string path)
  570. {
  571. var blob = repo.Head.Tip[path]?.Target as Blob;
  572. return blob?.GetContentText() ?? "";
  573. }
  574. string CreateTempFile(string originalPath, string content)
  575. {
  576. var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + Path.GetExtension(originalPath));
  577. File.WriteAllText(tempPath, content);
  578. return tempPath;
  579. }
  580. switch (change.Status)
  581. {
  582. case ChangeKind.Added:
  583. fileAPath = CreateTempFile(change.FilePath, "");
  584. fileBPath = Path.Combine(ProjectRoot, change.FilePath);
  585. break;
  586. case ChangeKind.Deleted:
  587. fileAPath = CreateTempFile(change.FilePath, GetFileContentFromHead(change.FilePath));
  588. fileBPath = CreateTempFile(change.FilePath, "");
  589. break;
  590. case ChangeKind.Renamed:
  591. fileAPath = CreateTempFile(change.OldFilePath, GetFileContentFromHead(change.OldFilePath));
  592. fileBPath = Path.Combine(ProjectRoot, change.FilePath);
  593. break;
  594. default: // Modified
  595. fileAPath = CreateTempFile(change.FilePath, GetFileContentFromHead(change.FilePath));
  596. fileBPath = Path.Combine(ProjectRoot, change.FilePath);
  597. break;
  598. }
  599. await GitCommand.RunVsCodeAsync(new StringBuilder(), new[] { "--diff", fileAPath, fileBPath });
  600. resolve("Launched external diff tool.");
  601. }
  602. catch(Win32Exception ex)
  603. {
  604. reject(new Exception("Could not launch VS Code. Ensure it is installed and the 'code' command is available in your system's PATH.", ex));
  605. }
  606. catch(Exception ex)
  607. {
  608. reject(ex);
  609. }
  610. finally
  611. {
  612. try
  613. {
  614. if (fileAPath != null && fileAPath.Contains(Path.GetTempPath()) && File.Exists(fileAPath)) File.Delete(fileAPath);
  615. if (fileBPath != null && fileBPath.Contains(Path.GetTempPath()) && File.Exists(fileBPath)) File.Delete(fileBPath);
  616. }
  617. catch(Exception cleanupEx)
  618. {
  619. Debug.LogError($"Failed to clean up temporary diff files: {cleanupEx.Message}");
  620. }
  621. }
  622. }
  623. public static void FileLevelConflictCheckExecutor(Action<PullAnalysisResult> resolve, Action<Exception> reject)
  624. {
  625. try
  626. {
  627. using var repo = new Repository(ProjectRoot);
  628. var result = AnalyzePullConflictsInternal(repo).Result;
  629. resolve(result);
  630. }
  631. catch (Exception ex)
  632. {
  633. reject(ex);
  634. }
  635. }
  636. private static Task<PullAnalysisResult> AnalyzePullConflictsInternal(Repository repo)
  637. {
  638. var remote = repo.Network.Remotes["origin"];
  639. if (remote == null) throw new Exception("No remote named 'origin' was found.");
  640. var localBranch = repo.Head;
  641. var remoteBranch = repo.Head.TrackedBranch;
  642. if (remoteBranch == null) throw new Exception("Current branch is not tracking a remote branch.");
  643. var mergeBase = repo.ObjectDatabase.FindMergeBase(localBranch.Tip, remoteBranch.Tip);
  644. if (mergeBase == null) throw new Exception("Could not find a common ancestor.");
  645. var theirChanges = new HashSet<string>(repo.Diff.Compare<TreeChanges>(mergeBase.Tree, remoteBranch.Tip.Tree).Select(c => c.Path));
  646. var ourChanges = new HashSet<string>(repo.Diff.Compare<TreeChanges>(mergeBase.Tree, localBranch.Tip.Tree).Select(c => c.Path));
  647. foreach (var statusEntry in repo.RetrieveStatus()) ourChanges.Add(statusEntry.FilePath);
  648. return Task.FromResult(new PullAnalysisResult(ourChanges.Where(theirChanges.Contains).ToList()));
  649. }
  650. public static async void SafePullExecutor(Action<string> resolve, Action<Exception> reject)
  651. {
  652. try
  653. {
  654. var authenticatedUrl = GetAuthenticatedRemoteUrl();
  655. var log = new StringBuilder();
  656. string currentBranchName;
  657. using (var repo = new Repository(ProjectRoot))
  658. {
  659. currentBranchName = repo.Head.FriendlyName;
  660. }
  661. await GitCommand.RunGitAsync(log, new[] { "pull", "--no-rebase", authenticatedUrl, currentBranchName }, 0, 141);
  662. resolve(log.ToString());
  663. }
  664. catch (Exception ex)
  665. {
  666. reject(ex);
  667. }
  668. }
  669. public static async void PullAndOverwriteExecutor(Action<string> resolve, Action<Exception> reject, List<GitChange> resolutions)
  670. {
  671. var tempFiles = new Dictionary<string, string>();
  672. var log = new StringBuilder();
  673. try
  674. {
  675. foreach (var resolution in resolutions.Where(r => r.Resolution == GitChange.ConflictResolution.Mine))
  676. {
  677. var fullPath = Path.Combine(ProjectRoot, resolution.FilePath);
  678. var tempPath = Path.GetTempFileName();
  679. File.Copy(fullPath, tempPath, true);
  680. tempFiles[resolution.FilePath] = tempPath;
  681. }
  682. using (var repo = new Repository(ProjectRoot))
  683. {
  684. var filesToReset = resolutions.Where(r => r.Resolution != GitChange.ConflictResolution.None).Select(r => r.FilePath).ToArray();
  685. if(filesToReset.Length > 0)
  686. {
  687. repo.CheckoutPaths(repo.Head.Tip.Sha, filesToReset, new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force });
  688. }
  689. }
  690. await GitCommand.RunGitAsync(log, new[] { "pull", "--no-rebase" }, 0, 1, 141);
  691. foreach (var entry in tempFiles)
  692. {
  693. var finalPath = Path.Combine(ProjectRoot, entry.Key);
  694. File.Copy(entry.Value, finalPath, true);
  695. await GitCommand.RunGitAsync(log, new[] { "add", entry.Key });
  696. }
  697. var unresolvedFiles = resolutions.Where(r => r.Resolution == GitChange.ConflictResolution.None).ToList();
  698. if (unresolvedFiles.Any())
  699. {
  700. var fileList = string.Join(", ", unresolvedFiles.Select(f => f.FilePath));
  701. resolve($"Pull completed with unresolved conflicts in: {fileList}. Please resolve them manually.");
  702. }
  703. else
  704. {
  705. resolve("Pull successful. Your chosen local changes have been preserved.");
  706. }
  707. }
  708. catch (Exception ex)
  709. {
  710. reject(ex);
  711. }
  712. finally
  713. {
  714. foreach (var tempFile in tempFiles.Values.Where(File.Exists))
  715. {
  716. File.Delete(tempFile);
  717. }
  718. }
  719. }
  720. public static async void LaunchMergeToolExecutor(Action<string> resolve, Action<Exception> reject, GitChange change)
  721. {
  722. try
  723. {
  724. if (change.FilePath == null)
  725. {
  726. reject(new Exception("Could not find file path."));
  727. return;
  728. }
  729. var fileExtension = Path.GetExtension(change.FilePath).ToLower();
  730. if (fileExtension is ".prefab" or ".unity")
  731. {
  732. reject(new Exception("Cannot auto-resolve conflicts for binary files. Please use an external merge tool."));
  733. return;
  734. }
  735. await GitCommand.RunVsCodeAsync(new StringBuilder(), new[] { "--wait", change.FilePath }, 0, 141);
  736. var fullPath = Path.Combine(ProjectRoot, change.FilePath);
  737. var fileContent = await File.ReadAllTextAsync(fullPath);
  738. if (fileContent.Contains("<<<<<<<"))
  739. {
  740. resolve($"Conflict in '{change.FilePath}' was not resolved. Please try again.");
  741. return;
  742. }
  743. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "add", change.FilePath });
  744. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "reset", "HEAD", change.FilePath });
  745. resolve($"Successfully resolved conflict in '{change.FilePath}'. The file is now modified and ready for review.");
  746. }
  747. catch (Win32Exception ex)
  748. {
  749. reject(new Exception("Could not launch VS Code. Ensure it is installed and the 'code' command is available in your system's PATH.", ex));
  750. }
  751. catch (Exception ex)
  752. {
  753. reject(ex);
  754. }
  755. }
  756. public static async void UnstageAllFilesIfSafeExecutor(Action<bool> resolve, Action<Exception> reject)
  757. {
  758. try
  759. {
  760. using var repo = new Repository(ProjectRoot);
  761. if (repo.Index.Conflicts.Any())
  762. {
  763. resolve(false);
  764. return;
  765. }
  766. var stagedFiles = repo.RetrieveStatus().Count(s => s.State is
  767. FileStatus.NewInIndex or
  768. FileStatus.ModifiedInIndex or
  769. FileStatus.DeletedFromIndex or
  770. FileStatus.RenamedInIndex or
  771. FileStatus.TypeChangeInIndex);
  772. if (stagedFiles == 0)
  773. {
  774. resolve(false);
  775. return;
  776. }
  777. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "reset" });
  778. resolve(true);
  779. }
  780. catch (Exception ex)
  781. {
  782. reject(ex);
  783. }
  784. }
  785. private static string CreateTempFileFromBlob(Blob blob, string fallbackFileName)
  786. {
  787. var content = blob?.GetContentText() ?? "";
  788. return CreateTempFileWithContent(content, fallbackFileName);
  789. }
  790. private static string CreateTempFileWithContent(string content, string originalFileName)
  791. {
  792. var tempFileName = $"{Path.GetFileName(originalFileName)}-{Path.GetRandomFileName()}";
  793. var tempPath = Path.Combine(Path.GetTempPath(), tempFileName);
  794. File.WriteAllText(tempPath, content);
  795. return tempPath;
  796. }
  797. }
  798. }