繁体   English   中英

如何使用 LibGit2Sharp 控制行尾转换?

[英]How do I control line endings conversion with LibGit2Sharp?

我正在使用 LibGit2Sharp 访问远程 Git 存储库。 场景如下:

  1. 使用Repository.Clone方法从远程 URL 克隆存储Repository.Clone
  2. 使用Commands.Fetch方法从远程存储库中获取。
  3. 通过标记commit = repo.Tags["myTag"].PeeledTarget as Commit;导航到所需的commit = repo.Tags["myTag"].PeeledTarget as Commit;
  4. 获取提交树tree = commit.Tree
  5. 导航树并获取文件 blob blob = tree["my path"].Target as Blob
  6. 从 blob blob.GetContentStream()获取文件内容

结果,我得到了带有 Unix 行结尾的文件文本,因为它存储在存储库中。 但我更喜欢在我的本地副本中有 Windows 行结尾。

我需要让 Git 自动为我转换行尾,就像使用core.autocrlf配置选项一样。 我如何使用 LibGit2Sharp 做到这一点?

检查LibGit2Sharp.Tests/BlobFixture.cs是否证明 core.autocrlf 处于活动状态:

    [InlineData("false", "hey there\n")]
    [InlineData("input", "hey there\n")]
    [InlineData("true", "hey there\r\n")]
    public void CanGetBlobAsFilteredText(string autocrlf, string expectedText)
    {
        SkipIfNotSupported(autocrlf);

        var path = SandboxBareTestRepo();
        using (var repo = new Repository(path))
        {
            repo.Config.Set("core.autocrlf", autocrlf);

            var blob = repo.Lookup<Blob>("a8233120f6ad708f843d861ce2b7228ec4e3dec6");

            var text = blob.GetContentText(new FilteringOptions("foo.txt"));

            Assert.Equal(expectedText, text);
        }
    }

但请注意,如libgit2/libgit2sharp 问题 1195# 中所述

注意, core.autocrlf很糟糕并且已被弃用,应该非常避免使用正确配置的.gitattributes

OP CF 在评论中确认:

显然我必须使用IsBinary属性检查 blob 的类型并相应地使用GetContentTextGetContentStream

我正在努力解决完全相同的问题。

要获得正确的行尾,您需要调用blob.GetContentStream(new FilteringOptions(relativePath)) 该名称并不是真正的自我解释,但它会调用一个不同的函数( git_blob_filtered_content_stream ),该函数将返回带有转换后的git_blob_filtered_content_stream的内容。

https://github.com/libgit2/libgit2sharp/blob/master/LibGit2Sharp/Blob.cs#L56

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM