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

Multithreading JGit:有没有线程安全的方法来添加和更新文件,multithreading,git,jgit,Multithreading,Git,Jgit,在JGit中添加或更新文件的简单方法如下: git.add().addFilepattern(file).call() 但这假设该文件存在于Git工作目录中。 如果我有一个多线程设置(使用Scala和Akka),有没有一种方法可以只在一个裸存储库上工作,直接将数据写入JGit,而不必首先将文件写入工作目录 要获取该文件,这似乎需要: git.getRepository().open(objId).getBytes() 添加或更新文件有类似的功能吗?“添加”是一种高级抽象,它将文件放在

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

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

要获取该文件,这似乎需要:

  git.getRepository().open(objId).getBytes()
添加或更新文件有类似的功能吗?

“添加”是一种高级抽象,它将文件放在索引中。在裸存储库中,您缺少索引,因此这不是功能之间的1:1对应关系。相反,您可以在新提交中创建文件。要做到这一点,您可以使用添加对象到存储库中(请每个线程添加一个)。那么你会:

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

  • 使用创建包含新文件的树

  • 使用创建指向树的提交

  • 例如,要创建仅包含您的文件的新提交(无父级):

    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
    提交id返回为
    commitId

    谢谢您的详细回答。我尝试使用代码(稍作修改)添加2个文件,但当我尝试在以后使用命令行克隆存储库时,它似乎是空的。存储库的初始化方式是否有特殊之处?它需要一个主分支还是什么?它需要一个指向(最终)这个提交的头。典型的机制是
    HEAD
    ->
    refs/heads/master
    ->这个提交ID。关于如何使用JGit创建存储库以便它与上述代码一起工作,有什么提示吗?谢谢查看
    RefUpdate
    ——在这些评论中很难写太多,因此如果您对使用此API有疑问,可能需要另一个问题。