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

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

Introduction

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

Prototype

public DiffCommand diff() 

Source Link

Document

Return a command object to execute a diff command

Usage

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

License:Open Source License

/**
 * Update a git repository and return if it has changed and the differences
 *//*from  w w w .ja v a 2s . com*/
public RepositoryChanged updateGitRepository(String repoName, String repoRemoteLocation, String repoUserName,
        String repoPassword, String repoLocations, String branch, boolean useCredentials) {
    boolean changed = false;
    List<String> changedFiles = new ArrayList<>();
    List<String> deletedFiles = new ArrayList<>();
    Singleton.getLogger().info("Attempting to pull latest from " + repoRemoteLocation + " for " + repoName);

    Repository localRepository = null;
    Git git = null;

    try {
        localRepository = new FileRepository(new File(repoLocations + "/" + repoName + "/.git"));

        Ref head = localRepository.getRef("HEAD");
        git = new Git(localRepository);

        git.reset();
        git.clean();

        PullCommand pullCmd = git.pull();

        if (useCredentials) {
            pullCmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(repoUserName, repoPassword));
        }

        pullCmd.call();
        Ref newHEAD = localRepository.getRef("HEAD");

        if (!head.toString().equals(newHEAD.toString())) {
            changed = true;

            // Get the differences between the the heads which we updated at
            // and use these to just update the differences between them
            ObjectId oldHead = localRepository.resolve(head.getObjectId().getName() + "^{tree}");
            ObjectId newHead = localRepository.resolve(newHEAD.getObjectId().getName() + "^{tree}");

            ObjectReader reader = localRepository.newObjectReader();

            CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
            oldTreeIter.reset(reader, oldHead);

            CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
            newTreeIter.reset(reader, newHead);

            List<DiffEntry> entries = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();

            for (DiffEntry entry : entries) {
                if ("DELETE".equals(entry.getChangeType().name())) {
                    deletedFiles.add(FilenameUtils.separatorsToUnix(entry.getOldPath()));
                } else {
                    changedFiles.add(FilenameUtils.separatorsToUnix(entry.getNewPath()));
                }
            }
        }

    } catch (IOException | GitAPIException | InvalidPathException ex) {
        changed = false;
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                + " updateGitRepository for " + repoName + "\n with message: " + ex.getMessage());
    } finally {
        Singleton.getHelpers().closeQuietly(localRepository);
        Singleton.getHelpers().closeQuietly(git);
    }

    return new RepositoryChanged(changed, changedFiles, deletedFiles);
}

From source file:de.ks.blogging.grav.pages.RepositorySupport.java

License:Apache License

public FileChanges getChangedFiles(String from, String to) {
    try {/*w  w  w  .  ja  v a2 s .  c om*/
        Git git = pages.getGit();
        Repository repository = git.getRepository();
        List<DiffEntry> diffs = git.diff().setNewTree(prepareTreeParser(repository, to))
                .setOldTree(prepareTreeParser(repository, from)).call();
        FileChanges fileChanges = new FileChanges(diffs);
        log.info("Found {} added/modified, {} deleted.", fileChanges.getModifiedAdded().size(),
                fileChanges.getDeleted().size());
        return fileChanges;
    } catch (Exception e) {
        log.error("Could not get changed files ", e);
    }

    return new FileChanges(Collections.emptyList());
}

From source file:es.logongas.openshift.ant.impl.OpenShiftUtil.java

License:Apache License

