Example usage for org.eclipse.jgit.lib RefUpdate update

List of usage examples for org.eclipse.jgit.lib RefUpdate update

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib RefUpdate update.

Prototype

public Result update() throws IOException 

Source Link

Document

Gracefully update the ref to the new value.

Usage

From source file:com.google.gerrit.pgm.init.api.VersionedMetaDataOnInit.java

License:Apache License

private void updateRef(Repository repo, PersonIdent ident, ObjectId newRevision, String refLogMsg)
        throws IOException {
    RefUpdate ru = repo.updateRef(getRefName());
    ru.setRefLogIdent(ident);//  w ww.j a v a  2 s. c  om
    ru.setNewObjectId(newRevision);
    ru.setExpectedOldObjectId(revision);
    ru.setRefLogMessage(refLogMsg, false);
    RefUpdate.Result r = ru.update();
    switch (r) {
    case FAST_FORWARD:
    case NEW:
    case NO_CHANGE:
        break;
    case FORCED:
    case IO_FAILURE:
    case LOCK_FAILURE:
    case NOT_ATTEMPTED:
    case REJECTED:
    case REJECTED_CURRENT_BRANCH:
    case RENAMED:
    default:
        throw new IOException("Failed to update " + getRefName() + " of " + project + ": " + r.name());
    }
}

From source file:com.google.gerrit.server.account.AccountsUpdate.java

License:Apache License

public static void createUserBranch(Repository repo, ObjectInserter oi, PersonIdent committerIdent,
        PersonIdent authorIdent, Account account) throws IOException {
    ObjectId id = createInitialEmptyCommit(oi, committerIdent, authorIdent, account.getRegisteredOn());

    String refName = RefNames.refsUsers(account.getId());
    RefUpdate ru = repo.updateRef(refName);
    ru.setExpectedOldObjectId(ObjectId.zeroId());
    ru.setNewObjectId(id);/*www  . j  a v a  2s  . c  o m*/
    ru.setForceUpdate(true);
    ru.setRefLogIdent(committerIdent);
    ru.setRefLogMessage("Create Account", true);
    Result result = ru.update();
    if (result != Result.NEW) {
        throw new IOException(String.format("Failed to update ref %s: %s", refName, result.name()));
    }
}

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

License:Apache License

/** Commits updates to the external IDs. */
public static ObjectId commit(Repository repo, RevWalk rw, ObjectInserter ins, ObjectId rev, NoteMap noteMap,
        String commitMessage, PersonIdent committerIdent, PersonIdent authorIdent) throws IOException {
    CommitBuilder cb = new CommitBuilder();
    cb.setMessage(commitMessage);/*from w  w  w .  j a v a  2 s .  c  o m*/
    cb.setTreeId(noteMap.writeTree(ins));
    cb.setAuthor(authorIdent);
    cb.setCommitter(committerIdent);
    if (!rev.equals(ObjectId.zeroId())) {
        cb.setParentId(rev);
    } else {
        cb.setParentIds(); // Ref is currently nonexistent, commit has no parents.
    }
    if (cb.getTreeId() == null) {
        if (rev.equals(ObjectId.zeroId())) {
            cb.setTreeId(emptyTree(ins)); // No parent, assume empty tree.
        } else {
            RevCommit p = rw.parseCommit(rev);
            cb.setTreeId(p.getTree()); // Copy tree from parent.
        }
    }
    ObjectId commitId = ins.insert(cb);
    ins.flush();

    RefUpdate u = repo.updateRef(RefNames.REFS_EXTERNAL_IDS);
    u.setRefLogIdent(committerIdent);
    u.setRefLogMessage("Update external IDs", false);
    u.setExpectedOldObjectId(rev);
    u.setNewObjectId(commitId);
    RefUpdate.Result res = u.update();
    switch (res) {
    case NEW:
    case FAST_FORWARD:
    case NO_CHANGE:
    case RENAMED:
    case FORCED:
        break;
    case LOCK_FAILURE:
        throw new LockFailureException("Updating external IDs failed with " + res);
    case IO_FAILURE:
    case NOT_ATTEMPTED:
    case REJECTED:
    case REJECTED_CURRENT_BRANCH:
    default:
        throw new IOException("Updating external IDs failed with " + res);
    }
    return rw.parseCommit(commitId);
}

From source file:com.google.gerrit.server.change.ConsistencyChecker.java

License:Apache License

private void fixPatchSetRef(ProblemInfo p, PatchSet ps) {
    try {/*from   ww  w  .j  a va2  s .co m*/
        RefUpdate ru = repo.updateRef(ps.getId().toRefName());
        ru.setForceUpdate(true);
        ru.setNewObjectId(ObjectId.fromString(ps.getRevision().get()));
        ru.setRefLogIdent(newRefLogIdent());
        ru.setRefLogMessage("Repair patch set ref", true);
        RefUpdate.Result result = ru.update();
        switch (result) {
        case NEW:
        case FORCED:
        case FAST_FORWARD:
        case NO_CHANGE:
            p.status = Status.FIXED;
            p.outcome = "Repaired patch set ref";
            return;
        default:
            p.status = Status.FIX_FAILED;
            p.outcome = "Failed to update patch set ref: " + result;
            return;
        }
    } catch (IOException e) {
        String msg = "Error fixing patch set ref";
        log.warn(msg + ' ' + ps.getId().toRefName(), e);
        p.status = Status.FIX_FAILED;
        p.outcome = msg;
    }
}

From source file:com.google.gerrit.server.git.CreateCodeReviewNotes.java

License:Apache License

public void updateRef() throws IOException, InterruptedException, CodeReviewNoteCreationException,
        MissingObjectException, IncorrectObjectTypeException, CorruptObjectException {
    if (baseCommit != null && oursCommit.getTree().equals(baseCommit.getTree())) {
        // If the trees are identical, there is no change in the notes.
        // Avoid saving this commit as it has no new information.
        return;// www . j av  a 2 s  .c om
    }

    int remainingLockFailureCalls = MAX_LOCK_FAILURE_CALLS;
    RefUpdate refUpdate = createRefUpdate(oursCommit, baseCommit);

    for (;;) {
        Result result = refUpdate.update();

        if (result == Result.LOCK_FAILURE) {
            if (--remainingLockFailureCalls > 0) {
                Thread.sleep(SLEEP_ON_LOCK_FAILURE_MS);
            } else {
                throw new CodeReviewNoteCreationException("Failed to lock the ref: " + REFS_NOTES_REVIEW);
            }

        } else if (result == Result.REJECTED) {
            RevCommit theirsCommit = revWalk.parseCommit(refUpdate.getOldObjectId());
            NoteMap theirs = NoteMap.read(revWalk.getObjectReader(), theirsCommit);
            NoteMapMerger merger = new NoteMapMerger(db);
            NoteMap merged = merger.merge(base, ours, theirs);
            RevCommit mergeCommit = createCommit(merged, gerritIdent, "Merged note commits\n", theirsCommit,
                    oursCommit);
            refUpdate = createRefUpdate(mergeCommit, theirsCommit);
            remainingLockFailureCalls = MAX_LOCK_FAILURE_CALLS;

        } else if (result == Result.IO_FAILURE) {
            throw new CodeReviewNoteCreationException(
                    "Couldn't create code review notes because of IO_FAILURE");
        } else {
            break;
        }
    }
}

From source file:com.google.gerrit.server.git.NotesBranchUtil.java

License:Apache License

