修改存储库的所有提交的所有注释

时间:2015-06-30 06:54:37

标签: azure-devops libgit2sharp

我正在将我们的内部部署tfs存储库移动到visualstudio online。在这个过程中,我更愿意将所有内容转换为git。 我发现这个(*)在线发布,一切正常。但现在我想使用libgit2sharp修改所有注释,以指向正确的工作项。

我拼凑了一些可以解决问题的代码:

Dictionary<string,string> links; //contains all links between new and old workitems, keys: old workitems, values: new workitems

using (var repo = new Repository(@"D:\gittfs\testproject"))
{
    foreach (var commit in repo.Commits)
    {
        var commitMessage = commit.Message;
        var regex = new Regex(@"#[0-9]*");
        foreach (Match match in regex.Matches(commitMessage))
        {
            string newId;
            if (links.TryGetValue(match.ToString(), out newId))
            {
                commitMessage = commitMessage.Replace(match.ToString(), newId);
            }
        }

        var c = repo.Commit(commitMessage, new CommitOptions { AmendPreviousCommit = true });
    }
}

此代码运行没有问题,如果我将c.Messagecommit.Message进行比较,我可以看到其中一些被替换。问题是程序运行后,修改后的提交都没有在存储库中。所以我觉得我还在做错什么?

(*)https://www.microsoft.com/en-gb/developers/articles/week02mar2014/migrating-a-tfs-tfvc-based-team-project-to-a-git-team-project-retaining-as-much-source-and-work-item-history-as-possible/

2 个答案:

答案 0 :(得分:0)

我认为您可能更喜欢使用某些 git filter-branch 之类的功能。

LibGit2Sharp通过 HistoryRewriter 类型公开此内容。

您可以查看 FilterBranchFixture 测试套件以获取灵感。

答案 1 :(得分:0)

以下代码为我做了诀窍。 thnx nulltoken!

 var rewriteHistoryOptions = new RewriteHistoryOptions()
            {
                CommitHeaderRewriter = commit =>
                {
                    var commitMessage = commit.Message;
                    bool stuffreplaced = false;
                    var r = new Regex(@"#[0-9]*\ ");
                    foreach (Match match in r.Matches(commit.Message))
                    {
                        string value;
                        if (links.TryGetValue(match.ToString().TrimEnd(), out value))
                        {
                            commitMessage = commitMessage.Replace(match.ToString().Trim(), value);
                            Console.WriteLine(commit.Id + ": " + match.ToString() + " replaced by " + value);
                            stuffreplaced = true;
                            counter++;
                        }
                    }
                    if (stuffreplaced)
                    {
                        return CommitRewriteInfo.From(commit, message: commitMessage);
                    }
                    else
                    {
                        return CommitRewriteInfo.From(commit);
                    }
                }
            };

            repo.Refs.RewriteHistory(rewriteHistoryOptions, repo.Commits);