0

我正在尝试使用 Grit 写入 Git 存储库。我可以轻松地创建一个 repo 并提交:

repo = Repo.init_bare("grit.git")
index = Index.new(repo)
index.add('myfile.txt', 'This is the content')
index.commit('first commit')

我还可以轻松地进行第二次提交,使用第一次提交作为父提交:

index.add('myotherfile.txt', 'This is some other content')
index.commit("second commit", [repo.commits.first])

但是现在我如何在不遍历整个提交历史的情况下获取这两个文件的内容呢?我没有更聪明的方法来获取回购中文件的当前状态吗?

4

1 回答 1

1
(repo.tree / 'myfile.txt').data

具体来说,tree方法(可以接受任何提交,但默认为 master)返回Tree。Tree 有一个方便的/方法,它根据您传入的文件名返回Blob或 Tree。最后,Blob 有一个返回确切数据的data方法。

编辑:如果您想要 repo 中所有文件名的列表(这可能是一项昂贵的操作),一种方法是:

all_files = repo.status.map { |stat_file| stat_file.path }

这假设一切都被跟踪。如果您不确定,可以过滤untracked属性。

于 2011-03-13T04:32:04.327 回答