| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Text;
- namespace SKMC.Api.Common.Version
- {
- /// <summary>
- /// git指令帮助类
- /// </summary>
- internal static class GitCommandHelper
- {
- private static readonly Dictionary<string, Dictionary<string, string>> _cache = new Dictionary<string, Dictionary<string, string>>();
- private static readonly object _lock = new object();
- /// <summary>
- /// 通过执行git指令获取git提交的哈希值/id
- /// </summary>
- /// <param name="workingDir">git文件存在的文件夹</param>
- /// <param name="args"></param>
- /// <param name="noCache"></param>
- /// <returns></returns>
- public static string Run(string workingDir, string args, bool noCache = false)
- {
- if (string.IsNullOrEmpty(workingDir)) return string.Empty;
- lock (_lock)
- {
- if (!noCache && _cache.TryGetValue(workingDir, out var dict) && dict.TryGetValue(args, out var v))
- return v;
- }
- try
- {
- var psi = new ProcessStartInfo
- {
- FileName = "git",
- Arguments = args,
- WorkingDirectory = workingDir,
- UseShellExecute = false,
- RedirectStandardOutput = true,
- RedirectStandardError = true,
- StandardOutputEncoding = Encoding.UTF8,
- CreateNoWindow = true
- };
- var process = System.Diagnostics.Process.Start(psi);
- process.WaitForExit(1000);
- var output = process.StandardOutput.ReadToEnd().Trim();
- var error = process.StandardError.ReadToEnd().Trim();
- if (process.ExitCode != 0 || !string.IsNullOrEmpty(error))
- return string.Empty;
- lock (_lock)
- {
- if (!_cache.ContainsKey(workingDir))
- _cache[workingDir] = new Dictionary<string, string>();
- _cache[workingDir][args] = output;
- }
- return output;
- }
- catch
- {
- return string.Empty;
- }
- }
- public static void ClearCache(string dir = null)
- {
- lock (_lock)
- {
- if (dir == null) _cache.Clear();
- else _cache.Remove(dir);
- }
- }
- }
- }
|