Example usage for org.eclipse.jgit.diff DiffEntry getOldPath

List of usage examples for org.eclipse.jgit.diff DiffEntry getOldPath

Introduction

In this page you can find the example usage for org.eclipse.jgit.diff DiffEntry getOldPath.

Prototype

public String getOldPath() 

Source Link

Document

Get the old name associated with this file.

Usage

From source file:MyDiffFormatter.java

License:Eclipse Distribution License

private List<DiffEntry> updateFollowFilter(List<DiffEntry> files) {
    String oldPath = ((FollowFilter) pathFilter).getPath();
    for (DiffEntry ent : files) {
        if (isRename(ent) && ent.getNewPath().equals(oldPath)) {
            pathFilter = FollowFilter.create(ent.getOldPath(), diffCfg);
            return Collections.singletonList(ent);
        }//from w w  w.  j  a  va 2  s . c om
    }
    return Collections.emptyList();
}

From source file:MyDiffFormatter.java

License:Eclipse Distribution License

private void formatHeader(ByteArrayOutputStream o, DiffEntry ent) throws IOException {
    final ChangeType type = ent.getChangeType();
    final String oldp = ent.getOldPath();
    final String newp = ent.getNewPath();
    final FileMode oldMode = ent.getOldMode();
    final FileMode newMode = ent.getNewMode();

    formatGitDiffFirstHeaderLine(o, type, oldp, newp);

    if ((type == MODIFY || type == COPY || type == RENAME) && !oldMode.equals(newMode)) {
        o.write(encodeASCII("old mode ")); //$NON-NLS-1$
        oldMode.copyTo(o);/*from www . jav a2  s  .co m*/
        o.write('\n');

        o.write(encodeASCII("new mode ")); //$NON-NLS-1$
        newMode.copyTo(o);
        o.write('\n');
    }

    switch (type) {
    case ADD:
        o.write(encodeASCII("new file mode ")); //$NON-NLS-1$
        newMode.copyTo(o);
        o.write('\n');
        break;

    case DELETE:
        o.write(encodeASCII("deleted file mode ")); //$NON-NLS-1$
        oldMode.copyTo(o);
        o.write('\n');
        break;

    case RENAME:
        o.write(encodeASCII("similarity index " + ent.getScore() + "%")); //$NON-NLS-1$ //$NON-NLS-2$
        o.write('\n');

        o.write(encode("rename from " + quotePath(oldp))); //$NON-NLS-1$
        o.write('\n');

        o.write(encode("rename to " + quotePath(newp))); //$NON-NLS-1$
        o.write('\n');
        break;

    case COPY:
        o.write(encodeASCII("similarity index " + ent.getScore() + "%")); //$NON-NLS-1$ //$NON-NLS-2$
        o.write('\n');

        o.write(encode("copy from " + quotePath(oldp))); //$NON-NLS-1$
        o.write('\n');

        o.write(encode("copy to " + quotePath(newp))); //$NON-NLS-1$
        o.write('\n');
        break;

    case MODIFY:
        if (0 < ent.getScore()) {
            o.write(encodeASCII("dissimilarity index " //$NON-NLS-1$
                    + (100 - ent.getScore()) + "%")); //$NON-NLS-1$
            o.write('\n');
        }
        break;
    }

    if (ent.getOldId() != null && !ent.getOldId().equals(ent.getNewId())) {
        formatIndexLine(o, ent);
    }
}

From source file:MyDiffFormatter.java

License:Eclipse Distribution License

private void formatOldNewPaths(ByteArrayOutputStream o, DiffEntry ent) throws IOException {
    if (ent.getOldId().equals(ent.getNewId()))
        return;//from w  w w .j a  va2 s  .  c o  m

    final String oldp;
    final String newp;

    switch (ent.getChangeType()) {
    case ADD:
        oldp = DiffEntry.DEV_NULL;
        newp = quotePath(newPrefix + ent.getNewPath());
        break;

    case DELETE:
        oldp = quotePath(oldPrefix + ent.getOldPath());
        newp = DiffEntry.DEV_NULL;
        break;

    default:
        oldp = quotePath(oldPrefix + ent.getOldPath());
        newp = quotePath(newPrefix + ent.getNewPath());
        break;
    }

    o.write(encode("--- " + oldp + "\n")); //$NON-NLS-1$ //$NON-NLS-2$
    o.write(encode("+++ " + newp + "\n")); //$NON-NLS-1$ //$NON-NLS-2$
}

