Example usage for org.eclipse.jgit.revwalk RevWalk getObjectReader

List of usage examples for org.eclipse.jgit.revwalk RevWalk getObjectReader

Introduction

In this page you can find the example usage for org.eclipse.jgit.revwalk RevWalk getObjectReader.

Prototype

public ObjectReader getObjectReader() 

Source Link

Document

Get the reader this walker is using to load objects.

Usage

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  ww  w . j  av a  2s .c  om
    }

    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:br.com.metricminer2.scm.GitRepository.java

License:Apache License

private List<DiffEntry> diffsForTheCommit(Repository repo, RevCommit commit)
        throws IOException, AmbiguousObjectException, IncorrectObjectTypeException {

    AnyObjectId currentCommit = repo.resolve(commit.getName());
    AnyObjectId parentCommit = commit.getParentCount() > 0 ? repo.resolve(commit.getParent(0).getName()) : null;

    DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
    df.setBinaryFileThreshold(2 * 1024); // 2 mb max a file
    df.setRepository(repo);/*from w  ww.  ja v  a2  s  .com*/
    df.setDiffComparator(RawTextComparator.DEFAULT);
    df.setDetectRenames(true);
    List<DiffEntry> diffs = null;

    if (parentCommit == null) {
        RevWalk rw = new RevWalk(repo);
        diffs = df.scan(new EmptyTreeIterator(),
                new CanonicalTreeParser(null, rw.getObjectReader(), commit.getTree()));
        rw.release();
    } else {
        diffs = df.scan(parentCommit, currentCommit);
    }

    df.release();

    return diffs;
}

From source file:com.github.checkstyle.regression.git.DiffParser.java

License:Open Source License

/**
 * Creates a tree parser from a commit, to be used by diff command.
 * @param walk   the {@link RevWalk} to parse the tree
 * @param commit the commit to create tree parser from
 * @return the tree parser//  www. jav a2 s.c  o  m
 * @throws IOException JGit library exception
 */
private static AbstractTreeIterator prepareTreeParser(RevWalk walk, RevCommit commit) throws IOException {
    final RevTree tree = walk.parseTree(commit.getTree().getId());
    final CanonicalTreeParser returnValue;
    returnValue = new CanonicalTreeParser();
    returnValue.reset(walk.getObjectReader(), tree.getId());
    return returnValue;
}

From source file:com.google.appraise.eclipse.core.client.git.AppraiseGitReviewClient.java

License:Open Source License

/**
 * Merges the notes from local and origin commits with the given merge base.
 *//*from www  .ja va2s . com*/
private void mergeNotesAndPush(RevWalk revWalk, String refName, RevCommit baseCommit, RevCommit localCommit,
        RevCommit originCommit) throws GitClientException {
    int remainingLockFailureCalls = JgitUtils.MAX_LOCK_FAILURE_CALLS;

    // Merge and commit.
    while (true) {
        try {
            NoteMap theirNoteMap = NoteMap.read(revWalk.getObjectReader(), originCommit);
            NoteMap ourNoteMap = NoteMap.read(revWalk.getObjectReader(), localCommit);
            NoteMap baseNoteMap;
            if (baseCommit != null) {
                baseNoteMap = NoteMap.read(revWalk.getObjectReader(), baseCommit);
            } else {
                baseNoteMap = NoteMap.newEmptyMap();
            }

            NoteMapMerger merger = new NoteMapMerger(repo, new DefaultNoteMerger(), MergeStrategy.RESOLVE);
            NoteMap merged = merger.merge(baseNoteMap, ourNoteMap, theirNoteMap);
            try (ObjectInserter inserter = repo.newObjectInserter()) {
                RevCommit mergeCommit = createNotesCommit(merged, inserter, revWalk, "Merged note commits\n",
                        localCommit, originCommit);

                RefUpdate update = JgitUtils.updateRef(repo, mergeCommit, localCommit, refName);
                Result result = update.update();
                if (result == Result.LOCK_FAILURE) {
                    if (--remainingLockFailureCalls > 0) {
                        Thread.sleep(JgitUtils.SLEEP_ON_LOCK_FAILURE_MS);
                    } else {
                        throw new GitClientException("Failed to lock the ref: " + refName);
                    }
                } else if (result == Result.REJECTED) {
                    throw new GitClientException("Rejected update to " + refName + ", this is unexpected");
                } else if (result == Result.IO_FAILURE) {
                    throw new GitClientException("I/O failure merging notes");
                } else {
                    // OK.
                    break;
                }
            }
        } catch (Exception e) {
            throw new GitClientException("Error merging notes commits", e);
        }
    }

    // And push.
    try {
        pushCommentsAndReviews();
    } catch (Exception e) {
        throw new GitClientException("Error pushing merge commit", e);
    }
}

From source file:com.google.gerrit.acceptance.rest.change.ConfigChangeIT.java

License:Apache License

