Example usage for org.eclipse.jgit.api Git log

List of usage examples for org.eclipse.jgit.api Git log

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git log.

Prototype

public LogCommand log() 

Source Link

Document

Return a command object to execute a Log command

Usage

From source file:com.romanenco.gitt.git.GitHelper.java

License:Open Source License

/**
 * Read log messages, up to maxRecords/*from w  w w.  j  a  v a  2 s  .c o  m*/
 * 
 * @param repoPath
 * @param maxRecords
 * @return
 */
public static List<LogEntry> readRepoHistory(String repoPath, int maxRecords) {
    ArrayList<LogEntry> result = new ArrayList<GitHelper.LogEntry>(maxRecords);
    try {
        Git git = Git.open(new File(repoPath));
        Iterable<RevCommit> logs = git.log().call();
        for (RevCommit commit : logs) {
            result.add(new LogEntry(commit));
            if (--maxRecords == 0)
                break;
        }
    } catch (IOException e) {
        Log.e(TAG, "IO", e);
    } catch (NoHeadException e) {
        Log.e(TAG, "NoHead", e);
    } catch (GitAPIException e) {
        Log.e(TAG, "GitApi", e);
    }
    if (maxRecords > 0) {
        result.trimToSize();
    }
    return result;
}

From source file:com.sbt.plugins.MyMojo.java

License:Apache License

private void writeLogsInWriter(Writer writer) throws IOException, GitAPIException {
    Repository existingRepo = new FileRepositoryBuilder().setGitDir(new File("./.git")).build();
    Git git = new Git(existingRepo);
    LogCommand logCommand = git.log();
    Iterable<RevCommit> logs = logCommand.call();
    for (RevCommit current : logs) {
        writer.write(current.getName() + ": " + current.getFullMessage());
        writer.write(LINE_SEPARATOR);//from   www .j a v  a 2s .  co m
    }
}

From source file:com.searchcode.app.jobs.repository.IndexGitHistoryJob.java

public void getGitChangeSets() throws IOException, GitAPIException {
    //Repository localRepository = new FileRepository(new File("./repo/server/.git"));
    Repository localRepository = new FileRepository(new File("./repo/thumbor/.git"));

    Git git = new Git(localRepository);
    Iterable<RevCommit> logs = git.log().call();

    List<GitChangeSet> gitChangeSets = new ArrayList<>();
    for (RevCommit rev : logs) {
        String message = rev.getFullMessage();
        String author = rev.getAuthorIdent().getName();

        Date expiry = new Date(Long.valueOf(rev.getCommitTime()) * 1000);
        System.out.println(expiry.toString() + " " + rev.getCommitTime() + " " + rev.getName());

        gitChangeSets.add(new GitChangeSet(message, author, rev.getName(), expiry));
    }// www.  j av a2s. co m

    gitChangeSets = Lists.reverse(gitChangeSets);

    // TODO currently this is ignoring the very first commit changes need to include those
    for (int i = 1; i < gitChangeSets.size(); i++) {
        System.out.println("///////////////////////////////////////////////");
        this.getRevisionChanges(localRepository, git, gitChangeSets.get(i - 1), gitChangeSets.get(i));
    }

}

From source file:com.smartbear.collab.util.ChangeListUtils.java

License:Apache License

public static List<ChangeList> VcsFileRevisionToChangeList(String rootDirectory, ScmToken scmToken,
        Map<VcsFileRevision, CommittedChangeList> commits, Project project) {
    List<ChangeList> changeLists = new ArrayList<ChangeList>();
    ProjectLevelVcsManager projectLevelVcsManager = ProjectLevelVcsManager.getInstance(project);

    for (Map.Entry<VcsFileRevision, CommittedChangeList> commit : commits.entrySet()) {
        VcsFileRevision fileRevision = commit.getKey();
        CommittedChangeList committedChangeList = commit.getValue();

        CommitInfo commitInfo = new CommitInfo(fileRevision.getCommitMessage(), fileRevision.getRevisionDate(),
                fileRevision.getAuthor(), false, fileRevision.getRevisionNumber().asString(), "");
        List<Version> versions = new ArrayList<Version>();
        String scmRepoURL = "";
        String scmRepoUUID = "";
        for (Change change : committedChangeList.getChanges()) {
            String fileContent = "";
            try {
                fileContent = change.getAfterRevision().getContent();
            } catch (VcsException ve) {
                log.severe(scmToken.name() + " error: " + ve.getMessage());
            }/*from   w  w w  . j  a  v  a2 s. c  om*/
            ContentRevision baseRevision = change.getBeforeRevision();
            BaseVersion baseVersion;
            if (baseRevision == null) {
                baseVersion = null;
            } else {
                String baseMd5 = "";
                String baseScmPath = getScmPath(rootDirectory, baseRevision.getFile().getPath());
                try {
                    baseMd5 = getMD5(baseRevision.getContent().getBytes());
                } catch (VcsException ve) {
                    log.severe(scmToken.name() + " error: " + ve.getMessage());
                }
                String baseVersionName = "";
                baseVersionName = getScmVersionName(scmToken, baseRevision);
                baseVersion = new BaseVersion(change.getFileStatus().getId(), baseMd5, commitInfo,
                        CollabConstants.SOURCE_TYPE_SCM, baseVersionName, baseScmPath);
            }

            //Version
            String localPath = change.getAfterRevision().getFile().getPath();
            String scmPath = getScmPath(rootDirectory, change.getAfterRevision().getFile().getPath());
            String md5 = getMD5(fileContent.getBytes());
            String action = change.getFileStatus().getId();
            String scmVersionName = getScmVersionName(scmToken, change.getAfterRevision());
            Version version = new Version(scmPath, md5, scmVersionName, localPath, action,
                    CollabConstants.SOURCE_TYPE_SCM, baseVersion);

            versions.add(version);

            if (scmRepoURL.equals("")) {
                switch (scmToken) {
                case SUBVERSION: // TODO: can probably get this in a less hacky way with svnkit, since we need that anyway now?
                    String fullPath = fileRevision.getChangedRepositoryPath().toPresentableString(); // this gives the full path down to the file, so:
                    if (fullPath.endsWith(scmPath) && fullPath.indexOf(scmPath) > 0) {
                        scmRepoURL = fullPath.substring(0, fullPath.indexOf(scmPath) - 1); // -1 to trim off trailing "/"
                    }
                    break;
                case GIT:
                    VcsRoot vcsRoot = projectLevelVcsManager.getVcsRootObjectFor(change.getVirtualFile());
                    FileRepositoryBuilder builder = new FileRepositoryBuilder();
                    try {
                        Repository gitRepo = builder.readEnvironment()
                                .findGitDir(new File(vcsRoot.getPath().getCanonicalPath())).build();
                        Config gitConfig = gitRepo.getConfig();

                        Set<String> remotes = gitConfig.getSubsections("remote");
                        Set<String> remoteURLs = new HashSet<String>();
                        if (remotes.isEmpty()) {
                            // TODO: figure out what existing collab clients use for git repo url for local-only situation
                            scmRepoURL = "git: local-only";
                        } else {
                            for (String remoteName : remotes) {
                                remoteURLs.add(gitConfig.getString("remote", remoteName, "url"));
                            }
                            Iterator<String> urlitr = remoteURLs.iterator();

                            if (remoteURLs.size() == 1) { // the easy case
                                scmRepoURL = urlitr.next();
                            } else {
                                // TODO we have more than one, so figure out what the existing clients do here
                                // for now, just grab the first one
                                scmRepoURL = urlitr.next();
                            }
                        }
                    } catch (Exception e) {
                        log.severe("GIT interaction error: " + e.getMessage());
                    }
                    break;
                default:
                    log.severe("Unsupported SCM: " + scmToken);
                    break;
                }

            }
            if (scmRepoUUID.equals("")) {
                switch (scmToken) {
                case SUBVERSION:
                    if (!scmRepoURL.equals("")) {
                        try {
                            SVNURL svnURL = SVNURL.parseURIEncoded(scmRepoURL);
                            SVNClientManager cm = SVNClientManager.newInstance();
                            SVNWCClient workingCopyClient = cm.getWCClient();
                            SVNInfo svnInfo = workingCopyClient.doInfo(svnURL, SVNRevision.UNDEFINED,
                                    SVNRevision.HEAD);
                            scmRepoUUID = svnInfo.getRepositoryUUID();
                        } catch (SVNException svne) {
                            log.severe("SVN error: " + svne.getMessage());
                        }
                    }
                    break;
                case GIT: // for this, we use the sha1 of the first git commit in the project
                    FileRepositoryBuilder builder = new FileRepositoryBuilder();
                    try {
                        VcsRoot vcsRoot = projectLevelVcsManager.getVcsRootObjectFor(change.getVirtualFile());
                        Repository gitRepo = builder.readEnvironment()
                                .findGitDir(new File(vcsRoot.getPath().getCanonicalPath())).build();
                        Git git = new Git(gitRepo);

                        Iterable<RevCommit> gitCommits = git.log().all().call();
                        Iterator<RevCommit> gitr = gitCommits.iterator();

                        RevCommit firstCommit = null;
                        while (gitr.hasNext()) { // run through log,
                            firstCommit = gitr.next();
                        }
                        if (firstCommit != null) {
                            scmRepoUUID = firstCommit.getName(); // sha1 of first commit in repo, lower-case hexadecimal
                        }
                    } catch (Exception e) {
                        log.severe("GIT interaction error: " + e.getMessage());
                    }

                    break;
                default:
                    log.severe("Unsupported SCM: " + scmToken);
                    break;
                }
            }
        }

        // we might have to do something more sophisticated once we support other SCMs, but for git and svn
        // collab only really needs an URL and some sort of UUID-ish value
        ArrayList<String> scmConnectionParameters = new ArrayList<String>(2);
        scmConnectionParameters.add(scmRepoURL);
        scmConnectionParameters.add(scmRepoUUID);

        ChangeList changeList = new ChangeList(scmToken, scmConnectionParameters, commitInfo, versions);
        changeLists.add(changeList);
    }
    return changeLists;
}

From source file:com.tasktop.c2c.server.scm.service.GitBrowseUtil.java

License:Open Source License

private static void addHistory(Git git, Trees.Tree tree, ObjectId revision, String path)
        throws MissingObjectException, IncorrectObjectTypeException, GitAPIException {
    LogCommand logCommand = git.log();
    logCommand.add(revision);/*from   ww  w  .j a  v a 2  s  .c  o  m*/

    logCommand.addPath(path);

    for (RevCommit revCommit : logCommand.call()) {
        Commit commit = GitDomain.createCommit(revCommit);
        tree.setLatestCommit(commit);
        break;
    }

}

From source file:com.verigreen.collector.common.EmailSender.java

License:Apache License

public String getCommitMessage(String commitId) {
    String commitMessage = null;/*from www  . ja v  a  2 s .c om*/
    try {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        String repoPath = VerigreenNeededLogic.properties.getProperty("git.repositoryLocation");
        Repository repo = builder.setGitDir(new File(repoPath)).setMustExist(true).build();
        Git git = new Git(repo);
        Iterable<RevCommit> log = git.log().call();
        Iterator<RevCommit> iterator = log.iterator();
        while (commitMessage == null && iterator.hasNext()) {
            RevCommit rev = iterator.next();
            String commit = rev.getName().substring(0, 7);
            if (commit.equals(commitId)) {
                commitMessage = rev.getFullMessage();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return commitMessage;
}

From source file:com.verigreen.collector.rest.CommitMessage.java

License:Apache License

@GET
@Produces(MediaType.APPLICATION_JSON)/*  ww w  .java2 s  . c om*/
public static Response get() {
    Map<String, String> logMessages = new HashMap<>();
    try {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repo = builder
                .setGitDir(new File(VerigreenNeededLogic.properties.getProperty("git.repositoryLocation")))
                .setMustExist(true).build();
        Git git = new Git(repo);
        Iterable<RevCommit> log = git.log().call();
        for (Iterator<RevCommit> iterator = log.iterator(); iterator.hasNext();) {
            RevCommit rev = iterator.next();
            logMessages.put(rev.getName(), rev.getFullMessage());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return Response.status(Status.OK).entity(logMessages).build();
}

From source file:de.felixschulze.gradle.helper.GitHelper.java

License:Open Source License

public int numberOfCommits() throws GitAPIException {
    Git git = new Git(repository);
    Iterable<RevCommit> logs = git.log().call();
    Iterator<RevCommit> i = logs.iterator();
    int numberOfCommits = 0;
    while (i.hasNext()) {
        numberOfCommits++;/*w ww. j a v  a 2 s . c om*/
        i.next();
    }
    return numberOfCommits;
}

From source file:de.sjka.jenkins.view.branches.BranchOverviewAction.java

License:Open Source License

@SuppressWarnings("rawtypes")
public List<BranchState> getBranches() {
    // read remote branches from the repository
    Map<String, String> branches = new HashMap<String, String>();
    Map<String, String> messages = new HashMap<String, String>();
    try {//w ww . j a  v a2  s .com
        if (target.getScm() instanceof GitSCM) {
            GitSCM gitSCM = (GitSCM) target.getScm();
            String location = target.getLastBuild().getWorkspace().getRemote() + gitSCM.getRelativeTargetDir();
            Git git = Git.open(new File(location));
            for (Ref ref : git.branchList().setListMode(ListMode.REMOTE).call()) {
                String name = ref.getName();
                if (name.endsWith("/HEAD")) {
                    continue;
                }
                if (name.startsWith("refs/remotes/")) {
                    name = name.replace("refs/remotes/", "");
                }
                branches.put(name, ref.getObjectId().getName());
                System.out.println(name);
                messages.put(name, git.log().add(ref.getObjectId()).call().iterator().next().getShortMessage());
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (GitAPIException e) {
        throw new RuntimeException(e);
    }

    // read commits from the build history
    Map<String, AbstractBuild> builds = new HashMap<String, AbstractBuild>();
    for (AbstractBuild build : target.getBuilds()) {
        for (Entry<String, Build> entry : ((Actionable) build).getAction(BuildData.class)
                .getBuildsByBranchName().entrySet()) {
            String sha1 = entry.getValue().getRevision().getSha1String();
            int number = entry.getValue().getBuildNumber();
            if (number == build.getNumber() && builds.get(sha1) == null) {
                builds.put(sha1, build);
                break;
            }
        }
    }

    // create model
    Map<String, BranchState> ret = new HashMap<String, BranchState>();
    for (Entry<String, String> branch : branches.entrySet()) {
        AbstractBuild build = builds.get(branch.getValue());
        BranchState state = new BranchState(branch.getKey(), branch.getValue(), messages.get(branch.getKey()),
                build);
        ret.put(branch.getKey(), state);
    }

    return new ArrayList<BranchState>(ret.values());
}

From source file:eu.hohenegger.gitmine.ui.views.TimeLapseView.java

License:Open Source License

@Inject
public void setSelection(@Optional @Named(IServiceConstants.ACTIVE_SELECTION) IStructuredSelection selection) {
    if (scale == null || scale.isDisposed()) {
        return;/* ww w.j ava  2  s  . c o m*/
    }

    if (selection == null) {
        return;
    }

    if (!(selection.getFirstElement() instanceof PlatformObject)) {
        return;
    }

    PlatformObject firstElement = (PlatformObject) selection.getFirstElement();

    resource = (IResource) firstElement.getAdapter(IResource.class);

    if (resource == null) {
        return;
    }

    IProject project = resource.getProject();

    RepositoryMapping mapping = RepositoryMapping.getMapping(project.getLocation());
    repository = mapping.getRepository();

    String relativePath = createRelativePath(resource.getLocation().toString(), repository);

    Git git = Git.wrap(repository);

    commitList = new ArrayList<>();

    Iterable<RevCommit> commits;

    LogCommand logCmd = git.log();
    if (!relativePath.isEmpty()) {
        logCmd.addPath(relativePath);
    }
    try {
        commits = logCmd.call();

        for (RevCommit revCommit : commits) {
            commitList.add(0, revCommit);
        }
        scale.setMaximum(commitList.size() - 1);
    } catch (NoHeadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (GitAPIException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}