using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace SKMC.Api.Common.Version
{
public class RuntimeVersionProvider
{
///
/// 获取模块版本信息
///
/// 路径
///
public ModuleVersion GetModuleVersion(string directory)
{
if (!Directory.Exists(directory))
return new ModuleVersion { Name = Path.GetFileName(directory) };
var commit = GitCommandHelper.Run(directory, "rev-parse HEAD");
var branch = GitCommandHelper.Run(directory, "rev-parse --abbrev-ref HEAD");
var author = GitCommandHelper.Run(directory, "log -1 --format=%an");
var time = GitCommandHelper.Run(directory, "log -1 --format=%ci");
var msg = GitCommandHelper.Run(directory, "log -1 --format=%s");
var dirty = !string.IsNullOrEmpty(GitCommandHelper.Run(directory, "status --porcelain", noCache: true));
DateTime.TryParse(time?.Split('+')[0]?.Trim(), out var commitTime);
var moduleVersion = new ModuleVersion
{
Name = Path.GetFileName(directory),
CommitHash = commit,
Branch = branch,
Author = author,
CommitTime = commitTime,
CommitMessage = msg,
HasUncommittedChanges = dirty,
Path = directory,
AssemblyFileVersion = GetAssemblyVersion(directory)
};
return moduleVersion;
}
///
/// 获取项目版本
///
///
///
public ProjectVersion GetProjectVersions(string rootDir)
{
var project = new ProjectVersion
{
ProjectName = Path.GetFileName(rootDir),
BuildTime = DateTime.Now,
RootCommitHash = GitCommandHelper.Run(rootDir, "rev-parse HEAD")
};
foreach (var dir in Directory.GetDirectories(rootDir))
{
var folderName = Path.GetFileName(dir);
// 过滤文件
if (folderName.Equals(".git") || folderName.Equals("packages") || folderName.Equals("bin") || folderName.Equals("obj"))
continue;
// 查找是否存在csproj格式文件
if (Directory.GetFiles(dir, "*.csproj", SearchOption.TopDirectoryOnly).Length > 0)
{
project.Modules.Add(GetModuleVersion(dir));
}
}
return project;
}
public string FindGitRoot(string startDir)
{
try
{
var dir = new DirectoryInfo(startDir);
while (dir != null)
{
if (Directory.Exists(Path.Combine(dir.FullName, ".git")))
return dir.FullName;
dir = dir.Parent;
}
}
catch { }
return null;
}
private string GetAssemblyVersion(string modulePath)
{
try
{
var moduleName = Path.GetFileName(modulePath);
var dllPath = Path.Combine(Path.GetDirectoryName(AppContext.BaseDirectory), $"{moduleName}.dll");
var exePath = Path.Combine(Path.GetDirectoryName(AppContext.BaseDirectory), $"{moduleName}.exe");
if (!System.IO.File.Exists(dllPath) && !System.IO.File.Exists(exePath))
return "unknown";
var path = new[] { exePath, dllPath }.FirstOrDefault(System.IO.File.Exists);
var assembly = Assembly.LoadFrom(path);
var informationalVersion = assembly.GetCustomAttributesData()
.FirstOrDefault(a => a.AttributeType == typeof(AssemblyInformationalVersionAttribute))?
.ConstructorArguments.FirstOrDefault().Value?.ToString();
if (!string.IsNullOrEmpty(informationalVersion))
return informationalVersion;
return $"{assembly.GetName().Version}";
}
catch
{
return "unknown";
}
}
}
}