「添加」是將文件放置在索引中的高級抽象。在裸倉庫中,您缺少索引,因此這不是功能之間的1:1對應關係。相反,您可以在新的提交中創建一個文件。爲此,您可以使用ObjectInserter
將對象添加到存儲庫(請每個線程一個)。那麼你會:
文件的內容添加到存儲庫,作爲一個blob,通過插入其字節(或提供InputStream
)。
使用TreeFormatter
創建一個包含新文件的樹。
通過使用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
。
感謝您的詳細解答。我嘗試使用代碼(稍作修改)添加2個文件,但是當我嘗試使用命令行克隆存儲庫時,它似乎是空的。存儲庫的初始化方式有什麼特別之處嗎?它需要有一個主分支什麼的? – Allan
它需要一個指向(最終)指向此提交的HEAD。典型的機制是'HEAD' - >'refs/heads/master' - >這個提交ID。 –
有關如何使用JGit創建存儲庫的任何提示,以便它可以與上面的代碼一起使用?謝謝! – Allan