using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace SKMC.Api.Common.Version
{
///
/// git指令帮助类
///
internal static class GitCommandHelper
{
private static readonly Dictionary> _cache = new Dictionary>();
private static readonly object _lock = new object();
///
/// 通过执行git指令获取git提交的哈希值/id
///
/// git文件存在的文件夹
///
///
///
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();
_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);
}
}
}
}