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

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

Introduction

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

Prototype

public void setForceUpdate(boolean b) 

Source Link

Document

Set if this update wants to forcefully change the ref.

Usage

From source file:com.genuitec.eclipse.gerrit.tools.internal.fbranches.commands.DeleteFeatureBranchCommand.java

License:Open Source License

private void deleteBranchRemotely(final Repository repository, final String branch) throws Exception {
    PushOperationSpecification spec = BranchingUtils.setupPush(repository, ":" + branch); //$NON-NLS-1$

    PushOperationUI op = new PushOperationUI(repository, spec, false) {

        @Override//www  .j  a  v  a  2s . c  o  m
        public PushOperationResult execute(IProgressMonitor monitor) throws CoreException {
            PushOperationResult result = super.execute(monitor);
            for (URIish uri : result.getURIs()) {
                if (result.getErrorMessage(uri) != null) {
                    return result;
                }
            }
            try {
                //delete reference from local repo
                RefUpdate updateRef = repository
                        .updateRef("refs/remotes/origin/" + branch.substring("refs/heads/".length())); //$NON-NLS-1$ //$NON-NLS-2$
                updateRef.setForceUpdate(true);
                updateRef.delete();
            } catch (Exception e) {
                RepositoryUtils.handleException(e);
            }
            return result;
        }

    };
    op.setCredentialsProvider(new EGitCredentialsProvider());
    op.start();
}

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 .  ja  va2  s.  com*/
        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;//  w ww  .  j  a 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.gitblit.utils.JGitUtils.java

License:Apache License

/**
 * Deletes the specified branch ref.//from w  w  w .  ja v  a  2  s .  c om
 *
 * @param repository
 * @param branch
 * @return true if successful
 */
public static boolean deleteBranchRef(Repository repository, String branch) {

    try {
        RefUpdate refUpdate = repository.updateRef(branch, false);
        refUpdate.setForceUpdate(true);
        RefUpdate.Result result = refUpdate.delete();
        switch (result) {
        case NEW:
        case FORCED:
        case NO_CHANGE:
        case FAST_FORWARD:
            return true;
        default:
            LOGGER.error(MessageFormat.format("{0} failed to delete to {1} returned result {2}",
                    repository.getDirectory().getAbsolutePath(), branch, result));
        }
    } catch (Throwable t) {
        error(t, repository, "{0} failed to delete {1}", branch);
    }
    return false;
}

From source file:com.gitblit.utils.JGitUtils.java

License:Apache License

public static boolean commitIndex(Repository db, String branch, DirCache index, ObjectId parentId,
        boolean forceCommit, String author, String authorEmail, String message)
        throws IOException, ConcurrentRefUpdateException {
    boolean success = false;

    ObjectId headId = db.resolve(branch + "^{commit}");
    ObjectId baseId = parentId;/*from w  ww  . j  a v a2  s. com*/
    if (baseId == null || headId == null) {
        return false;
    }

    ObjectInserter odi = db.newObjectInserter();
    try {
        // Create the in-memory index of the new/updated ticket
        ObjectId indexTreeId = index.writeTree(odi);

        // Create a commit object
        PersonIdent ident = new PersonIdent(author, authorEmail);

        if (forceCommit == false) {
            ThreeWayMerger merger = MergeStrategy.RECURSIVE.newMerger(db, true);
            merger.setObjectInserter(odi);
            merger.setBase(baseId);
            boolean mergeSuccess = merger.merge(indexTreeId, headId);

            if (mergeSuccess) {
                indexTreeId = merger.getResultTreeId();
            } else {
                //Manual merge required
                return false;
            }
        }

        CommitBuilder commit = new CommitBuilder();
        commit.setAuthor(ident);
        commit.setCommitter(ident);
        commit.setEncoding(com.gitblit.Constants.ENCODING);
        commit.setMessage(message);
        commit.setParentId(headId);
        commit.setTreeId(indexTreeId);

        // Insert the commit into the repository
        ObjectId commitId = odi.insert(commit);
        odi.flush();

        RevWalk revWalk = new RevWalk(db);
        try {
            RevCommit revCommit = revWalk.parseCommit(commitId);
            RefUpdate ru = db.updateRef(branch);
            ru.setForceUpdate(forceCommit);
            ru.setNewObjectId(commitId);
            ru.setExpectedOldObjectId(headId);
            ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
            Result rc = ru.update();

            switch (rc) {
            case NEW:
            case FORCED:
            case FAST_FORWARD:
                success = true;
                break;
            case REJECTED:
            case LOCK_FAILURE:
                throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
            default:
                throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, branch,
                        commitId.toString(), rc));
            }
        } finally {
            revWalk.close();
        }
    } finally {
        odi.close();
    }
    return success;
}

