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:io.syndesis.github.GitHubServiceITCase.java

License:Apache License

@Test
public void testProjectCommit() throws IOException, IllegalStateException, GitAPIException, URISyntaxException {
    URL url = this.getClass().getResource(PROJECT_DIR);
    System.out.println("Reading sample project from " + url);
    //Read from classpath sample-github-project into map
    Map<String, byte[]> files = new HashMap<>();
    Files.find(Paths.get(url.getPath()), Integer.MAX_VALUE, (filePath, fileAttr) -> fileAttr.isRegularFile())
            .forEach(filePath -> {//from   w  ww  . j  ava2  s  . co m
                if (!filePath.startsWith(".git")) {
                    byte[] content;
                    try {
                        content = Files.readAllBytes(filePath);
                        String file = filePath.toString()
                                .substring(filePath.toString().indexOf(PROJECT_DIR) + PROJECT_DIR.length() + 1);
                        files.put(file, content);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });

    User user = githubService.getApiUser();
    String cloneURL = githubService.createOrUpdateProjectFiles(REPO_NAME, user,
            "my itcase initial message" + UUID.randomUUID().toString(), files, null);
    Assertions.assertThat(cloneURL).isNotNull().isNotBlank();

    File tmpDir = Files.createTempDirectory(testName.getMethodName()).toFile();
    tmpDir.deleteOnExit();
    Git clone = Git.cloneRepository().setDirectory(tmpDir).setURI(cloneURL).call();
    PersonIdent author = clone.log().call().iterator().next().getAuthorIdent();
    Assertions.assertThat(author).isNotNull();
    Assertions.assertThat(author.getName()).isNotNull().isNotBlank();
}

From source file:net.aprendizajengrande.gitrecommender.ExtractLog.java

License:Open Source License

public static void main(String[] args) throws Exception {

    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    System.out.println("Git dir: " + args[0]);
    Repository repository = builder.setGitDir(new File(args[0])).readEnvironment() // scan environment GIT_* variables
            .findGitDir() // scan up the file system tree
            .build();/*  w  w  w  .j av  a 2s .  c om*/

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

    RevCommit previous = null;
    String previousAuthor = null;

    // author -> file -> counts
    Map<String, Map<String, Counter>> counts = new HashMap<>();
    Map<String, Counter> commitCounts = new HashMap<>(); // author -> counts
    Map<String, Integer> authorIds = new HashMap<>();
    Map<String, Integer> fileIds = new HashMap<>();
    List<String> authors = new ArrayList<>();
    List<String> files = new ArrayList<>();

    int commitNum = 0;

    for (RevCommit commit : log) {
        commitNum++;
        if (commitNum % 1000 == 0) {
            System.out.println(commitNum);

            // compute affinity for files as % of commits that touch that
            // file
            PrintWriter pw = new PrintWriter(args[1] + "." + commitNum + ".dat");
            for (String author : commitCounts.keySet()) {
                double totalCommits = commitCounts.get(author).intValue();
                for (Map.Entry<String, Counter> c : counts.get(author).entrySet()) {
                    pw.println(authorIds.get(author) + "\t" + fileIds.get(c.getKey()) + "\t"
                            + ((c.getValue().intValue() / totalCommits) * 10000) + "\t"
                            + c.getValue().intValue());
                }
            }
            pw.close();

            pw = new PrintWriter(args[1] + "." + commitNum + ".users");
            int id = 1;
            for (String author : authors) {
                pw.println(id + "\t" + author);
                id++;
            }
            pw.close();

            pw = new PrintWriter(args[1] + "." + commitNum + ".files");
            id = 1;
            for (String file : files) {
                pw.println(id + "\t" + file);
                id++;
            }
            pw.close();
        }
        // System.out.println("Author: " +
        // commit.getAuthorIdent().getName());
        String author = commit.getAuthorIdent().getName();
        if (!counts.containsKey(author)) {
            counts.put(author, new HashMap<String, Counter>());
            commitCounts.put(author, new Counter(1));
            authorIds.put(author, authorIds.size() + 1);
            authors.add(author);
        } else {
            commitCounts.get(author).inc();
        }

        if (previous != null) {
            AbstractTreeIterator oldTreeParser = prepareTreeParser(repository, previous);
            AbstractTreeIterator newTreeParser = prepareTreeParser(repository, commit);
            // then the procelain diff-command returns a list of diff
            // entries
            List<DiffEntry> diff = git.diff().setOldTree(oldTreeParser).setNewTree(newTreeParser).call();
            for (DiffEntry entry : diff) {
                // System.out.println("\tFile: " + entry.getNewPath());
                String file = entry.getNewPath();
                if (!fileIds.containsKey(file)) {
                    fileIds.put(file, fileIds.size() + 1);
                    files.add(file);
                }
                if (!counts.get(previousAuthor).containsKey(file)) {
                    counts.get(previousAuthor).put(file, new Counter(1));
                } else {
                    counts.get(previousAuthor).get(file).inc();
                }
            }
            // diff.dispose();
            // previous.dispose();
        }
        previous = commit;
        previousAuthor = author;
    }

    // compute affinity for files as % of commits that touch that file
    PrintWriter pw = new PrintWriter(args[1] + ".dat");
    for (String author : commitCounts.keySet()) {
        double totalCommits = commitCounts.get(author).intValue();
        for (Map.Entry<String, Counter> c : counts.get(author).entrySet()) {
            pw.println(authorIds.get(author) + "\t" + fileIds.get(c.getKey()) + "\t"
                    + ((c.getValue().intValue() / totalCommits) * 10000) + "\t" + c.getValue().intValue());
        }
    }
    pw.close();

    pw = new PrintWriter(args[1] + ".users");
    int id = 1;
    for (String author : authors) {
        pw.println(id + "\t" + author);
        id++;
    }
    pw.close();

    pw = new PrintWriter(args[1] + ".files");
    id = 1;
    for (String file : files) {
        pw.println(id + "\t" + file);
        id++;
    }
    pw.close();

    repository.close();
}

From source file:net.aprendizajengrande.gitrecommender.UpdateLog.java

License:Open Source License

public static void main(String[] args) throws Exception {

    if (args.length == 0) {
        System.err.println("Usage: UpdateLog <git dir> <db dir>");
        System.exit(-1);/*from  www  .j av  a 2 s.c o  m*/
    }

    File gitDir = new File(args[0]);
    File dbDir = new File(args[1]);

    DB db = new DB(dbDir);

    System.out.println("Git dir: " + gitDir);
    System.out.println("DB dir: " + dbDir);

    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    // scan environment GIT_* variables
    Repository repository = builder.setGitDir(gitDir).readEnvironment().findGitDir() // scan up the file system tree
            .build();

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

    // go through all commits and process them in reverse order
    List<RevCommit> allCommits = new ArrayList<RevCommit>();

    int newCommits = 0;
    boolean seen = false;
    for (RevCommit commit : log) {
        String name = commit.name();
        if (db.lastCommit().equals(name)) {
            seen = true;
        }
        if (!seen)
            newCommits++;

        allCommits.add(commit);
    }
    System.out.println("Found " + allCommits.size() + " commits (" + newCommits + " new).");

    int commitNum = 0;
    List<Integer> files = new ArrayList<Integer>();
    for (int i = newCommits - 1; i >= 0; i--) {
        if (commitNum % 500 == 0)
            db.save();

        RevCommit commit = allCommits.get(i);

        String author = commit.getAuthorIdent().getName();
        int authorId = db.idAuthor(author);

        files.clear();

        if (i < allCommits.size() - 1) {
            AbstractTreeIterator oldTreeParser = prepareTreeParser(repository, allCommits.get(i + 1));
            AbstractTreeIterator newTreeParser = prepareTreeParser(repository, commit);
            // then the procelain diff-command returns a list of diff
            // entries
            List<DiffEntry> diff = git.diff().setOldTree(oldTreeParser).setNewTree(newTreeParser).call();
            for (DiffEntry entry : diff) {
                // System.out.println("\tFile: " + entry.getNewPath());
                String file = entry.getNewPath();
                files.add(db.idFile(file));
            }
        }
        db.observeCommit(commit.name(), authorId, files);
    }

    db.save();
    repository.close();
}

From source file:net.morimekta.gittool.cmd.Status.java

License:Apache License

@Override
public void execute(GitTool gt) throws IOException {
    try (Repository repository = gt.getRepository()) {
        RepositoryState state = repository.getRepositoryState();
        if (state != RepositoryState.SAFE) {
            System.out.println(WARN + "Repository not in a safe state" + CLEAR + ": " + state.getDescription());
        }//from   w  ww  .j  a  v  a 2s  .c o  m

        Git git = new Git(repository);
        String currentBranch = repository.getBranch();
        String diffWithBranch = branch != null ? branch : gt.getDiffbase(currentBranch);

        this.root = gt.getRepositoryRoot().getCanonicalFile().getAbsolutePath();

        Ref currentRef = repository.getRef(gt.refName(currentBranch));
        Ref diffWithRef = repository.getRef(gt.refName(diffWithBranch));
        if (diffWithRef == null) {
            System.out.println(format("No such branch %s%s%s", BOLD, diffWithBranch, CLEAR));
            return;
        }

        ObjectId currentHead = currentRef.getObjectId();
        ObjectId diffWithHead = diffWithRef.getObjectId();

        // RevCommit currentCommit = commitOf(repository, currentHead);

        if (!currentHead.equals(diffWithHead)) {
            String stats = "";
            String diff = gt.isRemote(diffWithBranch) ? format("[->%s%s%s] ", DIM, diffWithBranch, CLEAR)
                    : format("[d:%s%s%s] ", CLR_BASE_BRANCH, diffWithBranch, CLEAR);

            List<RevCommit> localCommits = ImmutableList
                    .copyOf(git.log().addRange(diffWithHead, currentHead).call());
            List<RevCommit> remoteCommits = ImmutableList
                    .copyOf(git.log().addRange(currentHead, diffWithHead).call());

            localCommits = Lists.reverse(localCommits);
            remoteCommits = Lists.reverse(remoteCommits);

            int commits = localCommits.size();
            int missing = remoteCommits.size();

            RevCommit ancestor, local;
            if (remoteCommits.size() > 0) {
                List<RevCommit> sub2 = Lists.reverse(
                        ImmutableList.copyOf(git.log().add(remoteCommits.get(0)).setMaxCount(2).call()));
                ancestor = sub2.get(0);
            } else {
                ancestor = gt.commitOf(repository, diffWithBranch)
                        .orElseThrow(() -> new IOException("No commit on " + diffWithBranch));
            }
            if (localCommits.size() > 0) {
                local = localCommits.get(localCommits.size() - 1);
            } else {
                local = gt.commitOf(repository, currentBranch)
                        .orElseThrow(() -> new IOException("No commit on " + currentBranch));
            }

            if (commits > 0 || missing > 0) {
                if (commits == 0) {
                    stats = format(" [%s-%d%s]", CLR_SUBS, missing, CLEAR);
                } else if (missing == 0) {
                    stats = format(" [%s+%d%s]", CLR_ADDS, commits, CLEAR);
                } else {
                    stats = format(" [%s+%d%s,%s-%d%s]", CLR_ADDS, commits, CLEAR, CLR_SUBS, missing, CLEAR);
                }
            }

            System.out.println(format("Commits on %s%s%s%s since %s -- %s%s%s%s", CLR_UPDATED_BRANCH,
                    currentBranch, CLEAR, stats, date(ancestor), diff, DIM, ancestor.getShortMessage(), CLEAR));

            if (files) {
                ObjectReader reader = repository.newObjectReader();
                CanonicalTreeParser ancestorTreeIter = new CanonicalTreeParser();
                ancestorTreeIter.reset(reader, ancestor.getTree());
                CanonicalTreeParser localTreeIter = new CanonicalTreeParser();
                localTreeIter.reset(reader, local.getTree());

                // finally get the list of changed files
                List<DiffEntry> diffs = git.diff().setShowNameAndStatusOnly(true).setOldTree(ancestorTreeIter)
                        .setNewTree(localTreeIter).call();
                for (DiffEntry entry : diffs) {
                    switch (entry.getChangeType()) {
                    case RENAME:
                        System.out.println(format(" R %s%s%s <- %s%s%s", new Color(YELLOW, DIM),
                                entry.getNewPath(), CLEAR, DIM, path(entry.getOldPath()), CLEAR));
                        break;
                    case MODIFY:
                        System.out.println(format("   %s", path(entry.getOldPath())));
                        break;
                    case ADD:
                        System.out.println(format(" A %s%s%s", GREEN, path(entry.getNewPath()), CLEAR));
                        break;
                    case DELETE:
                        System.out.println(format(" D %s%s%s", YELLOW, path(entry.getOldPath()), CLEAR));
                        break;
                    case COPY:
                        System.out.println(format(" C %s%s%s <- %s%s%s", new Color(YELLOW, DIM),
                                path(entry.getNewPath()), CLEAR, DIM, path(entry.getOldPath()), CLEAR));
                        break;
                    }
                }
            } else {
                for (RevCommit localCommit : localCommits) {
                    System.out.println(format("+ %s%s%s (%s)", GREEN, localCommit.getShortMessage(), CLEAR,
                            date(localCommit)));
                }
                for (RevCommit remoteCommit : remoteCommits) {
                    System.out.println(format("- %s%s%s (%s)", RED, remoteCommit.getShortMessage(), CLEAR,
                            date(remoteCommit)));
                }
            }
        } else {
            RevCommit diffWithCommit = gt.commitOf(repository, diffWithBranch)
                    .orElseThrow(() -> new IOException("No commit in " + diffWithBranch));
            System.out.println(format("No commits on %s%s%s since %s -- %s%s%s", GREEN, currentBranch, CLEAR,
                    date(diffWithCommit), DIM, diffWithCommit.getShortMessage(), CLEAR));
        }

        // Check for staged and unstaged changes.
        if (files) {
            List<DiffEntry> staged = git.diff().setCached(true).call();
            List<DiffEntry> unstaged = git.diff().setCached(false).call();

            if (staged.size() > 0 || unstaged.size() > 0) {
                System.out.println();
                System.out.println(format("%sUncommitted%s changes on %s%s%s:", RED, CLEAR, CLR_UPDATED_BRANCH,
                        currentBranch, CLEAR));

                Map<String, FileStatus> st = unstaged.stream().map(d -> new FileStatus(relative, root, d))
                        .collect(Collectors.toMap(FileStatus::getNewestPath, fs -> fs));
                staged.forEach(d -> {
                    if (d.getNewPath() != null) {
                        if (st.containsKey(d.getNewPath())) {
                            st.get(d.getNewPath()).setStaged(d);
                            return;
                        }
                    }
                    if (d.getOldPath() != null) {
                        if (st.containsKey(d.getOldPath())) {
                            st.get(d.getOldPath()).setStaged(d);
                            return;
                        }
                    }
                    FileStatus fs = new FileStatus(relative, root, null).setStaged(d);

                    st.put(fs.getNewestPath(), fs);
                });

                for (FileStatus fs : new TreeMap<>(st).values()) {
                    System.out.println(fs.statusLine());
                }
            }
        } else {
            List<DiffEntry> staged = git.diff().setShowNameAndStatusOnly(true).setCached(true).call();
            List<DiffEntry> unstaged = git.diff().setShowNameAndStatusOnly(true).setCached(false).call();

            if (staged.size() > 0 || unstaged.size() > 0) {
                System.out.println(
                        format("Uncommitted changes on %s%s%s:", CLR_UPDATED_BRANCH, currentBranch, CLEAR));

                if (staged.size() > 0) {
                    long adds = staged.stream().filter(e -> e.getChangeType() == DiffEntry.ChangeType.ADD)
                            .count();
                    long dels = staged.stream().filter(e -> e.getChangeType() == DiffEntry.ChangeType.DELETE)
                            .count();
                    long mods = staged.size() - adds - dels;

                    System.out.print(format(" - %sStaged files%s   :", new Color(YELLOW, DIM), CLEAR));
                    if (adds > 0) {
                        System.out.print(format(" %s+%d%s", GREEN, adds, CLEAR));
                    }
                    if (dels > 0) {
                        System.out.print(format(" %s-%d%s", RED, dels, CLEAR));
                    }
                    if (mods > 0) {
                        System.out.print(format(" %s/%d%s", DIM, mods, CLEAR));
                    }
                    System.out.println();
                }
                if (unstaged.size() > 0) {
                    long adds = unstaged.stream().filter(e -> e.getChangeType() == DiffEntry.ChangeType.ADD)
                            .count();
                    long dels = unstaged.stream().filter(e -> e.getChangeType() == DiffEntry.ChangeType.DELETE)
                            .count();
                    long mods = unstaged.size() - adds - dels;

                    System.out.print(format(" - %sUnstaged files%s :", YELLOW, CLEAR));
                    if (adds > 0) {
                        System.out.print(format(" %s+%d%s", GREEN, adds, CLEAR));
                    }
                    if (dels > 0) {
                        System.out.print(format(" %s-%d%s", RED, dels, CLEAR));
                    }
                    if (mods > 0) {
                        System.out.print(format(" %s/%d%s", DIM, mods, CLEAR));
                    }
                    System.out.println();
                }
            }
        }
    } catch (GitAPIException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:net.vexelon.jdevlog.vcs.git.GitSource.java

License:Open Source License

@Override
public Iterator<?> getLastHistory(long maxEntries) throws SCMException {

    Iterable<RevCommit> log = null;

    try {//ww  w . j a v  a 2  s. com
        Git git = new Git(repository);
        LogCommand cmd = git.log();

        cmd.setMaxCount((int) maxEntries);
        //         cmd.addPath(Constants.MASTER);

        try {
            cmd.add(repository.resolve(Constants.MASTER));
        } catch (Exception e) {
            throw new SCMException("Error getting log messages!", e);
        }

        log = cmd.call();
    } catch (NoHeadException e) {
        throw new SCMException("Error getting log messages!", e);
    }

    return log.iterator();
}

From source file:net.yacy.grid.tools.GitTool.java

License:Open Source License

public GitTool() {
    File gitWorkDir = new File(".");
    try {//from ww w  . j a  v a2 s .  com
        Git git = Git.open(gitWorkDir);
        Iterable<RevCommit> commits = git.log().all().call();
        Repository repo = git.getRepository();
        branch = repo.getBranch();
        RevCommit latestCommit = commits.iterator().next();
        name = latestCommit.getName();
        message = latestCommit.getFullMessage();
    } catch (Throwable e) {
        name = "";
        message = "";
        branch = "";
    }
}

From source file:org.abratuhi.camel.GitLogProducer.java

License:Apache License

public void process(Exchange exchange) throws Exception {
    String repo = endpoint.getEndpointUri().substring("git://".length());
    FileRepositoryBuilder frb = new FileRepositoryBuilder();
    FileRepository fr = frb.setGitDir(new File(repo)).readEnvironment().build();
    Git git = new Git(fr);
    Iterable<RevCommit> commits = git.log().call();

    StringBuffer sb = new StringBuffer();
    for (RevCommit rc : commits) {
        sb.append(rc.getShortMessage() + "\n");
    }/*from  w ww .j  a v  a  2s.c o  m*/

    GitLogMessage msg = new GitLogMessage();
    msg.setBody(sb.toString());

    exchange.setOut(msg);
}

From source file:org.commonwl.view.git.GitService.java

License:Apache License

/**
 * Gets a set of authors for a path in a given repository
 * @param repo The git repository//from   w ww. j av  a  2 s.  c  om
 * @param path The path to get commits for
 * @return An iterable of commits
 * @throws GitAPIException Any API errors which may occur
 * @throws URISyntaxException Error constructing mailto link
 */
public Set<HashableAgent> getAuthors(Git repo, String path) throws GitAPIException, URISyntaxException {
    Iterable<RevCommit> logs = repo.log().addPath(path).call();
    Set<HashableAgent> fileAuthors = new HashSet<>();
    for (RevCommit rev : logs) {
        // Use author first with backup of committer
        PersonIdent author = rev.getAuthorIdent();
        if (author == null) {
            author = rev.getCommitterIdent();
        }
        // Create a new agent and add as much detail as possible
        if (author != null) {
            HashableAgent newAgent = new HashableAgent();
            String name = author.getName();
            if (name != null && name.length() > 0) {
                newAgent.setName(author.getName());
            }
            String email = author.getEmailAddress();
            if (email != null && email.length() > 0) {
                newAgent.setUri(new URI("mailto:" + author.getEmailAddress()));
            }
            fileAuthors.add(newAgent);
        }
    }
    return fileAuthors;
}

From source file:org.craftercms.commons.git.impl.GitRepositoryImplTest.java

License:Open Source License

@Test
public void testCommit() throws Exception {
    Git git = Git.init().setDirectory(tmpDir.getRoot()).call();
    GitRepositoryImpl repository = new GitRepositoryImpl(git);

    File testFile = new File(tmpDir.getRoot(), "test");
    testFile.createNewFile();/*  w  w w  .ja v a2s . co m*/

    git.add().addFilepattern("test").call();

    repository.commit("Test message");

    List<RevCommit> commits = IterableUtils.toList(git.log().all().call());

    assertNotNull(commits);
    assertEquals(1, commits.size());
    assertEquals("Test message", commits.get(0).getFullMessage());
}

From source file:org.craftercms.commons.git.impl.GitRepositoryImplTest.java

License:Open Source License

@Test
public void testPush() throws Exception {
    File masterRepoDir = tmpDir.newFolder("master.git");
    File cloneRepoDir = tmpDir.newFolder("clone");

    Git masterGit = Git.init().setDirectory(masterRepoDir).setBare(true).call();
    Git cloneGit = Git.cloneRepository().setURI(masterRepoDir.getCanonicalPath()).setDirectory(cloneRepoDir)
            .call();// w  w  w  .  j a va  2 s.c  o m
    GitRepositoryImpl cloneRepo = new GitRepositoryImpl(cloneGit);

    File testFile = new File(cloneRepoDir, "test");
    testFile.createNewFile();

    cloneGit.add().addFilepattern("test").call();
    cloneGit.commit().setMessage("Test message").call();

    cloneRepo.push();

    List<RevCommit> commits = IterableUtils.toList(masterGit.log().all().call());

    assertNotNull(commits);
    assertEquals(1, commits.size());
    assertEquals("Test message", commits.get(0).getFullMessage());

    List<String> committedFiles = getCommittedFiles(masterGit.getRepository(), commits.get(0));

    assertNotNull(committedFiles);
    assertEquals(1, committedFiles.size());
    assertEquals("test", committedFiles.get(0));
}