8

一个 JGit 初学者问题:

我使用 JGit 从存储库中读取文件 (BLOB) 并操作其内容。之后,我想将具有相同文件名的新内容作为新提交写回存储库。但是如何使用 JGit 提交新内容呢?

我的伪代码:

String gitUrl = "path/to/repository/.git";
Repository repository = new FileRepository(gitUrl);
String filename = "test/seppl.txt";
blobId = getIdOf(filename);
ObjectLoader object = repository.open(blobId, Constants.OBJ_BLOB);
ObjectStream is = object.openStream();
String newContent = processStream(is);
// How to commit the newContent in filename?

我是否必须将其写入文件并使用AddCommandCommitCommandnewContent提交该文件?或者我可以将字符串“on-the-fly”以相同的文件名写入存储库吗?

网络上是否有任何使用 JGit 提交的示例?

4

3 回答 3

6

我认为除了使用 CommitCommand 之外没有其他方法可以提交任何数据(合并或非常具体的此类操作除外)。

所以,是的,您应该对文件进行任何更改,然后添加并提交(使用 API 中的 AddCommand 和 CommitCommand)。

于 2012-04-13T13:44:42.557 回答
4

Yes, of course you can do what you want, but just not using Add/Commit as they are part of the high-level Porcelein API which is just a convenience API built on top of the low level API. Thus they just implement the most common use cases.

What you need to do is to look at the implementation of the AddCommand and CommitCommand to see how to use the lower-level API to create BLOB objects and then tree objects and than commit objects.

I'd second the recommendation that you thoroughly read chapter 9 of the Pro Git book so that you properly understand how Git works on a low level.

于 2012-05-07T05:58:10.043 回答
3

您可能想研究在 Git 中使用 Blob。此技术用于在签署标签时存储公共 PGP 密钥。看起来您想要的内容仍然必须放入一个文件中,但它可以是一个临时文件。当有人拉动时,该文件将不存在于主目录中。它将是树中的一个条目,作为一个 blob。

http://book.git-scm.com/7_raw_git.html

告诉它-w写入条目并返回哈希。

git hash-object -w myfile.txt
6ff87c4664981e4397625791c8ea3bbb5f2279a3

更新

我在手机上浏览了此条目,因此对您提供的细节没有那么关注。是的,您需要将字符串写入文件,但不,您不必像普通文件一样添加它。我怀疑 JGit 有能力做hash-object. 看起来您已经有了一些代码来处理 BLOB 条目。也许对哈希对象有更高级别的调用,您不直接处理 BLOB。

考虑到 Git 中的所有内容都依赖于内容的哈希值,我想说的是,即使您确实找到了一种直接编写字符串的方法,也不应该这样做。您应该使用相同的文件名重新提交对象,以便获得新的哈希和更新的条目。

于 2012-04-13T14:57:51.757 回答