获取git版本号写入到DLL文件

发布时间 2023-12-04 17:23:55作者: 张布斯521

private static void SetGitVersion()
{

    string baseDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
    string projectDirectory = baseDirectory.Substring(0, baseDirectory.LastIndexOf("\\aspnet-core"));
    string filePath = projectDirectory + "\\aspnet-core\\common.props";

    if (File.Exists(filePath))
    {
        string content = File.ReadAllText(filePath);
        var repo = new Repository(projectDirectory);
        var hash = ((LibGit2Sharp.SymbolicReference)repo.Refs.Head).Target.TargetIdentifier;
        var dt = ((LibGit2Sharp.Commit)((LibGit2Sharp.DirectReference)((LibGit2Sharp.SymbolicReference)repo.Refs.Head).Target).Target).Author.When.DateTime;
        string dateString = dt.ToString("yyyy-MM-dd");
        Regex versionRegex = new Regex("(?<=(" + "<Version>3.0.0" + "))[.\\s\\S]*?(?=(" + "</Version>" + "))", RegexOptions.Multiline | RegexOptions.Singleline);
        string oldHash = versionRegex.Match(content).Value;
        if ("+" + hash != oldHash)
        {
            content = content.Replace(oldHash, "+" + hash);
        }
        // 读取JSON文件内容
        string json = File.ReadAllText("appsettings.json");
        // 解析JSON字符串为JObject对象
        JObject jObject = JObject.Parse(json);
        // 获取要修改的值
        JToken value = jObject.SelectToken("PublishDate");
        // 修改值
        value.Replace(dateString);
        // 将修改后的JObject对象转换回JSON字符串
        string modifiedJson = jObject.ToString();
        // 保存修改后的JSON字符串到文件
        File.WriteAllText("appsettings.json", modifiedJson);

        File.WriteAllText(filePath, content);
    }
}