private Config readProjectConfig() throws Exception {
    RevWalk rw = testRepo.getRevWalk();
    RevTree tree = rw.parseTree(testRepo.getRepository().resolve("HEAD"));
    RevObject obj = rw.parseAny(testRepo.get(tree, "project.config"));
    ObjectLoader loader = rw.getObjectReader().open(obj);
    String text = new String(loader.getCachedBytes(), UTF_8);
    Config cfg = new Config();
    cfg.fromText(text);//  w  w  w  . j av a  2s . c  o  m
    return cfg;
}

From source file:com.google.gerrit.server.account.externalids.ExternalIdReader.java

License:Apache License

public static NoteMap readNoteMap(RevWalk rw, ObjectId rev) throws IOException {
    if (!rev.equals(ObjectId.zeroId())) {
        return NoteMap.read(rw.getObjectReader(), rw.parseCommit(rev));
    }//from   w  w w . j  a  v a 2s .c o  m
    return NoteMap.newEmptyMap();
}

From source file:com.google.gerrit.server.account.externalids.ExternalIdReader.java

License:Apache License

private static ExternalId parse(ExternalId.Key key, RevWalk rw, ObjectId rev)
        throws IOException, ConfigInvalidException {
    NoteMap noteMap = readNoteMap(rw, rev);
    ObjectId noteId = key.sha1();// w w  w  . ja  va  2s  .  co m
    if (!noteMap.contains(noteId)) {
        return null;
    }

    byte[] raw = rw.getObjectReader().open(noteMap.get(noteId), OBJ_BLOB).getCachedBytes(MAX_NOTE_SZ);
    return ExternalId.parse(noteId.name(), raw);
}

From source file:com.google.gerrit.server.account.externalids.ExternalIdsUpdate.java

License:Apache License

/**
 * Insert or updates an new external ID and sets it in the note map.
 *
 * <p>If the external ID already exists it is overwritten.
 *//* w  ww  .j a  v  a2 s  . co  m*/
public static void upsert(RevWalk rw, ObjectInserter ins, NoteMap noteMap, ExternalId extId)
        throws IOException, ConfigInvalidException {
    ObjectId noteId = extId.key().sha1();
    Config c = new Config();
    if (noteMap.contains(extId.key().sha1())) {
        byte[] raw = rw.getObjectReader().open(noteMap.get(noteId), OBJ_BLOB).getCachedBytes(MAX_NOTE_SZ);
        try {
            c.fromText(new String(raw, UTF_8));
        } catch (ConfigInvalidException e) {
            throw new ConfigInvalidException(
                    String.format("Invalid external id config for note %s: %s", noteId, e.getMessage()));
        }
    }
    extId.writeToConfig(c);
    byte[] raw = c.toText().getBytes(UTF_8);
    ObjectId dataBlob = ins.insert(OBJ_BLOB, raw);
    noteMap.set(noteId, dataBlob);
}

From source file:com.google.gerrit.server.account.externalids.ExternalIdsUpdate.java

License:Apache License

/**
 * Removes an external ID from the note map.
 *
 * @throws IllegalStateException is thrown if there is an existing external ID that has the same
 *     key, but otherwise doesn't match the specified external ID.
 *//*  w  w  w.  j a  v a  2 s.c o  m*/
public static void remove(RevWalk rw, NoteMap noteMap, ExternalId extId)
        throws IOException, ConfigInvalidException {
    ObjectId noteId = extId.key().sha1();
    if (!noteMap.contains(noteId)) {
        return;
    }

    byte[] raw = rw.getObjectReader().open(noteMap.get(noteId), OBJ_BLOB).getCachedBytes(MAX_NOTE_SZ);
    ExternalId actualExtId = ExternalId.parse(noteId.name(), raw);
    checkState(extId.equals(actualExtId),
            "external id %s should be removed, but it's not matching the actual external id %s",
            extId.toString(), actualExtId.toString());
    noteMap.remove(noteId);
}

From source file:com.google.gerrit.server.account.externalids.ExternalIdsUpdate.java

License:Apache License

/**
 * Removes an external ID from the note map by external ID key.
 *
 * @throws IllegalStateException is thrown if an expected account ID is provided and an external
 *     ID with the specified key exists, but belongs to another account.
 */// w  ww  .  j  a v  a 2  s . c om
private static void remove(RevWalk rw, NoteMap noteMap, ExternalId.Key extIdKey, Account.Id expectedAccountId)
        throws IOException, ConfigInvalidException {
    ObjectId noteId = extIdKey.sha1();
    if (!noteMap.contains(noteId)) {
        return;
    }

    byte[] raw = rw.getObjectReader().open(noteMap.get(noteId), OBJ_BLOB).getCachedBytes(MAX_NOTE_SZ);
    ExternalId extId = ExternalId.parse(noteId.name(), raw);
    if (expectedAccountId != null) {
        checkState(expectedAccountId.equals(extId.accountId()),
                "external id %s should be removed for account %s," + " but external id belongs to account %s",
                extIdKey.get(), expectedAccountId.get(), extId.accountId().get());
    }
    noteMap.remove(noteId);
}