private void updateRef(String notesBranch) throws IOException, MissingObjectException,
        IncorrectObjectTypeException, CorruptObjectException, ConcurrentRefUpdateException {
    if (baseCommit != null && oursCommit.getTree().equals(baseCommit.getTree())) {
        // If the trees are identical, there is no change in the notes.
        // Avoid saving this commit as it has no new information.
        return;/*from  w w w. j  av  a 2s. c  o m*/
    }

    int remainingLockFailureCalls = MAX_LOCK_FAILURE_CALLS;
    RefUpdate refUpdate = createRefUpdate(notesBranch, oursCommit, baseCommit);

    for (;;) {
        Result result = refUpdate.update();

        if (result == Result.LOCK_FAILURE) {
            if (--remainingLockFailureCalls > 0) {
                try {
                    Thread.sleep(SLEEP_ON_LOCK_FAILURE_MS);
                } catch (InterruptedException e) {
                    // ignore
                }
            } else {
                throw new ConcurrentRefUpdateException("Failed to lock the ref: " + notesBranch,
                        refUpdate.getRef(), result);
            }

        } else if (result == Result.REJECTED) {
            RevCommit theirsCommit = revWalk.parseCommit(refUpdate.getOldObjectId());
            NoteMap theirs = NoteMap.read(revWalk.getObjectReader(), theirsCommit);
            NoteMapMerger merger = new NoteMapMerger(db, getNoteMerger(), MergeStrategy.RESOLVE);
            NoteMap merged = merger.merge(base, ours, theirs);
            RevCommit mergeCommit = createCommit(merged, gerritIdent, "Merged note commits\n", theirsCommit,
                    oursCommit);
            refUpdate = createRefUpdate(notesBranch, mergeCommit, theirsCommit);
            remainingLockFailureCalls = MAX_LOCK_FAILURE_CALLS;

        } else if (result == Result.IO_FAILURE) {
            throw new IOException("Couldn't update " + notesBranch + ". " + result.name());
        } else {
            gitRefUpdated.fire(project, refUpdate);
            break;
        }
    }
}

From source file:com.google.gerrit.server.git.SubmoduleOp.java

License:Apache License

/**
 * Update the submodules in one branch of one repository.
 *
 * @param subscriber the branch of the repository which should be changed.
 * @param updates submodule updates which should be updated to.
 * @throws SubmoduleException//from   ww  w  .  java2  s.com
 */