public boolean isRepositoryClean(String repositoryPath) {
    try {// www .j av  a  2s.  c o  m
        Git git = Git.open(new File(repositoryPath));

        List<DiffEntry> diffEntries = git.diff().call();

        if (diffEntries == null) {
            return true;
        } else {
            return diffEntries.isEmpty();
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } catch (GitAPIException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:getgitdata.JGitDiff.java

public static void main(String[] args) throws Exception {
    File gitWorkDir = new File("C:/Users/Masud/Documents/GitHub/tomcat");
    Git git = Git.open(gitWorkDir);

    String newHash = "278a36a";
    String oldHash = "1b46e37b92705159ddc22fd8a28ee1d2b7499072";

    //ObjectId headId = git.getRepository().resolve("HEAD^{tree}");
    // ObjectId headId = git.getRepository().resolve(newHash + "^{tree}");
    ObjectId headId = git.getRepository().resolve(newHash + "^{tree}");
    ObjectId oldId = git.getRepository().resolve(newHash + "^^{tree}");
    ObjectReader reader = git.getRepository().newObjectReader();

    CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
    oldTreeIter.reset(reader, oldId);/*ww  w  .ja va 2s.  c o  m*/
    CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
    newTreeIter.reset(reader, headId);

    List<DiffEntry> diffs = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DiffFormatter df = new DiffFormatter(out);
    df.setRepository(git.getRepository());
    int count = 0;
    for (DiffEntry diff : diffs) {
        count++;
        System.out.println("DIff: " + diff.toString());
        df.format(diff);

        // diff.getOldId();
        String diffText = out.toString("UTF-8");
        System.out.println(diffText);
        out.reset();
    }
    System.out.println("Count: " + count);
}

From source file:io.fabric8.git.internal.GitDataStore.java

License:Apache License

/**
 * Checks if there is an actual difference between two commits.
 * In some cases a container may push a commit, without actually modifying anything.
 * So comparing the commit hashes is not always enough. We need to actually diff the two commits.
 *
 * @param git    The {@link Git} instance to use.
 * @param before The hash of the first commit.
 * @param after  The hash of the second commit.
 *///from   w  ww  . j  av a  2 s.c om
private boolean hasChanged(Git git, String before, String after) throws IOException, GitAPIException {
    if (isCommitEqual(before, after)) {
        return false;
    }
    Repository db = git.getRepository();
    List<DiffEntry> entries = git.diff().setOldTree(getTreeIterator(db, before))
            .setNewTree(getTreeIterator(db, after)).call();
    return entries.size() > 0;
}

From source file:model.Buildmodel.java

public int build(Git git, List<RevCommit> logs, RepoSettings rs)
        throws NoHeadException, GitAPIException, IOException {

    //ObjectId lastCommitId = repository.resolve(Constants.MASTER);
    ObjectId parentid = null;/*from   w  w w  .  j a  va  2 s .c o m*/
    ObjectId currid = null;

    Repository repository = git.getRepository();

    //a new reader to read objects from getObjectDatabase()
    ObjectReader reader = repository.newObjectReader();
    CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
    CanonicalTreeParser newTreeIter = new CanonicalTreeParser();

    List<DiffEntry> diffs = null;

    WriteData wd = new WriteData(); //Class to write data to an external file
    wd.initiate(rs);

    int cnt = 0; //Commits count that is written in data
    for (RevCommit rev : logs) {

        if (rev.getParentCount() == 1) { //Not taking Merge commits, for taking them make it >= .

            try {

                parentid = repository.resolve(rev.getParent(0).getName() + "^{tree}");
                currid = repository.resolve(rev.getName() + "^{tree}");

                //Reset this parser to walk through the given tree
                oldTreeIter.reset(reader, parentid);
                newTreeIter.reset(reader, currid);
                diffs = git.diff() //Returns a command object to execute a diff command
                        .setNewTree(newTreeIter).setOldTree(oldTreeIter).call(); //returns a DiffEntry for each path which is different

            } catch (RevisionSyntaxException | IOException | GitAPIException e) {
                e.printStackTrace();
            }

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            //Create a new formatter with a default level of context.
            DiffFormatter df = new DiffFormatter(out);
            //Set the repository the formatter can load object contents from.
            df.setRepository(git.getRepository());

            ArrayList<String> diffText = new ArrayList<String>();
            ArrayList<String> filetypes = new ArrayList<String>();

            //A DiffEntry is 'A value class representing a change to a file' therefore for each file you have a diff entry.
            int ovllineadd = 0;
            int ovllinerem = 0;
            int totallinechanged = 0;
            int totalfilrem = 0;
            int totalfiladd = 0;

            for (DiffEntry diff : diffs) {

                try {

                    df.format(diff); //Format a patch script for one file entry.
                    RawText r = new RawText(out.toByteArray());
                    r.getLineDelimiter();
                    diffText.add(out.toString());

                    String st = out.toString();
                    String filetype = null;
                    int filerem = 0, fileadd = 0, filtyp = 0;
                    ;
                    int lineadd = 0, linerem = 0;

                    String[] temp = st.split("\n");

                    for (String tem : temp) {

                        if (tem.startsWith("---") || tem.startsWith("+++")) {

                            if (tem.startsWith("---")) {
                                if (tem.endsWith("null")) {
                                    fileadd++; //File added
                                } else {
                                    int p = tem.lastIndexOf("/");
                                    if (p >= 0) {
                                        tem = tem.substring(p + 1, tem.length());
                                    }
                                    int h = tem.lastIndexOf(".");
                                    if (h >= 0) {
                                        filetype = tem.substring(h, tem.length());
                                        filetype = filetype.replace(" ", "");
                                        filetype = filetype.replace("\"", "");
                                        if (filtyp != 1) {
                                            filetypes.add(filetype);
                                            filtyp = 1;
                                        }
                                    } else {
                                        //README, LICENSE type wanna do?
                                    }
                                }
                            }
                            if (tem.startsWith("+++")) {
                                if (tem.endsWith("null")) {
                                    filerem++; //Fil removed
                                } else {
                                    int p = tem.lastIndexOf("/");
                                    if (p >= 0) {
                                        tem = tem.substring(p + 1, tem.length());
                                    }
                                    int h = tem.lastIndexOf(".");
                                    if (h >= 0) {
                                        filetype = tem.substring(h, tem.length());
                                        filetype = filetype.replace(" ", "");
                                        filetype = filetype.replace("\"", "");
                                        if (filtyp != 1) {
                                            filetypes.add(filetype);
                                            filtyp = 1;
                                        }
                                    } else {
                                        //README, LICENSE type wanna do?
                                    }
                                }
                            }

                        }

                        if (tem.startsWith("+") && !tem.startsWith("+++")) {
                            lineadd++;
                        } else if (tem.startsWith("-") && !tem.startsWith("---")) {
                            linerem++;
                        }

                    }
                    ovllineadd += lineadd;
                    ovllinerem += linerem;
                    totallinechanged += (lineadd + linerem);
                    totalfiladd += fileadd;
                    totalfilrem += filerem;

                    out.reset();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            PersonIdent p = rev.getAuthorIdent();
            //DateFormat formatter= new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
            DateFormat formatter = new SimpleDateFormat("HH");
            formatter.setTimeZone(TimeZone.getTimeZone("UTC"));

            String email = p.getEmailAddress();
            //So that email folder is created properly
            if (email.contains("://") || email.contains("//")) {
                email = email.replace(":", "");
                email = email.replace("//", "");
            }

            String[] commsgwords = rev.getFullMessage().split(" ");

            wd.write(rev.getName(), email, totallinechanged, ovllineadd, ovllinerem, filetypes.size(),
                    totalfiladd, totalfilrem, Integer.parseInt(formatter.format(p.getWhen())), filetypes,
                    commsgwords.length);
            cnt++;
        }
    }

    repository.close();
    return cnt;
}

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 a v  a2 s .  c  o m*/

    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);/*w  ww.j ava 2  s.  c  om*/
    }

    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 w w . j a  va  2 s.  c om*/

        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:org.apache.maven.scm.provider.git.jgit.command.diff.JGitDiffCommand.java

License:Apache License

public DiffScmResult callDiff(Git git, ScmVersion startRevision, ScmVersion endRevision)
        throws IOException, GitAPIException, ScmException {

    AbstractTreeIterator oldTree = null;
    if (startRevision != null && StringUtils.isNotEmpty(startRevision.getName().trim())) {
        String startRev = startRevision.getName().trim();
        oldTree = getTreeIterator(git.getRepository(), startRev);
    }//from   w ww  .j ava 2  s. c om

    AbstractTreeIterator newTree = null;
    if (endRevision != null && StringUtils.isNotEmpty(endRevision.getName().trim())) {
        String endRev = endRevision.getName().trim();
        newTree = getTreeIterator(git.getRepository(), endRev);
    }

    OutputStream out = new ByteArrayOutputStream();

    git.diff().setOutputStream(out).setOldTree(oldTree).setNewTree(newTree).setCached(false).call();
    git.diff().setOutputStream(out).setOldTree(oldTree).setNewTree(newTree).setCached(true).call();

    out.flush();

    GitDiffConsumer consumer = new GitDiffConsumer(getLogger(), null);
    String fullDiff = out.toString();
    out.close();

    String[] lines = fullDiff.split("\n");
    for (String aLine : lines) {
        consumer.consumeLine(aLine);
    }

    return new DiffScmResult("JGit diff", consumer.getChangedFiles(), consumer.getDifferences(),
            consumer.getPatch());
}