From source file:at.ac.tuwien.inso.subcat.miner.GitMiner.java

License:Open Source License

private void processDiff(Repository repository, RevWalk walk, RevCommit current, DiffOutputStream outputStream,
        Map<String, FileStats> fileStatsMap) throws IOException {
    assert (repository != null);
    assert (walk != null);
    assert (current != null);
    assert (outputStream != null);
    assert (fileStatsMap != null);

    if (processDiffs == false) {
        return;/*from   w  w w .  ja v a2  s.co m*/
    }

    try {
        DiffFormatter df = new DiffFormatter(outputStream);
        df.setRepository(repository);
        df.setDetectRenames(true);

        List<DiffEntry> entries;
        if (current.getParentCount() > 0) {
            RevCommit parent = current.getParent(0);
            ObjectId oldTree = walk.parseCommit(parent).getTree();
            ObjectId newTree = current.getTree();
            entries = df.scan(oldTree, newTree);
        } else {
            entries = df.scan(new EmptyTreeIterator(),
                    new CanonicalTreeParser(null, walk.getObjectReader(), current.getTree()));
        }

        for (DiffEntry de : entries) {
            if (stopped == true) {
                break;
            }

            int emptyLinesAddedStart = outputStream.getTotalEmptyLinesAdded();
            int emptyLinesRemovedStart = outputStream.getTotalEmptyLinesRemoved();
            int linesAddedStart = outputStream.getTotalLinesAdded();
            int linesRemovedStart = outputStream.getTotalLinesRemoved();
            int chunksStart = outputStream.getTotalChunks();
            String oldPath = null;
            String path = null;

            switch (de.getChangeType()) {
            case ADD:
                path = de.getNewPath();
                break;
            case DELETE:
                path = de.getOldPath();
                break;
            case MODIFY:
                path = de.getOldPath();
                break;
            case COPY:
                oldPath = de.getOldPath();
                path = de.getNewPath();
                break;
            case RENAME:
                oldPath = de.getOldPath();
                path = de.getNewPath();
                break;
            default:
                continue;
            }

            assert (fileStatsMap.containsKey(path) == false);
            assert (path != null);

            FileStats fileStats = new FileStats();
            fileStatsMap.put(path, fileStats);

            outputStream.resetFile();
            df.format(de);
            df.flush();

            fileStats.emptyLinesAdded = outputStream.getTotalEmptyLinesAdded() - emptyLinesAddedStart;
            fileStats.emptyLinesRemoved = outputStream.getTotalEmptyLinesRemoved() - emptyLinesRemovedStart;
            fileStats.linesAdded += outputStream.getTotalLinesAdded() - linesAddedStart;
            fileStats.linesRemoved += outputStream.getTotalLinesRemoved() - linesRemovedStart;
            fileStats.chunks += outputStream.getTotalChunks() - chunksStart;

            fileStats.type = de.getChangeType();
            fileStats.oldPath = oldPath;
        }
    } catch (IOException e) {
        throw e;
    }
}

From source file:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java

License:Open Source License

/**
 * loads all patches of from the given list of {@link DiffEntry}s.
 * /*from   w w w  .  ja va 2s  .c  o m*/
 * @param patchSet
 *            the patchSet to add the patches to.
 * @param ref
 *            the ref to the commit of the patch set.
 * @param repository
 *            the git repository instance
 * @throws RepositoryIOException
 */