private void updateGitlinks(ReviewDb db, Branch.NameKey subscriber, Collection<SubmoduleSubscription> updates)
        throws SubmoduleException {
    PersonIdent author = null;
    StringBuilder msgbuf = new StringBuilder("Updated git submodules\n\n");
    boolean sameAuthorForAll = true;

    try (Repository pdb = repoManager.openRepository(subscriber.getParentKey())) {
        if (pdb.getRef(subscriber.get()) == null) {
            throw new SubmoduleException("The branch was probably deleted from the subscriber repository");
        }

        DirCache dc = readTree(pdb, pdb.getRef(subscriber.get()));
        DirCacheEditor ed = dc.editor();

        for (SubmoduleSubscription s : updates) {
            try (Repository subrepo = repoManager.openRepository(s.getSubmodule().getParentKey());
                    RevWalk rw = CodeReviewCommit.newRevWalk(subrepo)) {
                Ref ref = subrepo.getRefDatabase().exactRef(s.getSubmodule().get());
                if (ref == null) {
                    ed.add(new DeletePath(s.getPath()));
                    continue;
                }

                final ObjectId updateTo = ref.getObjectId();
                RevCommit newCommit = rw.parseCommit(updateTo);

                if (author == null) {
                    author = newCommit.getAuthorIdent();
                } else if (!author.equals(newCommit.getAuthorIdent())) {
                    sameAuthorForAll = false;
                }

                DirCacheEntry dce = dc.getEntry(s.getPath());
                ObjectId oldId;
                if (dce != null) {
                    if (!dce.getFileMode().equals(FileMode.GITLINK)) {
                        log.error("Requested to update gitlink " + s.getPath() + " in "
                                + s.getSubmodule().getParentKey().get() + " but entry "
                                + "doesn't have gitlink file mode.");
                        continue;
                    }
                    oldId = dce.getObjectId();
                } else {
                    // This submodule did not exist before. We do not want to add
                    // the full submodule history to the commit message, so omit it.
                    oldId = updateTo;
                }

                ed.add(new PathEdit(s.getPath()) {
                    @Override
                    public void apply(DirCacheEntry ent) {
                        ent.setFileMode(FileMode.GITLINK);
                        ent.setObjectId(updateTo);
                    }
                });
                if (verboseSuperProject) {
                    msgbuf.append("Project: " + s.getSubmodule().getParentKey().get());
                    msgbuf.append(" " + s.getSubmodule().getShortName());
                    msgbuf.append(" " + updateTo.getName());
                    msgbuf.append("\n\n");

                    try {
                        rw.markStart(newCommit);
                        rw.markUninteresting(rw.parseCommit(oldId));
                        for (RevCommit c : rw) {
                            msgbuf.append(c.getFullMessage() + "\n\n");
                        }
                    } catch (IOException e) {
                        logAndThrowSubmoduleException(
                                "Could not perform a revwalk to " + "create superproject commit message", e);
                    }
                }
            }
        }
        ed.finish();

        if (!sameAuthorForAll || author == null) {
            author = myIdent;
        }

        ObjectInserter oi = pdb.newObjectInserter();
        ObjectId tree = dc.writeTree(oi);

        ObjectId currentCommitId = pdb.getRef(subscriber.get()).getObjectId();

        CommitBuilder commit = new CommitBuilder();
        commit.setTreeId(tree);
        commit.setParentIds(new ObjectId[] { currentCommitId });
        commit.setAuthor(author);
        commit.setCommitter(myIdent);
        commit.setMessage(msgbuf.toString());
        oi.insert(commit);
        oi.flush();

        ObjectId commitId = oi.idFor(Constants.OBJ_COMMIT, commit.build());

        final RefUpdate rfu = pdb.updateRef(subscriber.get());
        rfu.setForceUpdate(false);
        rfu.setNewObjectId(commitId);
        rfu.setExpectedOldObjectId(currentCommitId);
        rfu.setRefLogMessage("Submit to " + subscriber.getParentKey().get(), true);

        switch (rfu.update()) {
        case NEW:
        case FAST_FORWARD:
            gitRefUpdated.fire(subscriber.getParentKey(), rfu);
            changeHooks.doRefUpdatedHook(subscriber, rfu, account);
            // TODO since this is performed "in the background" no mail will be
            // sent to inform users about the updated branch
            break;

        default:
            throw new IOException(rfu.getResult().name());
        }
        // Recursive call: update subscribers of the subscriber
        updateSuperProjects(db, Sets.newHashSet(subscriber));
    } catch (IOException e) {
        throw new SubmoduleException("Cannot update gitlinks for " + subscriber.get(), e);
    }
}

From source file:com.google.gerrit.server.git.VersionedMetaData.java

License:Apache License

/**
 * Open a batch of updates to the same metadata ref.
 * <p>//from   w w w . j  av a 2  s  .com
 * This allows making multiple commits to a single metadata ref, at the end of
 * which is a single ref update. For batching together updates to multiple
 * refs (each consisting of one or more commits against their respective
 * refs), create the {@link MetaDataUpdate} with a {@link BatchRefUpdate}.
 * <p>
 * A ref update produced by this {@link BatchMetaDataUpdate} is only committed
 * if there is no associated {@link BatchRefUpdate}. As a result, the
 * configured ref updated event is not fired if there is an associated batch.
 *
 * @param update helper info about the update.
 * @throws IOException if the update failed.
 */
