GitCommandHelper.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Text;
  5. namespace SKMC.Api.Common.Version
  6. {
  7. /// <summary>
  8. /// git指令帮助类
  9. /// </summary>
  10. internal static class GitCommandHelper
  11. {
  12. private static readonly Dictionary<string, Dictionary<string, string>> _cache = new Dictionary<string, Dictionary<string, string>>();
  13. private static readonly object _lock = new object();
  14. /// <summary>
  15. /// 通过执行git指令获取git提交的哈希值/id
  16. /// </summary>
  17. /// <param name="workingDir">git文件存在的文件夹</param>
  18. /// <param name="args"></param>
  19. /// <param name="noCache"></param>
  20. /// <returns></returns>
  21. public static string Run(string workingDir, string args, bool noCache = false)
  22. {
  23. if (string.IsNullOrEmpty(workingDir)) return string.Empty;
  24. lock (_lock)
  25. {
  26. if (!noCache && _cache.TryGetValue(workingDir, out var dict) && dict.TryGetValue(args, out var v))
  27. return v;
  28. }
  29. try
  30. {
  31. var psi = new ProcessStartInfo
  32. {
  33. FileName = "git",
  34. Arguments = args,
  35. WorkingDirectory = workingDir,
  36. UseShellExecute = false,
  37. RedirectStandardOutput = true,
  38. RedirectStandardError = true,
  39. StandardOutputEncoding = Encoding.UTF8,
  40. CreateNoWindow = true
  41. };
  42. var process = System.Diagnostics.Process.Start(psi);
  43. process.WaitForExit(1000);
  44. var output = process.StandardOutput.ReadToEnd().Trim();
  45. var error = process.StandardError.ReadToEnd().Trim();
  46. if (process.ExitCode != 0 || !string.IsNullOrEmpty(error))
  47. return string.Empty;
  48. lock (_lock)
  49. {
  50. if (!_cache.ContainsKey(workingDir))
  51. _cache[workingDir] = new Dictionary<string, string>();
  52. _cache[workingDir][args] = output;
  53. }
  54. return output;
  55. }
  56. catch
  57. {
  58. return string.Empty;
  59. }
  60. }
  61. public static void ClearCache(string dir = null)
  62. {
  63. lock (_lock)
  64. {
  65. if (dir == null) _cache.Clear();
  66. else _cache.Remove(dir);
  67. }
  68. }
  69. }
  70. }