JGit:找不到教程或简单的例子

我找不到JGit的工作教程。

如果任何人有一个很好的链接或者一个简单的例子(f.ex.cat-a-file),这将是非常有帮助的( 如何在JGit中“捕捉”一个文件的答案不能用JGit V进行编译1.0)。

不幸的是,对于初学者来说官方的JGit文档对我来说并不是很有用。 但是我认为肯定有很多开发者在使用JGit?

事实上,在API的使用情况方面,这方面的情况很less。

为了其他读者的缘故,我特此为大多数常见的操作提供一个简单的testing:

  1. 创build存储库
  2. 克隆它
  3. 添加一个文件
  4. 承诺
  5. 追踪origin/mastermaster (这是必要的,如果你克隆裸露的回购)
  6. 拉(无用,在这种情况下,但无论如何)

特别要注意的是添加文件需要一个模式 ,而不是path。 此外,由于克隆上存在master ,所以跟踪需要.setForce(true)

请认为这个例子是简单和独立的。

 import java.io.File; import java.io.IOException; import org.eclipse.jgit.api.*; import org.eclipse.jgit.api.errors.*; import org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode; import org.eclipse.jgit.internal.storage.file.FileRepository; import org.eclipse.jgit.lib.Repository; import org.junit.Before; import org.junit.Test; public class TestJGit { private String localPath, remotePath; private Repository localRepo; private Git git; @Before public void init() throws IOException { localPath = "/home/me/repos/mytest"; remotePath = "git@github.com:me/mytestrepo.git"; localRepo = new FileRepository(localPath + "/.git"); git = new Git(localRepo); } @Test public void testCreate() throws IOException { Repository newRepo = new FileRepository(localPath + ".git"); newRepo.create(); } @Test public void testClone() throws IOException, GitAPIException { Git.cloneRepository().setURI(remotePath) .setDirectory(new File(localPath)).call(); } @Test public void testAdd() throws IOException, GitAPIException { File myfile = new File(localPath + "/myfile"); myfile.createNewFile(); git.add().addFilepattern("myfile").call(); } @Test public void testCommit() throws IOException, GitAPIException, JGitInternalException { git.commit().setMessage("Added myfile").call(); } @Test public void testPush() throws IOException, JGitInternalException, GitAPIException { git.push().call(); } @Test public void testTrackMaster() throws IOException, JGitInternalException, GitAPIException { git.branchCreate().setName("master") .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM) .setStartPoint("origin/master").setForce(true).call(); } @Test public void testPull() throws IOException, GitAPIException { git.pull().call(); } } 

我已经创build了一个jgit-cookbook ,也就是可以用来在JGit中做各种事情的简单自包含的食谱的集合。 它应该已经包含了你会用JGit做的基本的事情,欢迎新的片段的build议!

这是一个非常好的“入门”教程: http : //alblue.bandlem.com/2013/11/embedding-jgit.html

我编写了JGit入门指南,通过JGit API指导创build或克隆存储库,获取更改,添加和删除历史logging中的文件,检查历史logging,最后推回原始存储库。

如果您更喜欢阅读源代码,本文将使用学习testing来演示API的用法。 源代码除了JGit本身之外没有任何依赖关系,所以它可以被粘贴到select的IDE中。 完整的清单可以在这里find: https : //gist.github.com/rherrmann/433adb44b3d15ed0f0c7

虽然这篇文章并没有详细说明,但是可以链接到我之前公布的更深入的信息。 例如,当涉及到authentication , 访问 , 初始化 , 克隆存储库或创build差异 。

请参阅用户指南: http : //wiki.eclipse.org/JGit/User_Guide

请参阅教程: https : //code.google.com/p/egit/wiki/JGitTutorialRepository