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

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

Introduction

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

Prototype

public Result delete() throws IOException 

Source Link

Document

Delete the ref.

Usage

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

License:Apache License

public static void deleteUserBranch(Repository repo, PersonIdent refLogIdent, Account.Id accountId)
        throws IOException {
    String refName = RefNames.refsUsers(accountId);
    Ref ref = repo.exactRef(refName);
    if (ref == null) {
        return;/*from  www.  j ava  2  s.c  o  m*/
    }

    RefUpdate ru = repo.updateRef(refName);
    ru.setExpectedOldObjectId(ref.getObjectId());
    ru.setNewObjectId(ObjectId.zeroId());
    ru.setForceUpdate(true);
    ru.setRefLogIdent(refLogIdent);
    ru.setRefLogMessage("Delete Account", true);
    Result result = ru.delete();
    if (result != Result.FORCED) {
        throw new IOException(String.format("Failed to delete ref %s: %s", refName, result.name()));
    }
}

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

License:Apache License

@Test
public void missingDestRef() throws Exception {
    RefUpdate ru = repo.getRepository().updateRef("refs/heads/master");
    ru.setForceUpdate(true);//from  w w  w.  jav a2s  . c o  m
    assertThat(ru.delete()).isEqualTo(RefUpdate.Result.FORCED);
    Change c = insertChange();
    RevCommit commit = repo.commit().create();
    PatchSet ps = newPatchSet(c.currentPatchSetId(), commit, userId);
    updatePatchSetRef(ps);
    db.patchSets().insert(singleton(ps));

    assertProblems(c, "Destination ref not found (may be new branch): master");
}

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

License:Apache License

private void deleteRef(String refName) throws Exception {
    RefUpdate ru = repo.getRepository().updateRef(refName, true);
    ru.setForceUpdate(true);/* w  ww.  ja v  a2s .co  m*/
    assertThat(ru.delete()).isEqualTo(RefUpdate.Result.FORCED);
}

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

License:Apache License

public void deleteOnlyDraftPatchSet(PatchSet patch, Change change)
        throws NoSuchChangeException, OrmException, IOException {
    PatchSet.Id patchSetId = patch.getId();
    if (!patch.isDraft()) {
        throw new NoSuchChangeException(patchSetId.getParentKey());
    }// w  w w  .jav a  2s . c  o m

    try (Repository repo = gitManager.openRepository(change.getProject())) {
        RefUpdate update = repo.updateRef(patch.getRefName());
        update.setForceUpdate(true);
        update.disableRefLog();
        switch (update.delete()) {
        case NEW:
        case FAST_FORWARD:
        case FORCED:
        case NO_CHANGE:
            // Successful deletion.
            break;
        default:
            throw new IOException("Failed to delete ref " + patch.getRefName() + " in " + repo.getDirectory()
                    + ": " + update.getResult());
        }
        gitRefUpdated.fire(change.getProject(), update, ReceiveCommand.Type.DELETE);
    }

    deleteOnlyDraftPatchSetPreserveRef(this.db.get(), patch);
}

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

License:Apache License

private static void deleteRef(Repository repo, ChangeEdit edit) throws IOException {
    String refName = edit.getRefName();
    RefUpdate ru = repo.updateRef(refName, true);
    ru.setExpectedOldObjectId(edit.getRef().getObjectId());
    ru.setForceUpdate(true);/*from   w w  w .ja  v a 2s.  co  m*/
    RefUpdate.Result result = ru.delete();
    switch (result) {
    case FORCED:
    case NEW:
    case NO_CHANGE:
        break;
    default:
        throw new IOException(String.format("Failed to delete ref %s: %s", refName, result));
    }
}

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  ww w  .j  av a  2s . c o  m*/
 * 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.notedb.ChangeDelete.java

License:Apache License

public void delete() throws OrmException, IOException {
    plcUtil.deleteAllDraftsFromAllUsers(notes.getChangeId());

    RefUpdate ru = repo.updateRef(notes.getRefName());
    ru.setExpectedOldObjectId(notes.load().getRevision());
    ru.setNewObjectId(ObjectId.zeroId());
    ru.setForceUpdate(true);//from www . j  ava 2 s.c  om
    ru.setRefLogMessage("Delete change from NoteDb", false);
    RefUpdate.Result result = ru.delete();
    switch (result) {
    case FAST_FORWARD:
    case FORCED:
    case NO_CHANGE:
        break;

    case IO_FAILURE:
    case LOCK_FAILURE:
    case NEW:
    case NOT_ATTEMPTED:
    case REJECTED:
    case REJECTED_CURRENT_BRANCH:
    case RENAMED:
    default:
        throw new IOException(String.format("Failed to delete change ref %s at %s: %s", notes.getRefName(),
                notes.getRevision(), result));
    }
}

From source file:com.google.gerrit.server.notedb.ChangeRebuilder.java

License:Apache License

