简体   繁体   中英

Get all commits from GitHub using Java API

I want to get all commits from GitHub using Java API. So far I managed to create this simple code:

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());
        }
    }
}

How I can get all commits into the repository from this account?

With the Eclipse GitHub Java API you are using, the class CommitService provides access to repository commits. The method getCommits(repository) can be invoked to retrieve the list of all commits for the given repository.

Sample code to print all commits of a repository:

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

For a given repository, you can use JGit git.log() function ( 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);
        }
    }
}

Depending on your Eclipse version, you would need the 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM