2013-05-17 22 views
3

最簡單的方式在JGit添加或更新文件是這樣的:JGit:是否有添加一個線程安全的方式和更新文件

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

但是,假定該文件在Git的工作目錄存在。 如果我有一個多線程安裝(使用Scala和Akka),是否有一種方法只能在裸存儲庫上工作,直接將數據寫入JGit,避免必須先將文件寫入工作目錄?

得到該文件,這似乎是一起工作:

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

是否有添加或更新的文件類似的東西?

回答

3

「添加」是將文件放置在索引中的高級抽象。在裸倉庫中,您缺少索引,因此這不是功能之間的1:1對應關係。相反,您可以在新的提交中創建一個文件。爲此,您可以使用ObjectInserter將對象添加到存儲庫(請每個線程一個)。那麼你會:

  1. 文件的內容添加到存儲庫,作爲一個blob,通過插入其字節(或提供InputStream)。

  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", "[email protected]"); 
    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

+0

感謝您的詳細解答。我嘗試使用代碼(稍作修改)添加2個文件,但是當我嘗試使用命令行克隆存儲庫時,它似乎是空的。存儲庫的初始化方式有什麼特別之處嗎?它需要有一個主分支什麼的? – Allan

+1

它需要一個指向(最終)指向此提交的HEAD。典型的機制是'HEAD' - >'refs/heads/master' - >這個提交ID。 –

+0

有關如何使用JGit創建存儲庫的任何提示,以便它可以與上面的代碼一起使用?謝謝! – Allan