Example usage for org.eclipse.jgit.lib Repository getRefDatabase

List of usage examples for org.eclipse.jgit.lib Repository getRefDatabase

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository getRefDatabase.

Prototype

@NonNull
public abstract RefDatabase getRefDatabase();

Source Link

Document

Get the reference database which stores the reference namespace.

Usage

From source file:com.google.gerrit.server.patch.AutoMerger.java

License:Apache License

/**
 * Perform an auto-merge of the parents of the given merge commit.
 *
 * @return auto-merge commit or {@code null} if an auto-merge commit
 *     couldn't be created. Headers of the returned RevCommit are parsed.
 *//*  w  w w.j  a v a2s .c  o m*/
public RevCommit merge(Repository repo, RevWalk rw, final ObjectInserter ins, RevCommit merge,
        ThreeWayMergeStrategy mergeStrategy) throws IOException {
    rw.parseHeaders(merge);
    String hash = merge.name();
    String refName = RefNames.REFS_CACHE_AUTOMERGE + hash.substring(0, 2) + "/" + hash.substring(2);
    Ref ref = repo.getRefDatabase().exactRef(refName);
    if (ref != null && ref.getObjectId() != null) {
        RevObject obj = rw.parseAny(ref.getObjectId());
        if (obj instanceof RevCommit) {
            return (RevCommit) obj;
        }
        return commit(repo, rw, ins, refName, obj, merge);
    }

    ResolveMerger m = (ResolveMerger) mergeStrategy.newMerger(repo, true);
    DirCache dc = DirCache.newInCore();
    m.setDirCache(dc);
    m.setObjectInserter(new ObjectInserter.Filter() {
        @Override
        protected ObjectInserter delegate() {
            return ins;
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() {
        }
    });

    boolean couldMerge;
    try {
        couldMerge = m.merge(merge.getParents());
    } catch (IOException e) {
        // It is not safe to continue further down in this method as throwing
        // an exception most likely means that the merge tree was not created
        // and m.getMergeResults() is empty. This would mean that all paths are
        // unmerged and Gerrit UI would show all paths in the patch list.
        log.warn("Error attempting automerge " + refName, e);
        return null;
    }

    ObjectId treeId;
    if (couldMerge) {
        treeId = m.getResultTreeId();

    } else {
        RevCommit ours = merge.getParent(0);
        RevCommit theirs = merge.getParent(1);
        rw.parseBody(ours);
        rw.parseBody(theirs);
        String oursMsg = ours.getShortMessage();
        String theirsMsg = theirs.getShortMessage();

        String oursName = String.format("HEAD   (%s %s)", ours.abbreviate(6).name(),
                oursMsg.substring(0, Math.min(oursMsg.length(), 60)));
        String theirsName = String.format("BRANCH (%s %s)", theirs.abbreviate(6).name(),
                theirsMsg.substring(0, Math.min(theirsMsg.length(), 60)));

        MergeFormatter fmt = new MergeFormatter();
        Map<String, MergeResult<? extends Sequence>> r = m.getMergeResults();
        Map<String, ObjectId> resolved = new HashMap<>();
        for (Map.Entry<String, MergeResult<? extends Sequence>> entry : r.entrySet()) {
            MergeResult<? extends Sequence> p = entry.getValue();
            try (TemporaryBuffer buf = new TemporaryBuffer.LocalFile(null, 10 * 1024 * 1024)) {
                fmt.formatMerge(buf, p, "BASE", oursName, theirsName, UTF_8.name());
                buf.close();

                try (InputStream in = buf.openInputStream()) {
                    resolved.put(entry.getKey(), ins.insert(Constants.OBJ_BLOB, buf.length(), in));
                }
            }
        }

        DirCacheBuilder builder = dc.builder();
        int cnt = dc.getEntryCount();
        for (int i = 0; i < cnt;) {
            DirCacheEntry entry = dc.getEntry(i);
            if (entry.getStage() == 0) {
                builder.add(entry);
                i++;
                continue;
            }

            int next = dc.nextEntry(i);
            String path = entry.getPathString();
            DirCacheEntry res = new DirCacheEntry(path);
            if (resolved.containsKey(path)) {
                // For a file with content merge conflict that we produced a result
                // above on, collapse the file down to a single stage 0 with just
                // the blob content, and a randomly selected mode (the lowest stage,
                // which should be the merge base, or ours).
                res.setFileMode(entry.getFileMode());
                res.setObjectId(resolved.get(path));

            } else if (next == i + 1) {
                // If there is exactly one stage present, shouldn't be a conflict...
                res.setFileMode(entry.getFileMode());
                res.setObjectId(entry.getObjectId());

            } else if (next == i + 2) {
                // Two stages suggests a delete/modify conflict. Pick the higher
                // stage as the automatic result.
                entry = dc.getEntry(i + 1);
                res.setFileMode(entry.getFileMode());
                res.setObjectId(entry.getObjectId());

            } else {
                // 3 stage conflict, no resolve above
                // Punt on the 3-stage conflict and show the base, for now.
                res.setFileMode(entry.getFileMode());
                res.setObjectId(entry.getObjectId());
            }
            builder.add(res);
            i = next;
        }
        builder.finish();
        treeId = dc.writeTree(ins);
    }
    ins.flush();

    return commit(repo, rw, ins, refName, treeId, merge);
}

From source file:com.google.gerrit.server.patch.PatchListLoader.java

License:Apache License

public static RevTree automerge(Repository repo, RevWalk rw, RevCommit b, ThreeWayMergeStrategy mergeStrategy,
        boolean save) throws IOException {
    String hash = b.name();//  w  ww . j av a  2 s  . co  m
    String refName = RefNames.REFS_CACHE_AUTOMERGE + hash.substring(0, 2) + "/" + hash.substring(2);
    Ref ref = repo.getRefDatabase().exactRef(refName);
    if (ref != null && ref.getObjectId() != null) {
        return rw.parseTree(ref.getObjectId());
    }

    ResolveMerger m = (ResolveMerger) mergeStrategy.newMerger(repo, true);
    try (ObjectInserter ins = repo.newObjectInserter()) {
        DirCache dc = DirCache.newInCore();
        m.setDirCache(dc);
        m.setObjectInserter(new ObjectInserter.Filter() {
            @Override
            protected ObjectInserter delegate() {
                return ins;
            }

            @Override
            public void flush() {
            }

            @Override
            public void close() {
            }
        });

        boolean couldMerge;
        try {
            couldMerge = m.merge(b.getParents());
        } catch (IOException e) {
            // It is not safe to continue further down in this method as throwing
            // an exception most likely means that the merge tree was not created
            // and m.getMergeResults() is empty. This would mean that all paths are
            // unmerged and Gerrit UI would show all paths in the patch list.
            log.warn("Error attempting automerge " + refName, e);
            return null;
        }

        ObjectId treeId;
        if (couldMerge) {
            treeId = m.getResultTreeId();

        } else {
            RevCommit ours = b.getParent(0);
            RevCommit theirs = b.getParent(1);
            rw.parseBody(ours);
            rw.parseBody(theirs);
            String oursMsg = ours.getShortMessage();
            String theirsMsg = theirs.getShortMessage();

            String oursName = String.format("HEAD   (%s %s)", ours.abbreviate(6).name(),
                    oursMsg.substring(0, Math.min(oursMsg.length(), 60)));
            String theirsName = String.format("BRANCH (%s %s)", theirs.abbreviate(6).name(),
                    theirsMsg.substring(0, Math.min(theirsMsg.length(), 60)));

            MergeFormatter fmt = new MergeFormatter();
            Map<String, MergeResult<? extends Sequence>> r = m.getMergeResults();
            Map<String, ObjectId> resolved = new HashMap<>();
            for (Map.Entry<String, MergeResult<? extends Sequence>> entry : r.entrySet()) {
                MergeResult<? extends Sequence> p = entry.getValue();
                try (TemporaryBuffer buf = new TemporaryBuffer.LocalFile(null, 10 * 1024 * 1024)) {
                    fmt.formatMerge(buf, p, "BASE", oursName, theirsName, "UTF-8");
                    buf.close();

                    try (InputStream in = buf.openInputStream()) {
                        resolved.put(entry.getKey(), ins.insert(Constants.OBJ_BLOB, buf.length(), in));
                    }
                }
            }

            DirCacheBuilder builder = dc.builder();
            int cnt = dc.getEntryCount();
            for (int i = 0; i < cnt;) {
                DirCacheEntry entry = dc.getEntry(i);
                if (entry.getStage() == 0) {
                    builder.add(entry);
                    i++;
                    continue;
                }

                int next = dc.nextEntry(i);
                String path = entry.getPathString();
                DirCacheEntry res = new DirCacheEntry(path);
                if (resolved.containsKey(path)) {
                    // For a file with content merge conflict that we produced a result
                    // above on, collapse the file down to a single stage 0 with just
                    // the blob content, and a randomly selected mode (the lowest stage,
                    // which should be the merge base, or ours).
                    res.setFileMode(entry.getFileMode());
                    res.setObjectId(resolved.get(path));

                } else if (next == i + 1) {
                    // If there is exactly one stage present, shouldn't be a conflict...
                    res.setFileMode(entry.getFileMode());
                    res.setObjectId(entry.getObjectId());

                } else if (next == i + 2) {
                    // Two stages suggests a delete/modify conflict. Pick the higher
                    // stage as the automatic result.
                    entry = dc.getEntry(i + 1);
                    res.setFileMode(entry.getFileMode());
                    res.setObjectId(entry.getObjectId());

                } else { // 3 stage conflict, no resolve above
                    // Punt on the 3-stage conflict and show the base, for now.
                    res.setFileMode(entry.getFileMode());
                    res.setObjectId(entry.getObjectId());
                }
                builder.add(res);
                i = next;
            }
            builder.finish();
            treeId = dc.writeTree(ins);
        }
        ins.flush();

        if (save) {
            RefUpdate update = repo.updateRef(refName);
            update.setNewObjectId(treeId);
            update.disableRefLog();
            update.forceUpdate();
        }

        return rw.lookupTree(treeId);
    }
}

From source file:com.google.gerrit.server.project.CreateBranch.java

License:Apache License

private RevWalk verifyConnected(final Repository repo, final ObjectId revid) throws InvalidRevisionException {
    try {/*from  w w w  . j  av  a 2  s.  com*/
        final ObjectWalk rw = new ObjectWalk(repo);
        try {
            rw.markStart(rw.parseCommit(revid));
        } catch (IncorrectObjectTypeException err) {
            throw new InvalidRevisionException();
        }
        RefDatabase refDb = repo.getRefDatabase();
        Iterable<Ref> refs = Iterables.concat(refDb.getRefs(Constants.R_HEADS).values(),
                refDb.getRefs(Constants.R_TAGS).values());
        Ref rc = refDb.exactRef(RefNames.REFS_CONFIG);
        if (rc != null) {
            refs = Iterables.concat(refs, Collections.singleton(rc));
        }
        for (Ref r : refs) {
            try {
                rw.markUninteresting(rw.parseAny(r.getObjectId()));
            } catch (MissingObjectException err) {
                continue;
            }
        }
        rw.checkConnectivity();
        return rw;
    } catch (IncorrectObjectTypeException | MissingObjectException err) {
        throw new InvalidRevisionException();
    } catch (IOException err) {
        log.error("Repository \"" + repo.getDirectory() + "\" may be corrupt; suggest running git fsck", err);
        throw new InvalidRevisionException();
    }
}

From source file:com.google.gerrit.server.project.DeleteBranches.java

License:Apache License

private ReceiveCommand createDeleteCommand(ProjectResource project, Repository r, String branch)
        throws OrmException, IOException {
    Ref ref = r.getRefDatabase().getRef(branch);
    ReceiveCommand command;//w ww  .j ava  2  s.com
    if (ref == null) {
        command = new ReceiveCommand(ObjectId.zeroId(), ObjectId.zeroId(), branch);
        command.setResult(Result.REJECTED_OTHER_REASON,
                "it doesn't exist or you do not have permission to delete it");
        return command;
    }
    command = new ReceiveCommand(ref.getObjectId(), ObjectId.zeroId(), ref.getName());
    Branch.NameKey branchKey = new Branch.NameKey(project.getNameKey(), ref.getName());
    if (!project.getControl().controlForRef(branchKey).canDelete()) {
        command.setResult(Result.REJECTED_OTHER_REASON,
                "it doesn't exist or you do not have permission to delete it");
    }
    if (!queryProvider.get().setLimit(1).byBranchOpen(branchKey).isEmpty()) {
        command.setResult(Result.REJECTED_OTHER_REASON, "it has open changes");
    }
    return command;
}

From source file:com.google.gerrit.server.project.DeleteRef.java

License:Apache License

private void deleteMultipleRefs(Repository r) throws OrmException, IOException, ResourceConflictException {
    BatchRefUpdate batchUpdate = r.getRefDatabase().newBatchUpdate();
    batchUpdate.setAtomic(false);/*from   w  w  w . j  a v a2s. com*/
    List<String> refs = prefix == null ? refsToDelete
            : refsToDelete.stream().map(ref -> ref.startsWith(prefix) ? ref : prefix + ref).collect(toList());
    for (String ref : refs) {
        batchUpdate.addCommand(createDeleteCommand(resource, r, ref));
    }
    try (RevWalk rw = new RevWalk(r)) {
        batchUpdate.execute(rw, NullProgressMonitor.INSTANCE);
    }
    StringBuilder errorMessages = new StringBuilder();
    for (ReceiveCommand command : batchUpdate.getCommands()) {
        if (command.getResult() == Result.OK) {
            postDeletion(resource, command);
        } else {
            appendAndLogErrorMessage(errorMessages, command);
        }
    }
    if (errorMessages.length() > 0) {
        throw new ResourceConflictException(errorMessages.toString());
    }
}

From source file:com.google.gerrit.server.project.DeleteRef.java

License:Apache License

private ReceiveCommand createDeleteCommand(ProjectResource project, Repository r, String refName)
        throws OrmException, IOException, ResourceConflictException {
    Ref ref = r.getRefDatabase().getRef(refName);
    ReceiveCommand command;/*from ww  w  .ja  va2  s  .com*/
    if (ref == null) {
        command = new ReceiveCommand(ObjectId.zeroId(), ObjectId.zeroId(), refName);
        command.setResult(Result.REJECTED_OTHER_REASON,
                "it doesn't exist or you do not have permission to delete it");
        return command;
    }
    command = new ReceiveCommand(ref.getObjectId(), ObjectId.zeroId(), ref.getName());

    if (!project.getControl().controlForRef(refName).canDelete()) {
        command.setResult(Result.REJECTED_OTHER_REASON,
                "it doesn't exist or you do not have permission to delete it");
    }

    if (!refName.startsWith(R_TAGS)) {
        Branch.NameKey branchKey = new Branch.NameKey(project.getNameKey(), ref.getName());
        if (!queryProvider.get().setLimit(1).byBranchOpen(branchKey).isEmpty()) {
            command.setResult(Result.REJECTED_OTHER_REASON, "it has open changes");
        }
    }

    RefUpdate u = r.updateRef(refName);
    u.setForceUpdate(true);
    u.setExpectedOldObjectId(r.exactRef(refName).getObjectId());
    u.setNewObjectId(ObjectId.zeroId());
    refDeletionValidator.validateRefOperation(project.getName(), identifiedUser.get(), u);
    return command;
}

From source file:com.google.gerrit.server.project.RefUtil.java

License:Apache License

public static RevWalk verifyConnected(Repository repo, ObjectId revid) throws InvalidRevisionException {
    try {//from w  w w.  ja va 2 s.c  o  m
        ObjectWalk rw = new ObjectWalk(repo);
        try {
            rw.markStart(rw.parseCommit(revid));
        } catch (IncorrectObjectTypeException err) {
            throw new InvalidRevisionException();
        }
        RefDatabase refDb = repo.getRefDatabase();
        Iterable<Ref> refs = Iterables.concat(refDb.getRefs(Constants.R_HEADS).values(),
                refDb.getRefs(Constants.R_TAGS).values());
        Ref rc = refDb.exactRef(RefNames.REFS_CONFIG);
        if (rc != null) {
            refs = Iterables.concat(refs, Collections.singleton(rc));
        }
        for (Ref r : refs) {
            try {
                rw.markUninteresting(rw.parseAny(r.getObjectId()));
            } catch (MissingObjectException err) {
                continue;
            }
        }
        rw.checkConnectivity();
        return rw;
    } catch (IncorrectObjectTypeException | MissingObjectException err) {
        throw new InvalidRevisionException();
    } catch (IOException err) {
        log.error("Repository \"" + repo.getDirectory() + "\" may be corrupt; suggest running git fsck", err);
        throw new InvalidRevisionException();
    }
}

From source file:com.google.gerrit.server.schema.Schema_108.java

License:Apache License

private static void updateProjectGroups(ReviewDb db, Repository repo, RevWalk rw, Set<Change.Id> changes)
        throws OrmException, IOException {
    // Match sorting in ReceiveCommits.
    rw.reset();/*w  w  w .  j av a2s. c  o m*/
    rw.sort(RevSort.TOPO);
    rw.sort(RevSort.REVERSE, true);

    RefDatabase refdb = repo.getRefDatabase();
    for (Ref ref : refdb.getRefs(Constants.R_HEADS).values()) {
        RevCommit c = maybeParseCommit(rw, ref.getObjectId());
        if (c != null) {
            rw.markUninteresting(c);
        }
    }

    Multimap<ObjectId, Ref> changeRefsBySha = ArrayListMultimap.create();
    Multimap<ObjectId, PatchSet.Id> patchSetsBySha = ArrayListMultimap.create();
    for (Ref ref : refdb.getRefs(RefNames.REFS_CHANGES).values()) {
        ObjectId id = ref.getObjectId();
        if (ref.getObjectId() == null) {
            continue;
        }
        id = id.copy();
        changeRefsBySha.put(id, ref);
        PatchSet.Id psId = PatchSet.Id.fromRef(ref.getName());
        if (psId != null && changes.contains(psId.getParentKey())) {
            patchSetsBySha.put(id, psId);
            RevCommit c = maybeParseCommit(rw, id);
            if (c != null) {
                rw.markStart(c);
            }
        }
    }

    GroupCollector collector = new GroupCollector(changeRefsBySha, db);
    RevCommit c;
    while ((c = rw.next()) != null) {
        collector.visit(c);
    }

    updateGroups(db, collector, patchSetsBySha);
}

From source file:com.google.gerrit.server.update.FusedNoteDbBatchUpdate.java

License:Apache License

private ChangesHandle executeChangeOps(boolean dryrun) throws Exception {
    logDebug("Executing change ops");
    initRepository();/*from w  w w. ja  va 2  s.c om*/
    Repository repo = repoView.getRepository();
    checkState(repo.getRefDatabase().performsAtomicTransactions(),
            "cannot use noteDb.changes.fuseUpdates=true with a repository that does not support atomic"
                    + " batch ref updates: %s",
            repo);

    ChangesHandle handle = new ChangesHandle(updateManagerFactory.create(project).setChangeRepo(repo,
            repoView.getRevWalk(), repoView.getInserter(), repoView.getCommands()), dryrun);
    if (user.isIdentifiedUser()) {
        handle.manager.setRefLogIdent(user.asIdentifiedUser().newRefLogIdent(when, tz));
    }
    for (Map.Entry<Change.Id, Collection<BatchUpdateOp>> e : ops.asMap().entrySet()) {
        Change.Id id = e.getKey();
        ChangeContextImpl ctx = newChangeContext(id);
        boolean dirty = false;
        logDebug("Applying {} ops for change {}", e.getValue().size(), id);
        for (BatchUpdateOp op : e.getValue()) {
            dirty |= op.updateChange(ctx);
        }
        if (!dirty) {
            logDebug("No ops reported dirty, short-circuiting");
            handle.setResult(id, ChangeResult.SKIPPED);
            continue;
        }
        for (ChangeUpdate u : ctx.updates.values()) {
            handle.manager.add(u);
        }
        if (ctx.deleted) {
            logDebug("Change {} was deleted", id);
            handle.manager.deleteChange(id);
            handle.setResult(id, ChangeResult.DELETED);
        } else {
            handle.setResult(id, ChangeResult.UPSERTED);
        }
    }
    return handle;
}

From source file:com.google.gerrit.server.util.MagicBranch.java

License:Apache License

private static Capable checkMagicBranchRef(String branchName, Repository repo, Project project) {
    Map<String, Ref> blockingFors;
    try {//from ww w.j av a  2 s.  c  o  m
        blockingFors = repo.getRefDatabase().getRefs(branchName);
    } catch (IOException err) {
        String projName = project.getName();
        log.warn("Cannot scan refs in '" + projName + "'", err);
        return new Capable("Server process cannot read '" + projName + "'");
    }
    if (!blockingFors.isEmpty()) {
        String projName = project.getName();
        log.error("Repository '" + projName + "' needs the following refs removed to receive changes: "
                + blockingFors.keySet());
        return new Capable("One or more " + branchName + " names blocks change upload");
    }

    return Capable.OK;
}