private void loadPatches(PatchSet patchSet, Ref ref, Git git) throws RepositoryIOException {

    EList<Patch> patches = patchSet.getPatches();
    Repository repository = git.getRepository();

    try {

        RevWalk revWalk = new RevWalk(repository);
        RevCommit newCommit = revWalk.parseCommit(ref.getObjectId());
        RevCommit oldCommit = newCommit.getParent(0);
        revWalk.parseHeaders(oldCommit);
        ObjectReader objectReader = repository.newObjectReader();
        revWalk.close();

        CanonicalTreeParser newTreeIterator = new CanonicalTreeParser();
        newTreeIterator.reset(objectReader, newCommit.getTree().getId());
        CanonicalTreeParser oldTreeIterator = new CanonicalTreeParser();
        oldTreeIterator.reset(objectReader, oldCommit.getTree().getId());

        List<DiffEntry> diffs = git.diff().setOldTree(oldTreeIterator).setNewTree(newTreeIterator).call();

        for (DiffEntry diff : diffs) {

            String newPath = diff.getNewPath();
            String oldPath = diff.getOldPath();
            Patch patch = null;

            /*
             * only papyrus diagrams are supported for now, so models are in
             * .uml files, diagrams in .notation files
             */

            if (diff.getChangeType() != ChangeType.DELETE) {
                if (newPath.endsWith(".uml")) {
                    patch = modelReviewFactory.createModelPatch();

                } else if (newPath.endsWith(".notation")) {
                    patch = modelReviewFactory.createDiagramPatch();
                } else {
                    patch = modelReviewFactory.createPatch();
                }
            } else {
                if (oldPath.endsWith(".uml")) {
                    patch = modelReviewFactory.createModelPatch();

                } else if (oldPath.endsWith(".notation")) {
                    patch = modelReviewFactory.createDiagramPatch();
                } else {
                    patch = modelReviewFactory.createPatch();
                }
            }

            switch (diff.getChangeType()) {
            case ADD:
                patch.setChangeType(PatchChangeType.ADD);
                break;
            case COPY:
                patch.setChangeType(PatchChangeType.COPY);
                break;
            case DELETE:
                patch.setChangeType(PatchChangeType.DELETE);
                break;
            case MODIFY:
                patch.setChangeType(PatchChangeType.MODIFY);
                break;
            case RENAME:
                patch.setChangeType(PatchChangeType.RENAME);
                break;
            }

            patch.setNewPath(newPath);
            patch.setOldPath(oldPath);

            if (diff.getChangeType() != ChangeType.DELETE) {
                ObjectLoader objectLoader = repository.open(diff.getNewId().toObjectId());
                patch.setNewContent(objectLoader.getBytes());
            }
            if (diff.getChangeType() != ChangeType.ADD) {
                ObjectLoader objectLoader = repository.open(diff.getOldId().toObjectId());
                patch.setOldContent(objectLoader.getBytes());
            }
            patches.add(patch);

        }

    } catch (IOException e) {
        throw new RepositoryIOException(MessageFormat.format(
                "An IO error occured during loading the patches for patch set #{0}", patchSet.getId()), e);
    } catch (GitAPIException e) {
        throw new RepositoryIOException(
                MessageFormat.format("An JGit API error occured during loading the patches for patch set #{0}",
                        patchSet.getId()),
                e);
    }
}

From source file:boa.datagen.scm.GitCommit.java

License:Apache License

private void getChangeFiles(final RevCommit parent, final RevCommit rc,
        final HashMap<String, String> rChangedPaths, final HashMap<String, String> rRemovedPaths,
        final HashMap<String, String> rAddedPaths) {
    final DiffFormatter df = new DiffFormatter(NullOutputStream.INSTANCE);
    df.setRepository(repository);//from   w w  w.j  a  v a  2 s .  co m
    df.setDiffComparator(RawTextComparator.DEFAULT);
    df.setDetectRenames(true);

    try {
        final AbstractTreeIterator parentIter;
        if (parent == null)
            parentIter = new EmptyTreeIterator();
        else
            parentIter = new CanonicalTreeParser(null, repository.newObjectReader(), parent.getTree());

        for (final DiffEntry diff : df.scan(parentIter,
                new CanonicalTreeParser(null, repository.newObjectReader(), rc.getTree()))) {
            if (diff.getChangeType() == ChangeType.MODIFY || diff.getChangeType() == ChangeType.COPY
                    || diff.getChangeType() == ChangeType.RENAME) {
                if (diff.getOldMode().getObjectType() == Constants.OBJ_BLOB
                        && diff.getNewMode().getObjectType() == Constants.OBJ_BLOB) {
                    String path = diff.getNewPath();
                    rChangedPaths.put(path, diff.getOldPath());
                    filePathGitObjectIds.put(path, diff.getNewId().toObjectId());
                }
            } else if (diff.getChangeType() == ChangeType.ADD) {
                if (diff.getNewMode().getObjectType() == Constants.OBJ_BLOB) {
                    String path = diff.getNewPath();
                    rAddedPaths.put(path, null);
                    filePathGitObjectIds.put(path, diff.getNewId().toObjectId());
                }
            } else if (diff.getChangeType() == ChangeType.DELETE) {
                if (diff.getOldMode().getObjectType() == Constants.OBJ_BLOB) {
                    rRemovedPaths.put(diff.getOldPath(), diff.getOldPath());
                }
            }
        }
    } catch (final IOException e) {
        if (debug)
            System.err.println("Git Error getting commit diffs: " + e.getMessage());
    }
    df.close();
}

From source file:br.com.metricminer2.scm.GitRepository.java

License:Apache License

@Override
public Commit getCommit(String id) {
    Git git = null;// www.  j av  a  2  s.com
    try {
        git = Git.open(new File(path));
        Repository repo = git.getRepository();

        Iterable<RevCommit> commits = git.log().add(repo.resolve(id)).call();
        Commit theCommit = null;

        for (RevCommit jgitCommit : commits) {

            Developer author = new Developer(jgitCommit.getAuthorIdent().getName(),
                    jgitCommit.getAuthorIdent().getEmailAddress());
            Developer committer = new Developer(jgitCommit.getCommitterIdent().getName(),
                    jgitCommit.getCommitterIdent().getEmailAddress());

            String msg = jgitCommit.getFullMessage().trim();
            String hash = jgitCommit.getName().toString();
            long epoch = jgitCommit.getCommitTime();
            String parent = (jgitCommit.getParentCount() > 0) ? jgitCommit.getParent(0).getName().toString()
                    : "";

            GregorianCalendar date = new GregorianCalendar();
            date.setTime(new Date(epoch * 1000L));

            theCommit = new Commit(hash, author, committer, date, msg, parent);

            List<DiffEntry> diffsForTheCommit = diffsForTheCommit(repo, jgitCommit);
            if (diffsForTheCommit.size() > MAX_NUMBER_OF_FILES_IN_A_COMMIT) {
                log.error("commit " + id + " has more than files than the limit");
                throw new RuntimeException("commit " + id + " too big, sorry");
            }

            for (DiffEntry diff : diffsForTheCommit) {

                ModificationType change = Enum.valueOf(ModificationType.class, diff.getChangeType().toString());

                String oldPath = diff.getOldPath();
                String newPath = diff.getNewPath();

                String diffText = "";
                String sc = "";
                if (diff.getChangeType() != ChangeType.DELETE) {
                    diffText = getDiffText(repo, diff);
                    sc = getSourceCode(repo, diff);
                }

                if (diffText.length() > MAX_SIZE_OF_A_DIFF) {
                    log.error("diff for " + newPath + " too big");
                    diffText = "-- TOO BIG --";
                }

                theCommit.addModification(oldPath, newPath, change, diffText, sc);

            }

            break;
        }

        return theCommit;
    } catch (Exception e) {
        throw new RuntimeException("error detailing " + id + " in " + path, e);
    } finally {
        if (git != null)
            git.close();
    }
}

From source file:co.bledo.gitmin.servlet.Review.java

License:Apache License