From source file:com.google.gerrit.acceptance.api.accounts.AccountIT.java

License:Apache License

@After
public void clearPublicKeyStore() throws Exception {
    try (Repository repo = repoManager.openRepository(allUsers)) {
        Ref ref = repo.getRef(REFS_GPG_KEYS);
        if (ref != null) {
            RefUpdate ru = repo.updateRef(REFS_GPG_KEYS);
            ru.setForceUpdate(true);
            assertThat(ru.delete()).isEqualTo(RefUpdate.Result.FORCED);
        }// ww  w.j  a  v  a2s .co  m
    }
}

From source file:com.google.gerrit.acceptance.api.accounts.AccountIT.java

License:Apache License

@After
public void deleteGpgKeys() throws Exception {
    String ref = REFS_GPG_KEYS;/*from  ww  w.jav a 2 s . c o m*/
    try (Repository repo = repoManager.openRepository(allUsers)) {
        if (repo.getRefDatabase().exactRef(ref) != null) {
            RefUpdate ru = repo.updateRef(ref);
            ru.setForceUpdate(true);
            assert_().withFailureMessage("Failed to delete " + ref).that(ru.delete())
                    .isEqualTo(RefUpdate.Result.FORCED);
        }
    }
}

From source file:com.google.gerrit.acceptance.api.accounts.GeneralPreferencesIT.java

License:Apache License

@After
public void cleanUp() throws Exception {
    gApi.accounts().id(user42.getId().toString()).setPreferences(GeneralPreferencesInfo.defaults());

    try (Repository git = repoManager.openRepository(allUsers)) {
        if (git.exactRef(RefNames.REFS_USERS_DEFAULT) != null) {
            RefUpdate u = git.updateRef(RefNames.REFS_USERS_DEFAULT);
            u.setForceUpdate(true);
            assertThat(u.delete()).isEqualTo(RefUpdate.Result.FORCED);
        }/* w  ww. ja  v  a2  s  .  co  m*/
    }
    accountCache.evictAll();
}

From source file:com.google.gerrit.acceptance.api.config.GeneralPreferencesIT.java

License:Apache License

@After
public void cleanUp() throws Exception {
    try (Repository git = repoManager.openRepository(allUsers)) {
        if (git.exactRef(RefNames.REFS_USERS_DEFAULT) != null) {
            RefUpdate u = git.updateRef(RefNames.REFS_USERS_DEFAULT);
            u.setForceUpdate(true);
            assertThat(u.delete()).isEqualTo(RefUpdate.Result.FORCED);
        }/*from w  w w  .  j av  a 2 s .c  om*/
    }
    accountCache.evictAll();
}

From source file:com.google.gerrit.acceptance.server.change.ConsistencyCheckerIT.java

License:Apache License

@Test
public void missingDestRef() throws Exception {
    String ref = "refs/heads/master";
    // Detach head so we're allowed to delete ref.
    testRepo.reset(testRepo.getRepository().getRef(ref).getObjectId());
    RefUpdate ru = testRepo.getRepository().updateRef(ref);
    ru.setForceUpdate(true);
    assertThat(ru.delete()).isEqualTo(RefUpdate.Result.FORCED);
    Change c = insertChange();//ww  w.j  a va2 s.c  o m
    RevCommit commit = testRepo.commit().create();
    PatchSet ps = newPatchSet(c.currentPatchSetId(), commit, adminId);
    updatePatchSetRef(ps);
    db.patchSets().insert(singleton(ps));

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