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.google.gerrit.server.StarredChangesUtil.java

License:Apache License

public void unstar(Account.Id accountId, Project.NameKey project, Change.Id changeId) throws OrmException {
    try (Repository repo = repoManager.openRepository(allUsers); RevWalk rw = new RevWalk(repo)) {
        RefUpdate u = repo.updateRef(RefNames.refsStarredChanges(changeId, accountId));
        u.setForceUpdate(true);
        u.setRefLogIdent(serverIdent);//from  w w w  .  jav  a 2  s . c  o m
        u.setRefLogMessage("Unstar change " + changeId.get(), true);
        RefUpdate.Result result = u.delete();
        switch (result) {
        case FORCED:
            indexer.index(dbProvider.get(), project, changeId);
            return;
        case FAST_FORWARD:
        case IO_FAILURE:
        case LOCK_FAILURE:
        case NEW:
        case NOT_ATTEMPTED:
        case NO_CHANGE:
        case REJECTED:
        case REJECTED_CURRENT_BRANCH:
        case RENAMED:
        default:
            throw new OrmException(String.format("Unstar change %d for account %d failed: %s", changeId.get(),
                    accountId.get(), result.name()));
        }
    } catch (IOException e) {
        throw new OrmException(
                String.format("Unstar change %d for account %d failed", changeId.get(), accountId.get()), e);
    }
}

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

License:Apache License

private void updateLabels(Repository repo, String refName, ObjectId oldObjectId, SortedSet<String> labels)
        throws IOException, OrmException {
    try (RevWalk rw = new RevWalk(repo)) {
        RefUpdate u = repo.updateRef(refName);
        u.setExpectedOldObjectId(oldObjectId);
        u.setForceUpdate(true);
        u.setNewObjectId(writeLabels(repo, labels));
        u.setRefLogIdent(serverIdent);/* w  w  w .ja v a 2s.  c  om*/
        u.setRefLogMessage("Update star labels", true);
        RefUpdate.Result result = u.update(rw);
        switch (result) {
        case NEW:
        case FORCED:
        case NO_CHANGE:
        case FAST_FORWARD:
            return;
        case IO_FAILURE:
        case LOCK_FAILURE:
        case NOT_ATTEMPTED:
        case REJECTED:
        case REJECTED_CURRENT_BRANCH:
        case RENAMED:
            throw new OrmException(
                    String.format("Update star labels on ref %s failed: %s", refName, result.name()));
        }
    }
}

From source file:com.googlesource.gerrit.plugins.manifest.TempRef.java

License:Apache License

@Inject
public TempRef(GitRepositoryManager repoManager, @Assisted Branch.NameKey branch) throws IOException {
    this.repoManager = repoManager;

    Project.NameKey project = branch.getParentKey();
    tempRef = new Branch.NameKey(project, "refs/temp/" + UUID.randomUUID().toString());

    Repository repo = repoManager.openRepository(project);
    try {/*from  w  ww.  java 2 s . co  m*/
        RefUpdate refUpdate = repo.updateRef(tempRef.get());
        refUpdate.setNewObjectId(repo.getRef(branch.get()).getObjectId());
        refUpdate.setForceUpdate(true);
        refUpdate.update();
    } finally {
        repo.close();
    }
}

From source file:com.googlesource.gerrit.plugins.manifest.TempRef.java

License:Apache License

public void close() throws IOException {
    Repository repo = repoManager.openRepository(tempRef.getParentKey());
    try {/*from www.j  a  v  a2  s .c  o  m*/
        RefUpdate refUpdate = repo.updateRef(tempRef.get());
        refUpdate.setNewObjectId(ObjectId.zeroId());
        refUpdate.setForceUpdate(true);
        refUpdate.delete();
    } finally {
        tempRef = null;
        repo.close();
    }
}

From source file:com.googlesource.gerrit.plugins.refprotection.BackupRef.java

License:Open Source License

