JGit:有没有线程安全的方式来添加和更新文件?



在JGit中添加或更新文件的简单方法如下:

  git.add().addFilepattern(file).call()

但这假设该文件存在于Git工作目录中。如果我有一个多线程设置(使用Scala和Akka),是否有一种方法可以只在裸存储库上工作,将数据直接写入JGit,而不必首先在工作目录中写入文件?

对于获取文件,似乎可以使用:

  git.getRepository().open(objId).getBytes()

是否有类似的添加或更新文件?

"Add"是将文件放入索引的高级抽象。在裸存储库中,没有索引,因此功能之间不是1:1的对应关系。相反,您可以在新提交中创建一个文件。为此,您将使用ObjectInserter向存储库添加对象(请每个线程一个对象)。那么你可以:

  1. 通过插入其字节(或提供InputStream),将文件的内容作为blob添加到存储库中。

  2. 创建包含新文件的树,通过使用TreeFormatter

  3. 通过CommitBuilder创建一个指向树的提交。

例如,要创建一个只包含文件的新提交(没有父提交):
ObjectInserter repoInserter = repository.newObjectInserter();
ObjectId blobId;
try
{
    // Add a blob to the repository
    ObjectId blobId = repoInserter.insert(OBJ_BLOB, "Hello World!n".getBytes());
    // Create a tree that contains the blob as file "hello.txt"
    TreeFormatter treeFormatter = new TreeFormatter();
    treeFormatter.append("hello.txt", FileMode.TYPE_FILE, blobId);
    ObjectId treeId = treeFormatter.insertTo(repoInserter);
    // Create a commit that contains this tree
    CommitBuilder commit = new CommitBuilder();
    PersonIdent ident = new PersonIdent("Me", "me@example.com");
    commit.setCommitter(ident);
    commit.setAuthor(ident);
    commit.setMessage("This is a new commit!");
    commit.setTreeId(treeId);
    ObjectId commitId = repositoryInserter.insert(commit);
    repoInserter.flush();
}
finally
{
    repoInserter.release();
}

现在您可以git checkout作为commitId返回的提交id

最新更新