private void deleteRef(Change change, Repository changeRepo) throws IOException {
    String refName = ChangeNoteUtil.changeRefName(change.getId());
    RefUpdate ru = changeRepo.updateRef(refName, true);
    ru.setForceUpdate(true);/*  ww w  .  ja va2 s.com*/
    RefUpdate.Result result = ru.delete();
    switch (result) {
    case FORCED:
    case NEW:
    case NO_CHANGE:
        break;
    default:
        throw new IOException(String.format("Failed to delete ref %s: %s", refName, result));
    }
}

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

License:Apache License

@Override
public Response<?> apply(BranchResource rsrc, Input input)
        throws AuthException, ResourceConflictException, OrmException, IOException {
    if (!rsrc.getControl().controlForRef(rsrc.getBranchKey()).canDelete()) {
        throw new AuthException("Cannot delete branch");
    }//from www  . j a v a2s . c o m
    if (!queryProvider.get().setLimit(1).byBranchOpen(rsrc.getBranchKey()).isEmpty()) {
        throw new ResourceConflictException("branch " + rsrc.getBranchKey() + " has open changes");
    }

    try (Repository r = repoManager.openRepository(rsrc.getNameKey())) {
        RefUpdate.Result result;
        RefUpdate u = r.updateRef(rsrc.getRef());
        u.setForceUpdate(true);
        int remainingLockFailureCalls = MAX_LOCK_FAILURE_CALLS;
        for (;;) {
            try {
                result = u.delete();
            } catch (LockFailedException e) {
                result = RefUpdate.Result.LOCK_FAILURE;
            } catch (IOException e) {
                log.error("Cannot delete " + rsrc.getBranchKey(), e);
                throw e;
            }
            if (result == RefUpdate.Result.LOCK_FAILURE && --remainingLockFailureCalls > 0) {
                try {
                    Thread.sleep(SLEEP_ON_LOCK_FAILURE_MS);
                } catch (InterruptedException ie) {
                    // ignore
                }
            } else {
                break;
            }
        }

        switch (result) {
        case NEW:
        case NO_CHANGE:
        case FAST_FORWARD:
        case FORCED:
            referenceUpdated.fire(rsrc.getNameKey(), u, ReceiveCommand.Type.DELETE);
            hooks.doRefUpdatedHook(rsrc.getBranchKey(), u, identifiedUser.get().getAccount());
            ResultSet<SubmoduleSubscription> submoduleSubscriptions = dbProvider.get().submoduleSubscriptions()
                    .bySuperProject(rsrc.getBranchKey());
            dbProvider.get().submoduleSubscriptions().delete(submoduleSubscriptions);
            break;

        case REJECTED_CURRENT_BRANCH:
            log.error("Cannot delete " + rsrc.getBranchKey() + ": " + result.name());
            throw new ResourceConflictException("cannot delete current branch");

        default:
            log.error("Cannot delete " + rsrc.getBranchKey() + ": " + result.name());
            throw new ResourceConflictException("cannot delete branch: " + result.name());
        }
    }
    return Response.none();
}

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

License:Apache License

private void deleteSingleRef(Repository r) throws IOException, ResourceConflictException {
    String ref = refsToDelete.get(0);
    if (prefix != null && !ref.startsWith(prefix)) {
        ref = prefix + ref;/*from   ww w .ja  va2 s.com*/
    }
    RefUpdate.Result result;
    RefUpdate u = r.updateRef(ref);
    u.setExpectedOldObjectId(r.exactRef(ref).getObjectId());
    u.setNewObjectId(ObjectId.zeroId());
    u.setForceUpdate(true);
    refDeletionValidator.validateRefOperation(resource.getName(), identifiedUser.get(), u);
    int remainingLockFailureCalls = MAX_LOCK_FAILURE_CALLS;
    for (;;) {
        try {
            result = u.delete();
        } catch (LockFailedException e) {
            result = RefUpdate.Result.LOCK_FAILURE;
        } catch (IOException e) {
            log.error("Cannot delete " + ref, e);
            throw e;
        }
        if (result == RefUpdate.Result.LOCK_FAILURE && --remainingLockFailureCalls > 0) {
            try {
                Thread.sleep(SLEEP_ON_LOCK_FAILURE_MS);
            } catch (InterruptedException ie) {
                // ignore
            }
        } else {
            break;
        }
    }

    switch (result) {
    case NEW:
    case NO_CHANGE:
    case FAST_FORWARD:
    case FORCED:
        referenceUpdated.fire(resource.getNameKey(), u, ReceiveCommand.Type.DELETE,
                identifiedUser.get().getAccount());
        break;

    case REJECTED_CURRENT_BRANCH:
        log.error("Cannot delete " + ref + ": " + result.name());
        throw new ResourceConflictException("cannot delete current branch");

    case IO_FAILURE:
    case LOCK_FAILURE:
    case NOT_ATTEMPTED:
    case REJECTED:
    case RENAMED:
    default:
        log.error("Cannot delete " + ref + ": " + result.name());
        throw new ResourceConflictException("cannot delete: " + result.name());
    }
}