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(RevWalk walk) throws IOException 

Source Link

Document

Gracefully update the ref to the new value.

Usage

From source file:com.gitblit.git.PatchsetReceivePack.java

License:Apache License

private RefUpdate updateRef(String ref, ObjectId newId, PatchsetType type) {
    ObjectId ticketRefId = ObjectId.zeroId();
    try {//  ww w .j  a  v  a 2  s. c o m
        ticketRefId = getRepository().resolve(ref);
    } catch (Exception e) {
        // ignore
    }

    try {
        RefUpdate ru = getRepository().updateRef(ref, false);
        ru.setRefLogIdent(getRefLogIdent());
        switch (type) {
        case Amend:
        case Rebase:
        case Rebase_Squash:
        case Squash:
            ru.setForceUpdate(true);
            break;
        default:
            break;
        }

        ru.setExpectedOldObjectId(ticketRefId);
        ru.setNewObjectId(newId);
        RefUpdate.Result result = ru.update(getRevWalk());
        if (result == RefUpdate.Result.LOCK_FAILURE) {
            sendError("Failed to obtain lock when updating {0}:{1}", repository.name, ref);
            sendError("Perhaps an administrator should remove {0}/{1}.lock?", getRepository().getDirectory(),
                    ref);
            return null;
        }
        return ru;
    } catch (IOException e) {
        LOGGER.error("failed to update ref " + ref, e);
        sendError("There was an error updating ref {0}:{1}", repository.name, ref);
    }
    return null;
}

From source file:com.gitblit.plugin.smartticketbranches.SmartTicketBranchesHook.java

License:Apache License

@Override
public void onUpdateTicket(TicketModel ticket, Change change) {
    if (!ticket.hasPatchsets()) {
        // ticket has no patchsets, nothing to do
        return;//from   w  w w  .  ja v a 2  s . c  o m
    }

    if (!change.isStatusChange()) {
        // not a status change, nothing to do
        return;
    }

    final Patchset ps = ticket.getCurrentPatchset();
    final String branch = PatchsetCommand.getTicketBranch(ticket.number);
    final IRepositoryManager repositoryManager = GitblitContext.getManager(IRepositoryManager.class);
    final Repository repo = repositoryManager.getRepository(ticket.repository);
    try {
        switch (change.getStatus()) {
        case New:
            // NOOP, new proposal
            log.debug("new proposal, skipping");
            break;
        case Open:
            /*
             *  Open or Re-open: create branch, if not exists
             */
            if (null == repo.getRef(branch)) {
                log.debug("ticket re-opened, trying to create '{}'", branch);
                RefUpdate ru = repo.updateRef(branch);
                ru.setExpectedOldObjectId(ObjectId.zeroId());
                ru.setNewObjectId(ObjectId.fromString(ps.tip));

                RevWalk rw = null;
                try {
                    rw = new RevWalk(repo);
                    RefUpdate.Result result = ru.update(rw);
                    switch (result) {
                    case NEW:
                        log.info(String.format("%s ticket RE-OPENED, created %s:%s", name, ticket.repository,
                                branch));
                        break;
                    default:
                        log.error(String.format("%s failed to re-create %s:%s (%s)", name, ticket.repository,
                                branch, result));
                        break;
                    }
                } finally {
                    if (rw != null) {
                        rw.release();
                    }
                }
            }
            break;
        default:
            /*
             * Ticket closed: delete branch, if exists
             */
            log.debug("ticket closed, trying to remove '{}'", branch);
            RefUpdate ru = repo.updateRef(branch);
            ru.setExpectedOldObjectId(ObjectId.fromString(ps.tip));
            ru.setNewObjectId(ObjectId.zeroId());
            ru.setForceUpdate(true);

            RefUpdate.Result result = ru.delete();
            switch (result) {
            case FORCED:
                log.info(String.format("%s ticket %s, removed %s:%s", name, change.getStatus(),
                        ticket.repository, branch));
                break;
            default:
                log.error(String.format("%s failed to remove %s:%s (%s)", name, ticket.repository, branch,
                        result));
                break;
            }
        }
    } catch (IOException e) {
        log.error(null, e);
    } finally {
        if (repo != null) {
            repo.close();
        }
    }
}

From source file:com.google.gerrit.httpd.rpc.project.AddBranch.java

License:Apache License

@Override
public ListBranchesResult call() throws NoSuchProjectException, InvalidNameException, InvalidRevisionException,
        IOException, BranchCreationNotAllowedException {
    final ProjectControl projectControl = projectControlFactory.controlFor(projectName);

    String refname = branchName;/*  ww  w  .ja  va  2s  .c  o m*/
    while (refname.startsWith("/")) {
        refname = refname.substring(1);
    }
    if (!refname.startsWith(Constants.R_REFS)) {
        refname = Constants.R_HEADS + refname;
    }
    if (!Repository.isValidRefName(refname)) {
        throw new InvalidNameException();
    }
    if (refname.startsWith(ReceiveCommits.NEW_CHANGE)) {
        throw new BranchCreationNotAllowedException(ReceiveCommits.NEW_CHANGE);
    }

    final Branch.NameKey name = new Branch.NameKey(projectName, refname);
    final RefControl refControl = projectControl.controlForRef(name);
    final Repository repo = repoManager.openRepository(projectName);
    try {
        final ObjectId revid = parseStartingRevision(repo);
        final RevWalk rw = verifyConnected(repo, revid);
        RevObject object = rw.parseAny(revid);

        if (refname.startsWith(Constants.R_HEADS)) {
            // Ensure that what we start the branch from is a commit. If we
            // were given a tag, deference to the commit instead.
            //
            try {
                object = rw.parseCommit(object);
            } catch (IncorrectObjectTypeException notCommit) {
                throw new IllegalStateException(startingRevision + " not a commit");
            }
        }

        if (!refControl.canCreate(rw, object)) {
            throw new IllegalStateException("Cannot create " + refname);
        }

        try {
            final RefUpdate u = repo.updateRef(refname);
            u.setExpectedOldObjectId(ObjectId.zeroId());
            u.setNewObjectId(object.copy());
            u.setRefLogIdent(identifiedUser.newRefLogIdent());
            u.setRefLogMessage("created via web from " + startingRevision, false);
            final RefUpdate.Result result = u.update(rw);
            switch (result) {
            case FAST_FORWARD:
            case NEW:
            case NO_CHANGE:
                replication.scheduleUpdate(name.getParentKey(), refname);
                hooks.doRefUpdatedHook(name, u, identifiedUser.getAccount());
                break;
            default: {
                throw new IOException(result.name());
            }
            }
        } catch (IOException err) {
            log.error("Cannot create branch " + name, err);
            throw err;
        }
    } finally {
        repo.close();
    }

    return listBranchesFactory.create(projectName).call();
}

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

License:Apache License

private Change createNewChange(Repository git, RevWalk revWalk, Change.Key changeKey, Project.NameKey project,
        Ref destRef, CodeReviewCommit cherryPickCommit, RefControl refControl, IdentifiedUser identifiedUser,
        String topic) throws OrmException, InvalidChangeOperationException, IOException {
    Change change = new Change(changeKey, new Change.Id(db.get().nextChangeId()), identifiedUser.getAccountId(),
            new Branch.NameKey(project, destRef.getName()), TimeUtil.nowTs());
    change.setTopic(topic);//  w w w  .j  a  v  a  2 s.co m
    ChangeInserter ins = changeInserterFactory.create(refControl.getProjectControl(), change, cherryPickCommit);
    PatchSet newPatchSet = ins.getPatchSet();

    CommitValidators commitValidators = commitValidatorsFactory.create(refControl, new NoSshInfo(), git);
    CommitReceivedEvent commitReceivedEvent = new CommitReceivedEvent(
            new ReceiveCommand(ObjectId.zeroId(), cherryPickCommit.getId(), newPatchSet.getRefName()),
            refControl.getProjectControl().getProject(), refControl.getRefName(), cherryPickCommit,
            identifiedUser);

    try {
        commitValidators.validateForGerritCommits(commitReceivedEvent);
    } catch (CommitValidationException e) {
        throw new InvalidChangeOperationException(e.getMessage());
    }

    final RefUpdate ru = git.updateRef(newPatchSet.getRefName());
    ru.setExpectedOldObjectId(ObjectId.zeroId());
    ru.setNewObjectId(cherryPickCommit);
    ru.disableRefLog();
    if (ru.update(revWalk) != RefUpdate.Result.NEW) {
        throw new IOException(String.format("Failed to create ref %s in %s: %s", newPatchSet.getRefName(),
                change.getDest().getParentKey().get(), ru.getResult()));
    }

    ins.insert();

    return change;
}

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

License:Apache License

private static void updateRef(Repository git, RevWalk rw, RevCommit c, Change change, PatchSet newPatchSet)
        throws IOException {
    RefUpdate ru = git.updateRef(newPatchSet.getRefName());
    ru.setExpectedOldObjectId(ObjectId.zeroId());
    ru.setNewObjectId(c);/* www .  j ava2  s .c o m*/
    ru.disableRefLog();
    if (ru.update(rw) != RefUpdate.Result.NEW) {
        throw new IOException(String.format("Failed to create ref %s in %s: %s", newPatchSet.getRefName(),
                change.getDest().getParentKey().get(), ru.getResult()));
    }
}

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

License:Apache License

public Change insert()
        throws InvalidChangeOperationException, OrmException, IOException, NoSuchChangeException {
    init();/*from   ww  w  . j av a  2  s.c o  m*/
    validate();

    Change c = ctl.getChange();
    Change updatedChange;
    RefUpdate ru = git.updateRef(patchSet.getRefName());
    ru.setExpectedOldObjectId(ObjectId.zeroId());
    ru.setNewObjectId(commit);
    ru.disableRefLog();
    if (ru.update(revWalk) != RefUpdate.Result.NEW) {
        throw new IOException(String.format("Failed to create ref %s in %s: %s", patchSet.getRefName(),
                c.getDest().getParentKey().get(), ru.getResult()));
    }
    gitRefUpdated.fire(c.getProject(), ru);

    final PatchSet.Id currentPatchSetId = c.currentPatchSetId();

    ChangeUpdate update = updateFactory.create(ctl, patchSet.getCreatedOn());

    db.changes().beginTransaction(c.getId());
    try {
        updatedChange = db.changes().get(c.getId());
        if (!updatedChange.getStatus().isOpen() && !allowClosed) {
            throw new InvalidChangeOperationException(String.format("Change %s is closed", c.getId()));
        }

        ChangeUtil.insertAncestors(db, patchSet.getId(), commit);
        if (groups != null) {
            patchSet.setGroups(groups);
        } else {
            patchSet.setGroups(GroupCollector.getCurrentGroups(db, c));
        }
        db.patchSets().insert(Collections.singleton(patchSet));

        SetMultimap<ReviewerState, Account.Id> oldReviewers = sendMail
                ? approvalsUtil.getReviewers(db, ctl.getNotes())
                : null;

        updatedChange = db.changes().atomicUpdate(c.getId(), new AtomicUpdate<Change>() {
            @Override
            public Change update(Change change) {
                if (change.getStatus().isClosed() && !allowClosed) {
                    return null;
                }
                if (!change.currentPatchSetId().equals(currentPatchSetId)) {
                    return null;
                }
                if (change.getStatus() != Change.Status.DRAFT && !allowClosed) {
                    change.setStatus(Change.Status.NEW);
                }
                change.setCurrentPatchSet(patchSetInfoFactory.get(commit, patchSet.getId()));
                ChangeUtil.updated(change);
                return change;
            }
        });
        if (updatedChange == null) {
            throw new ChangeModifiedException(String.format("Change %s was modified", c.getId()));
        }

        if (messageIsForChange()) {
            cmUtil.addChangeMessage(db, update, changeMessage);
        }

        approvalCopier.copy(db, ctl, patchSet);
        db.commit();
        if (messageIsForChange()) {
            update.commit();
        }

        if (!messageIsForChange()) {
            commitMessageNotForChange(updatedChange);
        }

        if (sendMail) {
            try {
                PatchSetInfo info = patchSetInfoFactory.get(commit, patchSet.getId());
                ReplacePatchSetSender cm = replacePatchSetFactory.create(c.getId());
                cm.setFrom(user.getAccountId());
                cm.setPatchSet(patchSet, info);
                cm.setChangeMessage(changeMessage);
                cm.addReviewers(oldReviewers.get(ReviewerState.REVIEWER));
                cm.addExtraCC(oldReviewers.get(ReviewerState.CC));
                cm.send();
            } catch (Exception err) {
                log.error("Cannot send email for new patch set on change " + updatedChange.getId(), err);
            }
        }

    } finally {
        db.rollback();
    }
    indexer.index(db, updatedChange);
    if (runHooks) {
        hooks.doPatchsetCreatedHook(updatedChange, patchSet, db);
    }
    return updatedChange;
}

From source file:com.google.gerrit.server.ChangeUtil.java

License:Apache License

public Change.Id revert(ChangeControl ctl, PatchSet.Id patchSetId, String message, PersonIdent myIdent,
        SshInfo sshInfo) throws NoSuchChangeException, OrmException, MissingObjectException,
        IncorrectObjectTypeException, IOException, InvalidChangeOperationException {
    Change.Id changeId = patchSetId.getParentKey();
    PatchSet patch = db.get().patchSets().get(patchSetId);
    if (patch == null) {
        throw new NoSuchChangeException(changeId);
    }/*from   w  w  w.ja  v  a2  s.  c o m*/
    Change changeToRevert = db.get().changes().get(changeId);

    Project.NameKey project = ctl.getChange().getProject();
    try (Repository git = gitManager.openRepository(project); RevWalk revWalk = new RevWalk(git)) {
        RevCommit commitToRevert = revWalk.parseCommit(ObjectId.fromString(patch.getRevision().get()));

        PersonIdent authorIdent = user().newCommitterIdent(myIdent.getWhen(), myIdent.getTimeZone());

        RevCommit parentToCommitToRevert = commitToRevert.getParent(0);
        revWalk.parseHeaders(parentToCommitToRevert);

        CommitBuilder revertCommitBuilder = new CommitBuilder();
        revertCommitBuilder.addParentId(commitToRevert);
        revertCommitBuilder.setTreeId(parentToCommitToRevert.getTree());
        revertCommitBuilder.setAuthor(authorIdent);
        revertCommitBuilder.setCommitter(authorIdent);

        if (message == null) {
            message = MessageFormat.format(ChangeMessages.get().revertChangeDefaultMessage,
                    changeToRevert.getSubject(), patch.getRevision().get());
        }

        ObjectId computedChangeId = ChangeIdUtil.computeChangeId(parentToCommitToRevert.getTree(),
                commitToRevert, authorIdent, myIdent, message);
        revertCommitBuilder.setMessage(ChangeIdUtil.insertId(message, computedChangeId, true));

        RevCommit revertCommit;
        try (ObjectInserter oi = git.newObjectInserter()) {
            ObjectId id = oi.insert(revertCommitBuilder);
            oi.flush();
            revertCommit = revWalk.parseCommit(id);
        }

        RefControl refControl = ctl.getRefControl();
        Change change = new Change(new Change.Key("I" + computedChangeId.name()),
                new Change.Id(db.get().nextChangeId()), user().getAccountId(), changeToRevert.getDest(),
                TimeUtil.nowTs());
        change.setTopic(changeToRevert.getTopic());
        ChangeInserter ins = changeInserterFactory.create(refControl.getProjectControl(), change, revertCommit);
        PatchSet ps = ins.getPatchSet();

        String ref = refControl.getRefName();
        String cmdRef = MagicBranch.NEW_PUBLISH_CHANGE + ref.substring(ref.lastIndexOf('/') + 1);
        CommitReceivedEvent commitReceivedEvent = new CommitReceivedEvent(
                new ReceiveCommand(ObjectId.zeroId(), revertCommit.getId(), cmdRef),
                refControl.getProjectControl().getProject(), refControl.getRefName(), revertCommit, user());

        try {
            commitValidatorsFactory.create(refControl, sshInfo, git)
                    .validateForGerritCommits(commitReceivedEvent);
        } catch (CommitValidationException e) {
            throw new InvalidChangeOperationException(e.getMessage());
        }

        RefUpdate ru = git.updateRef(ps.getRefName());
        ru.setExpectedOldObjectId(ObjectId.zeroId());
        ru.setNewObjectId(revertCommit);
        ru.disableRefLog();
        if (ru.update(revWalk) != RefUpdate.Result.NEW) {
            throw new IOException(String.format("Failed to create ref %s in %s: %s", ps.getRefName(),
                    change.getDest().getParentKey().get(), ru.getResult()));
        }

        ChangeMessage cmsg = new ChangeMessage(new ChangeMessage.Key(changeId, messageUUID(db.get())),
                user().getAccountId(), TimeUtil.nowTs(), patchSetId);
        StringBuilder msgBuf = new StringBuilder();
        msgBuf.append("Patch Set ").append(patchSetId.get()).append(": Reverted");
        msgBuf.append("\n\n");
        msgBuf.append("This patchset was reverted in change: ").append(change.getKey().get());
        cmsg.setMessage(msgBuf.toString());

        ins.setMessage(cmsg).insert();

        try {
            RevertedSender cm = revertedSenderFactory.create(change.getId());
            cm.setFrom(user().getAccountId());
            cm.setChangeMessage(cmsg);
            cm.send();
        } catch (Exception err) {
            log.error("Cannot send email for revert change " + change.getId(), err);
        }

        return change.getId();
    } catch (RepositoryNotFoundException e) {
        throw new NoSuchChangeException(changeId, e);
    }
}

From source file:com.google.gerrit.server.edit.ChangeEditModifier.java

License:Apache License

private RefUpdate.Result update(Repository repo, IdentifiedUser me, String refName, RevWalk rw,
        ObjectId oldObjectId, ObjectId newEdit) throws IOException {
    RefUpdate ru = repo.updateRef(refName);
    ru.setExpectedOldObjectId(oldObjectId);
    ru.setNewObjectId(newEdit);// w w  w  .j  av  a  2 s. c  o m
    ru.setRefLogIdent(getRefLogIdent(me));
    ru.setRefLogMessage("inline edit (amend)", false);
    ru.setForceUpdate(true);
    RefUpdate.Result res = ru.update(rw);
    if (res != RefUpdate.Result.NEW && res != RefUpdate.Result.FORCED) {
        throw new IOException("update failed: " + ru);
    }
    return res;
}

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

License:Apache License

private CodeReviewCommit writeCherryPickCommit(final CodeReviewCommit mergeTip, final CodeReviewCommit n)
        throws IOException, OrmException {

    args.rw.parseBody(n);// w w  w.  ja va  2  s . co  m

    final PatchSetApproval submitAudit = args.mergeUtil.getSubmitter(n.change.currentPatchSetId());

    PersonIdent cherryPickCommitterIdent = null;
    if (submitAudit != null) {
        cherryPickCommitterIdent = args.identifiedUserFactory.create(submitAudit.getAccountId())
                .newCommitterIdent(submitAudit.getGranted(), args.myIdent.getTimeZone());
    } else {
        cherryPickCommitterIdent = args.myIdent;
    }

    final String cherryPickCmtMsg = args.mergeUtil.createCherryPickCommitMessage(n);

    final CodeReviewCommit newCommit = (CodeReviewCommit) args.mergeUtil.createCherryPickFromCommit(args.repo,
            args.inserter, mergeTip, n, cherryPickCommitterIdent, cherryPickCmtMsg, args.rw);

    if (newCommit == null) {
        return null;
    }

    PatchSet.Id id = ChangeUtil.nextPatchSetId(args.repo, n.change.currentPatchSetId());
    final PatchSet ps = new PatchSet(id);
    ps.setCreatedOn(new Timestamp(System.currentTimeMillis()));
    ps.setUploader(submitAudit.getAccountId());
    ps.setRevision(new RevId(newCommit.getId().getName()));
    insertAncestors(args.db, ps.getId(), newCommit);
    args.db.patchSets().insert(Collections.singleton(ps));

    n.change.setCurrentPatchSet(patchSetInfoFactory.get(newCommit, ps.getId()));
    args.db.changes().update(Collections.singletonList(n.change));

    final List<PatchSetApproval> approvals = Lists.newArrayList();
    for (PatchSetApproval a : args.mergeUtil.getApprovalsForCommit(n)) {
        approvals.add(new PatchSetApproval(ps.getId(), a));
    }
    args.db.patchSetApprovals().insert(approvals);

    final RefUpdate ru = args.repo.updateRef(ps.getRefName());
    ru.setExpectedOldObjectId(ObjectId.zeroId());
    ru.setNewObjectId(newCommit);
    ru.disableRefLog();
    if (ru.update(args.rw) != RefUpdate.Result.NEW) {
        throw new IOException(String.format("Failed to create ref %s in %s: %s", ps.getRefName(),
                n.change.getDest().getParentKey().get(), ru.getResult()));
    }

    gitRefUpdated.fire(n.change.getProject(), ru);

    newCommit.copyFrom(n);
    newCommit.statusCode = CommitMergeStatus.CLEAN_PICK;
    newCommits.put(newCommit.patchsetId.getParentKey(), newCommit);
    setRefLogIdent(submitAudit);
    return newCommit;
}

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