public Response commit(Request req) throws IOException, GitAPIException {
    String repoName = req.getParam("repo", "");
    String hash = req.getParam("hash", "");

    Git git = Git.open(new File(GitminConfig.getGitRepositoriesPath() + "/" + repoName));

    /*/*from  www  .  j  a  v a  2  s .  c o m*/
    ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
    List<DiffEntry> diffTest = git.diff().setOutputStream(baos1)
    .setOldTree(getTreeIterator(git.getRepository(), hash))
    .setNewTree(getTreeIterator(git.getRepository(), hash + "^"))
    .call();
    System.out.println(baos1.toString());
    */

    RepositoryBuilder builder = new RepositoryBuilder();
    Repository repo = builder.setGitDir(new File(GitminConfig.getGitRepositoriesPath() + "/" + repoName))
            .readEnvironment().findGitDir().build();

    RevWalk rw = new RevWalk(repo);

    ObjectId hashOid = repo.resolve(hash);

    RevCommit commit = rw.parseCommit(hashOid);
    RevCommit parent = rw.parseCommit(commit.getParent(0).getId());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DiffFormatter df = new DiffFormatter(baos);
    df.setRepository(repo);
    df.setDiffComparator(RawTextComparator.DEFAULT);
    df.setDetectRenames(true);
    List<DiffEntry> diffs = df.scan(parent, commit);
    List<CommitInfo> commitInfos = new ArrayList<CommitInfo>();
    for (DiffEntry diff : diffs) {

        CommitInfo nfo = new CommitInfo();

        df.format(diff);

        nfo.diff = baos.toString();
        nfo.oldContents = getFileContent(repo, parent, diff.getOldPath());
        nfo.newContents = getFileContent(repo, parent, diff.getNewPath());
        nfo.newFile = diff.getNewPath();
        nfo.oldFile = diff.getOldPath();

        commitInfos.add(nfo);
    }

    VelocityResponse resp = VelocityResponse.newInstance(req, this);
    resp.assign("nfolist", commitInfos);
    return log.exit(resp);
}

From source file:com.centurylink.mdw.dataaccess.file.VersionControlGit.java

License:Apache License

public GitDiffs getDiffs(String branch, String path) throws Exception {
    fetch();/* w  w w. ja va  2 s  .  c  om*/
    GitDiffs diffs = new GitDiffs();
    ObjectId remoteHead = localRepo.resolve("origin/" + branch + "^{tree}");
    if (remoteHead == null)
        throw new IOException("Unable to determine Git Diffs due to missing remote HEAD");
    CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
    newTreeIter.reset(localRepo.newObjectReader(), remoteHead);
    DiffCommand dc = git.diff().setNewTree(newTreeIter);
    if (path != null)
        dc.setPathFilter(PathFilter.create(path));
    dc.setShowNameAndStatusOnly(true);
    for (DiffEntry diff : dc.call()) {
        if (diff.getChangeType() == ChangeType.ADD || diff.getChangeType() == ChangeType.COPY) {
            diffs.add(DiffType.MISSING, diff.getNewPath());
        } else if (diff.getChangeType() == ChangeType.MODIFY) {
            diffs.add(DiffType.DIFFERENT, diff.getNewPath());
        } else if (diff.getChangeType() == ChangeType.DELETE) {
            diffs.add(DiffType.EXTRA, diff.getOldPath());
        } else if (diff.getChangeType() == ChangeType.RENAME) {
            diffs.add(DiffType.MISSING, diff.getNewPath());
            diffs.add(DiffType.EXTRA, diff.getOldPath());
        }
    }
    // we're purposely omitting folders
    Status status = git.status().addPath(path).call();
    for (String untracked : status.getUntracked()) {
        if (!untracked.startsWith(path + "/Archive/"))
            diffs.add(DiffType.EXTRA, untracked);
    }
    for (String added : status.getAdded()) {
        diffs.add(DiffType.EXTRA, added);
    }
    for (String missing : status.getMissing()) {
        diffs.add(DiffType.MISSING, missing);
    }
    for (String removed : status.getRemoved()) {
        diffs.add(DiffType.MISSING, removed);
    }
    for (String changed : status.getChanged()) {
        diffs.add(DiffType.DIFFERENT, changed);
    }
    for (String modified : status.getModified()) {
        diffs.add(DiffType.DIFFERENT, modified);
    }
    for (String conflict : status.getConflicting()) {
        diffs.add(DiffType.DIFFERENT, conflict);
    }
    return diffs;
}

From source file:com.chungkwong.jgitgui.LogTreeItem.java

License:Open Source License

private static String toString(DiffEntry entry) {
    switch (entry.getChangeType()) {
    case ADD:/*from   w  w  w.  j a  v a 2s . com*/
        return entry.getNewPath()
                + java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString(" ADDED");
    case COPY:
        return entry.getOldPath()
                + java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString(" COPIED TO ")
                + entry.getNewPath();
    case DELETE:
        return entry.getOldPath()
                + java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString(" REMOVED");
    case MODIFY:
        return entry.getOldPath()
                + java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString(" MODIFIED");
    case RENAME:
        return entry.getOldPath()
                + java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString(" RENAMED TO ")
                + entry.getNewPath();
    default:
        return "";
    }
}