GitCommand.cs 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. // Copyright (c) 2025 TerraByte Inc.
  2. //
  3. // A new helper class that abstracts away the boilerplate of running external
  4. // command-line processes, specifically Git and VS Code, using CliWrap.
  5. using System;
  6. using CliWrap;
  7. using System.IO;
  8. using System.Linq;
  9. using UnityEngine;
  10. using System.Text;
  11. using UnityEngine.Scripting;
  12. using System.Threading.Tasks;
  13. using System.Runtime.InteropServices;
  14. namespace Terra.Arbitrator.Services
  15. {
  16. /// <summary>
  17. /// An internal helper class for executing Git commands.
  18. /// It centralizes the logic for finding executables and running them via CliWrap.
  19. /// </summary>
  20. [Preserve]
  21. internal static class GitCommand
  22. {
  23. private static string _projectRoot;
  24. private static string ProjectRoot => _projectRoot ??= Directory.GetParent(Application.dataPath)?.FullName;
  25. /// <summary>
  26. /// Runs a git command asynchronously.
  27. /// </summary>
  28. /// <param name="log">A StringBuilder to capture command output for logging.</param>
  29. /// <param name="progress">A delegate to report real-time standard error lines.</param>
  30. /// <param name="args">The arguments to pass to the git command.</param>
  31. /// <param name="acceptableExitCodes">A list of exit codes that should not be treated as errors.</param>
  32. public static async Task RunAsync(StringBuilder log, IProgress<string> progress, string[] args, params int[] acceptableExitCodes)
  33. {
  34. var stdOutBuffer = new StringBuilder();
  35. var stdErrBuffer = new StringBuilder();
  36. var argumentsString = string.Join(" ", args);
  37. log?.AppendLine($"\n--- Executing: git {argumentsString} ---");
  38. // Pipe stderr to a delegate that both captures the full output and reports each line for progress.
  39. var stdErrPipe = PipeTarget.ToDelegate(line => {
  40. stdErrBuffer.AppendLine(line);
  41. progress?.Report(line); // Report progress for each line received.
  42. });
  43. var command = Cli.Wrap(FindGitExecutable())
  44. .WithArguments(args)
  45. .WithWorkingDirectory(ProjectRoot)
  46. .WithValidation(CommandResultValidation.None) // We handle validation manually
  47. | (PipeTarget.ToDelegate(x => stdOutBuffer.Append(x)), stdErrPipe);
  48. var result = await command.ExecuteAsync();
  49. log?.AppendLine($"Exit Code: {result.ExitCode}");
  50. if (stdOutBuffer.Length > 0) log?.AppendLine($"StdOut: {stdOutBuffer}");
  51. if (stdErrBuffer.Length > 0) log?.AppendLine($"StdErr: {stdErrBuffer}");
  52. // Default to 0 if no specific codes are provided
  53. if (acceptableExitCodes.Length == 0)
  54. {
  55. acceptableExitCodes = new[] { 0 };
  56. }
  57. if (!acceptableExitCodes.Contains(result.ExitCode))
  58. {
  59. throw new Exception($"Command 'git {argumentsString}' failed with unexpected exit code {result.ExitCode}. Error: {stdErrBuffer}");
  60. }
  61. }
  62. public static Task RunAsync(StringBuilder log, string[] args, params int[] acceptableExitCodes)
  63. {
  64. return RunAsync(log, null, args, acceptableExitCodes);
  65. }
  66. /// <summary>
  67. /// Finds the absolute path to a given executable.
  68. /// </summary>
  69. private static string FindExecutable(string name)
  70. {
  71. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  72. {
  73. // CliWrap handles PATH search on Windows automatically.
  74. return name;
  75. }
  76. // For macOS/Linux, we need to be more explicit due to Unity's sandboxing.
  77. string[] searchPaths = { "/usr/local/bin", "/usr/bin", "/bin", "/opt/homebrew/bin" };
  78. foreach (var path in searchPaths)
  79. {
  80. var fullPath = Path.Combine(path, name);
  81. if (File.Exists(fullPath))
  82. {
  83. return fullPath;
  84. }
  85. }
  86. throw new FileNotFoundException($"Could not find executable '{name}'. Please ensure it is installed and in your system's PATH.");
  87. }
  88. public static string FindVsCodeExecutable() => FindExecutable("code");
  89. private static string FindGitExecutable() => FindExecutable("git");
  90. }
  91. }