public BatchMetaDataUpdate openUpdate(final MetaDataUpdate update) throws IOException {
    final Repository db = update.getRepository();

    reader = db.newObjectReader();
    inserter = db.newObjectInserter();
    final RevWalk rw = new RevWalk(reader);
    final RevTree tree = revision != null ? rw.parseTree(revision) : null;
    newTree = readTree(tree);
    return new BatchMetaDataUpdate() {
        AnyObjectId src = revision;
        AnyObjectId srcTree = tree;

        @Override
        public void write(CommitBuilder commit) throws IOException {
            write(VersionedMetaData.this, commit);
        }

        private boolean doSave(VersionedMetaData config, CommitBuilder commit) throws IOException {
            DirCache nt = config.newTree;
            ObjectReader r = config.reader;
            ObjectInserter i = config.inserter;
            try {
                config.newTree = newTree;
                config.reader = reader;
                config.inserter = inserter;
                return config.onSave(commit);
            } catch (ConfigInvalidException e) {
                throw new IOException(
                        "Cannot update " + getRefName() + " in " + db.getDirectory() + ": " + e.getMessage(),
                        e);
            } finally {
                config.newTree = nt;
                config.reader = r;
                config.inserter = i;
            }
        }

        @Override
        public void write(VersionedMetaData config, CommitBuilder commit) throws IOException {
            if (!doSave(config, commit)) {
                return;
            }

            // Reuse tree from parent commit unless there are contents in newTree or
            // there is no tree for a parent commit.
            ObjectId res = newTree.getEntryCount() != 0 || srcTree == null ? newTree.writeTree(inserter)
                    : srcTree.copy();
            if (res.equals(srcTree) && !update.allowEmpty() && (commit.getTreeId() == null)) {
                // If there are no changes to the content, don't create the commit.
                return;
            }

            // If changes are made to the DirCache and those changes are written as
            // a commit and then the tree ID is set for the CommitBuilder, then
            // those previous DirCache changes will be ignored and the commit's
            // tree will be replaced with the ID in the CommitBuilder. The same is
            // true if you explicitly set tree ID in a commit and then make changes
            // to the DirCache; that tree ID will be ignored and replaced by that of
            // the tree for the updated DirCache.
            if (commit.getTreeId() == null) {
                commit.setTreeId(res);
            } else {
                // In this case, the caller populated the tree without using DirCache.
                res = commit.getTreeId();
            }

            if (src != null) {
                commit.addParentId(src);
            }

            if (update.insertChangeId()) {
                ObjectId id = ChangeIdUtil.computeChangeId(res, getRevision(), commit.getAuthor(),
                        commit.getCommitter(), commit.getMessage());
                commit.setMessage(ChangeIdUtil.insertId(commit.getMessage(), id));
            }

            src = inserter.insert(commit);
            srcTree = res;
        }

        @Override
        public RevCommit createRef(String refName) throws IOException {
            if (Objects.equals(src, revision)) {
                return revision;
            }
            return updateRef(ObjectId.zeroId(), src, refName);
        }

        @Override
        public void removeRef(String refName) throws IOException {
            RefUpdate ru = db.updateRef(refName);
            ru.setForceUpdate(true);
            if (revision != null) {
                ru.setExpectedOldObjectId(revision);
            }
            RefUpdate.Result result = ru.delete();
            switch (result) {
            case FORCED:
                update.fireGitRefUpdatedEvent(ru);
                return;
            default:
                throw new IOException(
                        "Cannot delete " + ru.getName() + " in " + db.getDirectory() + ": " + ru.getResult());
            }
        }

        @Override
        public RevCommit commit() throws IOException {
            return commitAt(revision);
        }

        @Override
        public RevCommit commitAt(ObjectId expected) throws IOException {
            if (Objects.equals(src, expected)) {
                return revision;
            }
            return updateRef(MoreObjects.firstNonNull(expected, ObjectId.zeroId()), src, getRefName());
        }

        @Override
        public void close() {
            newTree = null;

            rw.close();
            if (inserter != null) {
                inserter.close();
                inserter = null;
            }

            if (reader != null) {
                reader.close();
                reader = null;
            }
        }

        private RevCommit updateRef(AnyObjectId oldId, AnyObjectId newId, String refName) throws IOException {
            BatchRefUpdate bru = update.getBatch();
            if (bru != null) {
                bru.addCommand(new ReceiveCommand(oldId.toObjectId(), newId.toObjectId(), refName));
                inserter.flush();
                revision = rw.parseCommit(newId);
                return revision;
            }

            RefUpdate ru = db.updateRef(refName);
            ru.setExpectedOldObjectId(oldId);
            ru.setNewObjectId(src);
            ru.setRefLogIdent(update.getCommitBuilder().getAuthor());
            String message = update.getCommitBuilder().getMessage();
            if (message == null) {
                message = "meta data update";
            }
            try (BufferedReader reader = new BufferedReader(new StringReader(message))) {
                // read the subject line and use it as reflog message
                ru.setRefLogMessage("commit: " + reader.readLine(), true);
            }
            inserter.flush();
            RefUpdate.Result result = ru.update();
            switch (result) {
            case NEW:
            case FAST_FORWARD:
                revision = rw.parseCommit(ru.getNewObjectId());
                update.fireGitRefUpdatedEvent(ru);
                return revision;
            default:
                throw new IOException(
                        "Cannot update " + ru.getName() + " in " + db.getDirectory() + ": " + ru.getResult());
            }
        }
    };
}

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