public void createBackup(RefUpdatedEvent event, ProjectResource project) {
    String refName = event.getRefName();

    try (Repository git = repoManager.openRepository(project.getNameKey())) {
        String backupRef = get(project, refName);

        // No-op if the backup branch name is same as the original
        if (backupRef.equals(refName)) {
            return;
        }//from  w  w  w .j a v  a2 s.c  o m

        try (RevWalk revWalk = new RevWalk(git)) {
            RefUpdateAttribute refUpdate = event.refUpdate.get();
            if (cfg.getFromGerritConfig(pluginName).getBoolean("createTag", false)) {
                TagBuilder tag = new TagBuilder();
                AccountAttribute submitter = event.submitter.get();
                tag.setTagger(new PersonIdent(submitter.name, submitter.email));
                tag.setObjectId(revWalk.parseCommit(ObjectId.fromString(refUpdate.oldRev)));
                String update = "Non-fast-forward update to";
                if (refUpdate.newRev.equals(ObjectId.zeroId().getName())) {
                    update = "Deleted";
                }
                String type = "branch";
                String fullMessage = "";
                if (refUpdate.refName.startsWith(R_TAGS)) {
                    type = "tag";
                    try {
                        RevTag origTag = revWalk.parseTag(ObjectId.fromString(refUpdate.oldRev));
                        SimpleDateFormat format = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy ZZZZ");
                        PersonIdent taggerIdent = origTag.getTaggerIdent();
                        String tagger = String.format("Tagger: %s <%s>\nDate:   %s", taggerIdent.getName(),
                                taggerIdent.getEmailAddress(), format.format(taggerIdent.getWhen()));
                        fullMessage = "\n\nOriginal tag:\n" + tagger + "\n\n" + origTag.getFullMessage();
                    } catch (MissingObjectException e) {
                        log.warn("Original tag does not exist", e);
                    } catch (IncorrectObjectTypeException e) {
                        log.warn("Original tag was not a tag", e);
                    } catch (IOException e) {
                        log.warn("Unable to read original tag details", e);
                    }
                }
                tag.setMessage(update + " " + type + " " + refUpdate.refName + fullMessage);
                tag.setTag(backupRef);

                ObjectInserter inserter = git.newObjectInserter();
                ObjectId tagId = inserter.insert(tag);
                inserter.flush();
                RefUpdate tagRef = git.updateRef(tag.getTag());
                tagRef.setNewObjectId(tagId);
                tagRef.setRefLogMessage("tagged deleted branch/tag " + tag.getTag(), false);
                tagRef.setForceUpdate(false);
                Result result = tagRef.update();
                switch (result) {
                case NEW:
                case FORCED:
                    log.debug("Successfully created backup tag");
                    break;

                case LOCK_FAILURE:
                    log.error("Failed to lock repository while creating backup tag");
                    break;

                case REJECTED:
                    log.error("Tag already exists while creating backup tag");
                    break;

                default:
                    log.error("Unknown error while creating backup tag");
                }
            } else {
                BranchInput input = new BranchInput();
                input.ref = backupRef;
                // We need to parse the commit to ensure if it's a tag, we get the
                // commit the tag points to!
                input.revision = ObjectId
                        .toString(revWalk.parseCommit(ObjectId.fromString(refUpdate.oldRev)).getId());

                try {
                    createBranchFactory.create(backupRef).apply(project, input);
                } catch (BadRequestException | AuthException | ResourceConflictException | IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    } catch (RepositoryNotFoundException e) {
        log.error("Repository does not exist", e);
    } catch (IOException e) {
        log.error("Could not open repository", e);
    }
}

From source file:com.madgag.agit.TagViewer.java

License:Open Source License

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Log.i(TAG, "onOptionsItemSelected " + item);
    switch (item.getItemId()) {
    case DELETE_ID:
        try {//from  w ww.ja  va  2  s .  c  o  m
            RefUpdate update = repo().updateRef(tagRef.getName());
            update.setForceUpdate(true);
            // update.setNewObjectId(head);
            // update.setForceUpdate(force || remote);
            Result result = update.delete();
            Toast.makeText(this, "Tag deletion : " + result.name(), Toast.LENGTH_SHORT).show();
            finish();
        } catch (IOException e) {
            Log.e(TAG, "Couldn't delete " + revTag.getName(), e);
            throw new RuntimeException(e);
        }
        return true;
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.microsoft.gittf.core.util.TfsBranchUtil.java

License:Open Source License

/**
 * Updates the remote tracking branch and branch to point at the commit
 * specified./*from  w w w .j  av  a2s . c  o  m*/
 * 
 * @param repository
 * @param commitId
 * @throws IOException
 * @throws RefAlreadyExistsException
 * @throws RefNotFoundException
 * @throws InvalidRefNameException
 * @throws GitAPIException
 */
public static void update(Repository repository, ObjectId commitId) throws IOException,
        RefAlreadyExistsException, RefNotFoundException, InvalidRefNameException, GitAPIException {
    if (repository.isBare()) {
        Ref tfsBranchRef = repository.getRef(Constants.R_HEADS + GitTFConstants.GIT_TF_BRANCHNAME);
        if (tfsBranchRef == null) {
            create(repository);
        }

        RefUpdate ref = repository.updateRef(Constants.R_HEADS + GitTFConstants.GIT_TF_BRANCHNAME);
        ref.setNewObjectId(commitId);
        ref.setForceUpdate(true);
        ref.update();
    }

    TfsRemoteReferenceUpdate remoteRefUpdate = new TfsRemoteReferenceUpdate(repository, commitId.name());
    remoteRefUpdate.update();

}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.GitServerUtil.java

License:Apache License

/**
 * Removes branches of a bare repository which are not present in a remote repository
 *//*  w  w  w  . ja va  2s  .c o m*/
private static void pruneRemovedBranches(@NotNull Repository db, @NotNull Transport tn) throws IOException {
    FetchConnection conn = null;
    try {
        conn = tn.openFetch();
        Map<String, Ref> remoteRefMap = conn.getRefsMap();
        for (Map.Entry<String, Ref> e : db.getAllRefs().entrySet()) {
            if (!remoteRefMap.containsKey(e.getKey())) {
                try {
                    RefUpdate refUpdate = db.getRefDatabase().newUpdate(e.getKey(), false);
                    refUpdate.setForceUpdate(true);
                    refUpdate.delete();
                } catch (Exception ex) {
                    LOG.info("Failed to prune removed ref " + e.getKey(), ex);
                    break;
                }
            }
        }
    } finally {
        if (conn != null)
            conn.close();
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.CollectChangesTest.java

License:Apache License

@TestFor(issues = { "TW-36080", "TW-35700" })
@Test(dataProvider = "separateProcess,newConnectionForPrune")
public void branch_turned_into_dir(boolean fetchInSeparateProcess, boolean newConnectionForPrune)
        throws Exception {
    myConfig.setSeparateProcessForFetch(fetchInSeparateProcess).setNewConnectionForPrune(newConnectionForPrune);
    VcsRoot root = vcsRoot().withFetchUrl(myRepo).withBranch("master").build();
    RepositoryStateData s1 = createVersionState("refs/heads/master",
            map("refs/heads/master", "f3f826ce85d6dad25156b2d7550cedeb1a422f4c", "refs/heads/patch-tests",
                    "a894d7d58ffde625019a9ecf8267f5f1d1e5c341"));
    RepositoryStateData s2 = createVersionState("refs/heads/master",
            map("refs/heads/master", "3b9fbfbb43e7edfad018b482e15e7f93cca4e69f", "refs/heads/patch-tests",
                    "a894d7d58ffde625019a9ecf8267f5f1d1e5c341"));

    git().getCollectChangesPolicy().collectChanges(root, s1, s2, CheckoutRules.DEFAULT);

    //rename refs/heads/patch-tests to refs/heads/patch-tests/a and make it point to commit not yet fetched by TC, so the fetch is required
    Repository r = new RepositoryBuilder().setGitDir(myRepo).build();
    r.getRefDatabase().newRename("refs/heads/patch-tests", "refs/heads/patch-tests/a").rename();
    RefUpdate refUpdate = r.updateRef("refs/heads/patch-tests/a");
    refUpdate.setForceUpdate(true);
    refUpdate.setNewObjectId(ObjectId.fromString("39679cc440c83671fbf6ad8083d92517f9602300"));
    refUpdate.update();/*  w ww  .  j  a v a  2  s .co m*/

    RepositoryStateData s3 = createVersionState("refs/heads/master",
            map("refs/heads/master", "3b9fbfbb43e7edfad018b482e15e7f93cca4e69f", "refs/heads/patch-tests/a",
                    "39679cc440c83671fbf6ad8083d92517f9602300"));
    git().getCollectChangesPolicy().collectChanges(root, s2, s3, CheckoutRules.DEFAULT);
}

From source file:models.PullRequest.java

License:Apache License

public PullRequestMergeResult attemptMerge() throws IOException, GitAPIException {
    // fetch the branch to merge
    String tempBranchToCheckConflict = fetchSourceTemporarilly();

    // merge/*from   w  w w .  j  a va 2  s .c o m*/
    Merger.MergeResult mergeResult = new Merger(toBranch, tempBranchToCheckConflict).merge();

    // Make a PullRequestMergeResult to return
    PullRequestMergeResult pullRequestMergeResult = new PullRequestMergeResult();
    pullRequestMergeResult.setPullRequest(this);
    if (mergeResult.conflicts()) {
        pullRequestMergeResult.setConflictStateOfPullRequest();
    } else {
        pullRequestMergeResult.setResolvedStateOfPullRequest();
    }
    pullRequestMergeResult.setGitCommits(GitRepository.diffCommits(getRepository(),
            mergeResult.getLeftParentId(), mergeResult.getRightParentId()));

    // Clean Up: Delete the temporary branch
    RefUpdate refUpdate = getRepository().updateRef(tempBranchToCheckConflict);
    refUpdate.setForceUpdate(true);
    refUpdate.delete();

    return pullRequestMergeResult;
}