License:Apache License

private RefUpdate updateBranch(Branch.NameKey destBranch) throws MergeException {
    RefUpdate branchUpdate = getPendingRefUpdate(destBranch);
    CodeReviewCommit branchTip = getBranchTip(destBranch);

    MergeTip mergeTip = mergeTips.get(destBranch);

    CodeReviewCommit currentTip = mergeTip != null ? mergeTip.getCurrentTip() : null;
    if (Objects.equals(branchTip, currentTip)) {
        if (currentTip != null) {
            logDebug("Branch already at merge tip {}, no update to perform", currentTip.name());
        } else {//from   ww  w .  j a  v  a  2  s . c  o  m
            logDebug("Both branch and merge tip are nonexistent, no update");
        }
        return null;
    } else if (currentTip == null) {
        logDebug("No merge tip, no update to perform");
        return null;
    }

    if (RefNames.REFS_CONFIG.equals(branchUpdate.getName())) {
        logDebug("Loading new configuration from {}", RefNames.REFS_CONFIG);
        try {
            ProjectConfig cfg = new ProjectConfig(destProject.getProject().getNameKey());
            cfg.load(repo, currentTip);
        } catch (Exception e) {
            throw new MergeException("Submit would store invalid" + " project configuration "
                    + currentTip.name() + " for " + destProject.getProject().getName(), e);
        }
    }

    branchUpdate.setRefLogIdent(refLogIdent);
    branchUpdate.setForceUpdate(false);
    branchUpdate.setNewObjectId(currentTip);
    branchUpdate.setRefLogMessage("merged", true);
    try {
        RefUpdate.Result result = branchUpdate.update(rw);
        logDebug("Update of {}: {}..{} returned status {}", branchUpdate.getName(),
                branchUpdate.getOldObjectId(), branchUpdate.getNewObjectId(), result);
        switch (result) {
        case NEW:
        case FAST_FORWARD:
            if (branchUpdate.getResult() == RefUpdate.Result.FAST_FORWARD) {
                tagCache.updateFastForward(destBranch.getParentKey(), branchUpdate.getName(),
                        branchUpdate.getOldObjectId(), currentTip);
            }

            if (RefNames.REFS_CONFIG.equals(branchUpdate.getName())) {
                Project p = destProject.getProject();
                projectCache.evict(p);
                destProject = projectCache.get(p.getNameKey());
                repoManager.setProjectDescription(p.getNameKey(), p.getDescription());
            }

            return branchUpdate;

        case LOCK_FAILURE:
            throw new MergeException("Failed to lock " + branchUpdate.getName());
        default:
            throw new IOException(branchUpdate.getResult().name() + '\n' + branchUpdate);
        }
    } catch (IOException e) {
        throw new MergeException("Cannot update " + branchUpdate.getName(), e);
    }
}