使用Java API从GitHub获取所有提交

时间:2016-07-31 08:55:17

标签: java github github-api

我想使用Java API从GitHub获取所有提交。到目前为止,我设法创建了这个简单的代码:

import java.io.IOException;
import java.util.List;
import org.eclipse.egit.github.core.Repository;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.eclipse.egit.github.core.service.RepositoryService;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class GithubImplTest
{
    public void testSomeMethod() throws IOException
    {
        GitHubClient client = new GitHubClient();
        client.setCredentials("sonratestw@gmail.com", "sono");

        RepositoryService service = new RepositoryService(client);

        List<Repository> repositories = service.getRepositories();

        for (int i = 0; i < repositories.size(); i++)
        {
            Repository get = repositories.get(i);
            System.out.println("Repository Name: " + get.getName());
        }
    }
}

如何从此帐户获取所有提交到存储库?

2 个答案:

答案 0 :(得分:3)

使用您正在使用的Eclipse GitHub Java API,类CommitService提供对存储库提交的访问。可以调用方法getCommits(repository)来检索给定存储库的所有提交的列表。

打印存储库的所有提交的示例代码:

CommitService commitService = new CommitService(client);
for (RepositoryCommit commit : commitService.getCommits(repository)) {
    System.out.println(commit.getCommit().getMessage());
}

答案 1 :(得分:1)

对于给定的存储库,您可以使用JGit git.log()函数(LogCommand):

public static void main(String[] args) throws IOException, InvalidRefNameException, GitAPIException {
    try (Repository repository = CookbookHelper.openJGitCookbookRepository()) {
        try (Git git = new Git(repository)) {
            Iterable<RevCommit> commits = git.log().all().call();
            int count = 0;
            for (RevCommit commit : commits) {
                System.out.println("LogCommit: " + commit);
                count++;
            }
            System.out.println(count);
        }
    }
}

根据您的Eclipse版本,您需要jgit-core maven dependency

<!-- https://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit -->
<dependency>
    <groupId>org.eclipse.jgit</groupId>
    <artifactId>org.eclipse.jgit</artifactId>
    <version>4.4.1.201607150455-r</version>
</dependency>