License:Apache License

private void createEmptyCommits(Repository repo, Project.NameKey project, List<String> refs)
        throws IOException {
    try (ObjectInserter oi = repo.newObjectInserter()) {
        CommitBuilder cb = new CommitBuilder();
        cb.setTreeId(oi.insert(Constants.OBJ_TREE, new byte[] {}));
        cb.setAuthor(metaDataUpdateFactory.getUserPersonIdent());
        cb.setCommitter(serverIdent);/*  w  ww.  ja v  a 2  s . c  o m*/
        cb.setMessage("Initial empty repository\n");

        ObjectId id = oi.insert(cb);
        oi.flush();

        for (String ref : refs) {
            RefUpdate ru = repo.updateRef(ref);
            ru.setNewObjectId(id);
            Result result = ru.update();
            switch (result) {
            case NEW:
                referenceUpdated.fire(project, ru, ReceiveCommand.Type.CREATE);
                break;
            default: {
                throw new IOException(String.format("Failed to create ref \"%s\": %s", ref, result.name()));
            }
            }
        }
    } catch (IOException e) {
        log.error("Cannot create empty commit for " + project.get(), e);
        throw e;
    }
}

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

License:Apache License

private void createEmptyCommits(final Repository repo, final Project.NameKey project, final List<String> refs)
        throws IOException {
    ObjectInserter oi = repo.newObjectInserter();
    try {/*from  w ww .j  a  v  a  2 s  . c o  m*/
        CommitBuilder cb = new CommitBuilder();
        cb.setTreeId(oi.insert(Constants.OBJ_TREE, new byte[] {}));
        cb.setAuthor(metaDataUpdateFactory.getUserPersonIdent());
        cb.setCommitter(serverIdent);
        cb.setMessage("Initial empty repository\n");

        ObjectId id = oi.insert(cb);
        oi.flush();

        for (String ref : refs) {
            RefUpdate ru = repo.updateRef(ref);
            ru.setNewObjectId(id);
            final Result result = ru.update();
            switch (result) {
            case NEW:
                referenceUpdated.fire(project, ru);
                break;
            default: {
                throw new IOException(String.format("Failed to create ref \"%s\": %s", ref, result.name()));
            }
            }
        }
    } catch (IOException e) {
        log.error("Cannot create empty commit for " + createProjectArgs.getProjectName(), e);
        throw e;
    } finally {
        oi.release();
    }
}