org.eclipse.jgit.lib.Repository.updateRef() - java examples

Here are the examples of the java api org.eclipse.jgit.lib.Repository.updateRef() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

75 Examples 7

19 View Complete Implementation : GitUtils.java
Copyright MIT License
Author : theonedev
public static RefUpdate getRefUpdate(Repository repository, String refName) {
    try {
        return repository.updateRef(refName);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

17 View Complete Implementation : GeneralPreferencesIT.java
Copyright Apache License 2.0
Author : gerrit-review
@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);
            replacedertThat(u.delete()).isEqualTo(RefUpdate.Result.FORCED);
        }
    }
    accountCache.evictAllNoReindex();
}

17 View Complete Implementation : JgitUtils.java
Copyright Eclipse Public License 1.0
Author : google
/**
 * Updates the given ref to the new commit.
 */
public static RefUpdate updateRef(Repository repo, ObjectId newObjectId, ObjectId expectedOldObjectId, String refName) throws IOException {
    RefUpdate refUpdate = repo.updateRef(refName);
    refUpdate.setNewObjectId(newObjectId);
    if (expectedOldObjectId == null) {
        refUpdate.setExpectedOldObjectId(ObjectId.zeroId());
    } else {
        refUpdate.setExpectedOldObjectId(expectedOldObjectId);
    }
    return refUpdate;
}

15 View Complete Implementation : RefUpdateUtil.java
Copyright Apache License 2.0
Author : GerritCodeReview
/**
 * Delete a single ref, throwing a checked exception on failure.
 *
 * <p>Does not require that the ref have any particular old value. Succeeds as a no-op if the ref
 * did not exist.
 *
 * @param repo repository.
 * @param refName ref name to delete.
 * @throws LockFailureException if a low-level lock failure (e.g. compare-and-swap failure)
 *     occurs.
 * @throws IOException if an error occurred.
 */
public static void deleteChecked(Repository repo, String refName) throws IOException {
    RefUpdate ru = repo.updateRef(refName);
    ru.setForceUpdate(true);
    ru.setCheckConflicting(false);
    switch(ru.delete()) {
        case FORCED:
            // Ref was deleted.
            return;
        case NEW:
            // Ref didn't exist (yes, really).
            return;
        case LOCK_FAILURE:
            throw new LockFailureException("Failed to delete " + refName + ": " + ru.getResult(), ru);
        // Not really failures, but should not be the result of a deletion, so the best option is to
        // throw.
        case NO_CHANGE:
        case FAST_FORWARD:
        case RENAMED:
        case NOT_ATTEMPTED:
        case IO_FAILURE:
        case REJECTED:
        case REJECTED_CURRENT_BRANCH:
        case REJECTED_MISSING_OBJECT:
        case REJECTED_OTHER_REASON:
        default:
            throw new GitUpdateFailureException("Failed to delete " + refName + ": " + ru.getResult(), ru);
    }
}

15 View Complete Implementation : ChangeEditUtil.java
Copyright Apache License 2.0
Author : gerrit-review
private static void deleteRef(Repository repo, ChangeEdit edit) throws IOException {
    String refName = edit.getRefName();
    RefUpdate ru = repo.updateRef(refName, true);
    ru.setExpectedOldObjectId(edit.getEditCommit());
    ru.setForceUpdate(true);
    RefUpdate.Result result = ru.delete();
    switch(result) {
        case FORCED:
        case NEW:
        case NO_CHANGE:
            break;
        case FAST_FORWARD:
        case IO_FAILURE:
        case LOCK_FAILURE:
        case NOT_ATTEMPTED:
        case REJECTED:
        case REJECTED_CURRENT_BRANCH:
        case RENAMED:
        case REJECTED_MISSING_OBJECT:
        case REJECTED_OTHER_REASON:
        default:
            throw new IOException(String.format("Failed to delete ref %s: %s", refName, result));
    }
}

15 View Complete Implementation : ChangeEditUtil.java
Copyright Apache License 2.0
Author : GerritCodeReview
private static void deleteRef(Repository repo, ChangeEdit edit) throws IOException {
    String refName = edit.getRefName();
    RefUpdate ru = repo.updateRef(refName, true);
    ru.setExpectedOldObjectId(edit.getEditCommit());
    ru.setForceUpdate(true);
    RefUpdate.Result result = ru.delete();
    switch(result) {
        case FORCED:
        case NEW:
        case NO_CHANGE:
            break;
        case LOCK_FAILURE:
            throw new LockFailureException(String.format("Failed to delete ref %s", refName), ru);
        case FAST_FORWARD:
        case IO_FAILURE:
        case NOT_ATTEMPTED:
        case REJECTED:
        case REJECTED_CURRENT_BRANCH:
        case RENAMED:
        case REJECTED_MISSING_OBJECT:
        case REJECTED_OTHER_REASON:
        default:
            throw new IOException(String.format("Failed to delete ref %s: %s", refName, result));
    }
}

14 View Complete Implementation : DeleteTagCommand.java
Copyright Apache License 2.0
Author : apache
@Override
protected void run() throws GitException {
    Repository repository = getRepository();
    Ref currentRef = repository.getTags().get(tagName);
    if (currentRef == null) {
        throw new GitException.MissingObjectException(tagName, GitObjectType.TAG);
    }
    String fullName = currentRef.getName();
    try {
        RefUpdate update = repository.updateRef(fullName);
        update.setRefLogMessage("tag deleted", false);
        update.setForceUpdate(true);
        Result deleteResult = update.delete();
        switch(deleteResult) {
            case IO_FAILURE:
            case LOCK_FAILURE:
            case REJECTED:
                throw new GitException.RefUpdateException("Cannot delete tag " + tagName, GitRefUpdateResult.valueOf(deleteResult.name()));
        }
    } catch (IOException ex) {
        throw new GitException(ex);
    }
}

13 View Complete Implementation : RefAdvertisementIT.java
Copyright Apache License 2.0
Author : gerrit-review
private void setUpChanges() throws Exception {
    gApi.projects().name(project.get()).branch("branch").create(new BranchInput());
    // First 2 changes are merged, which means the tags pointing to them are
    // visible.
    allow("refs/for/refs/heads/*", Permission.SUBMIT, admins);
    PushOneCommit.Result mr = pushFactory.create(db, admin.getIdent(), testRepo).to("refs/for/master%submit");
    mr.replacedertOkStatus();
    c1 = mr.getChange();
    r1 = changeRefPrefix(c1.getId());
    PushOneCommit.Result br = pushFactory.create(db, admin.getIdent(), testRepo).to("refs/for/branch%submit");
    br.replacedertOkStatus();
    c2 = br.getChange();
    r2 = changeRefPrefix(c2.getId());
    // Second 2 changes are unmerged.
    mr = pushFactory.create(db, admin.getIdent(), testRepo).to("refs/for/master");
    mr.replacedertOkStatus();
    c3 = mr.getChange();
    r3 = changeRefPrefix(c3.getId());
    br = pushFactory.create(db, admin.getIdent(), testRepo).to("refs/for/branch");
    br.replacedertOkStatus();
    c4 = br.getChange();
    r4 = changeRefPrefix(c4.getId());
    try (Repository repo = repoManager.openRepository(project)) {
        // master-tag -> master
        RefUpdate mtu = repo.updateRef("refs/tags/master-tag");
        mtu.setExpectedOldObjectId(ObjectId.zeroId());
        mtu.setNewObjectId(repo.exactRef("refs/heads/master").getObjectId());
        replacedertThat(mtu.update()).isEqualTo(RefUpdate.Result.NEW);
        // branch-tag -> branch
        RefUpdate btu = repo.updateRef("refs/tags/branch-tag");
        btu.setExpectedOldObjectId(ObjectId.zeroId());
        btu.setNewObjectId(repo.exactRef("refs/heads/branch").getObjectId());
        replacedertThat(btu.update()).isEqualTo(RefUpdate.Result.NEW);
    }
}

13 View Complete Implementation : GroupsConsistencyIT.java
Copyright Apache License 2.0
Author : GerritCodeReview
@Test
public void missingGroupNameRef() throws Exception {
    try (Repository repo = repoManager.openRepository(allUsers)) {
        RefUpdate ru = repo.updateRef(RefNames.REFS_GROUPNAMES);
        ru.setForceUpdate(true);
        RefUpdate.Result result = ru.delete();
        replacedertThat(result).isEqualTo(Result.FORCED);
    }
    replacedertError("refs/meta/group-names does not exist");
}

12 View Complete Implementation : AccessIT.java
Copyright Apache License 2.0
Author : GerritCodeReview
@Test
public void webLinkNoRefsMetaConfig() throws Exception {
    try (Repository repo = repoManager.openRepository(newProjectName);
        Registration registration = newFileHistoryWebLink()) {
        RefUpdate u = repo.updateRef(RefNames.REFS_CONFIG);
        u.setForceUpdate(true);
        replacedertThat(u.delete()).isEqualTo(Result.FORCED);
        // This should not crash.
        pApi().access();
    }
}

12 View Complete Implementation : VersionedMetaDataOnInit.java
Copyright Apache License 2.0
Author : gerrit-review
private void updateRef(Repository repo, PersonIdent ident, ObjectId newRevision, String refLogMsg) throws IOException {
    RefUpdate ru = repo.updateRef(getRefName());
    ru.setRefLogIdent(ident);
    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:
        case REJECTED_MISSING_OBJECT:
        case REJECTED_OTHER_REASON:
        default:
            throw new IOException("Failed to update " + getRefName() + " of " + project + ": " + r.name());
    }
}

12 View Complete Implementation : AllProjectsCreator.java
Copyright Apache License 2.0
Author : gerrit-review
public void create() throws IOException, ConfigInvalidException {
    try (Repository git = mgr.openRepository(allProjectsName)) {
        initAllProjects(git);
    } catch (RepositoryNotFoundException notFound) {
        // A repository may be missing if this project existed only to store
        // inheritable permissions. For example 'All-Projects'.
        try (Repository git = mgr.createRepository(allProjectsName)) {
            initAllProjects(git);
            RefUpdate u = git.updateRef(Constants.HEAD);
            u.link(RefNames.REFS_CONFIG);
        } catch (RepositoryNotFoundException err) {
            String name = allProjectsName.get();
            throw new IOException("Cannot create repository " + name, err);
        }
    }
}

12 View Complete Implementation : GeneralPreferencesIT.java
Copyright Apache License 2.0
Author : gerrit-review
@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);
            replacedertThat(u.delete()).isEqualTo(RefUpdate.Result.FORCED);
        }
    }
    accountCache.evictAllNoReindex();
}

12 View Complete Implementation : AllProjectsCreator.java
Copyright Apache License 2.0
Author : GerritCodeReview
public void create(AllProjectsInput input) throws IOException, ConfigInvalidException {
    try (Repository git = repositoryManager.openRepository(allProjectsName)) {
        initAllProjects(git, input);
    } catch (RepositoryNotFoundException notFound) {
        // A repository may be missing if this project existed only to store
        // inheritable permissions. For example 'All-Projects'.
        try (Repository git = repositoryManager.createRepository(allProjectsName)) {
            initAllProjects(git, input);
            RefUpdate u = git.updateRef(Constants.HEAD);
            u.link(RefNames.REFS_CONFIG);
        } catch (RepositoryNotFoundException err) {
            String name = allProjectsName.get();
            throw new IOException("Cannot create repository " + name, err);
        }
    }
}

12 View Complete Implementation : AllUsersCreator.java
Copyright Apache License 2.0
Author : GerritCodeReview
public void create() throws IOException, ConfigInvalidException {
    try (Repository git = mgr.openRepository(allUsersName)) {
        initAllUsers(git);
    } catch (RepositoryNotFoundException notFound) {
        try (Repository git = mgr.createRepository(allUsersName)) {
            initAllUsers(git);
            RefUpdate u = git.updateRef(Constants.HEAD);
            u.link(RefNames.REFS_CONFIG);
        } catch (RepositoryNotFoundException err) {
            String name = allUsersName.get();
            throw new IOException("Cannot create repository " + name, err);
        }
    }
}

12 View Complete Implementation : GroupsConsistencyIT.java
Copyright Apache License 2.0
Author : GerritCodeReview
@Test
public void missingGroupRef() throws Exception {
    try (Repository repo = repoManager.openRepository(allUsers)) {
        RefUpdate ru = repo.updateRef(RefNames.refsGroups(AccountGroup.uuid(g1.id)));
        ru.setForceUpdate(true);
        RefUpdate.Result result = ru.delete();
        replacedertThat(result).isEqualTo(Result.FORCED);
    }
    replacedertError("missing as group ref");
}

11 View Complete Implementation : GitPushEmbedded.java
Copyright GNU General Public License v2.0
Author : bozaro
@Override
public boolean push(@NotNull Repository repository, @NotNull ObjectId ReceiveId, @NotNull String branch, @NotNull User userInfo) throws SVNException, IOException {
    final RefUpdate refUpdate = repository.updateRef(branch);
    refUpdate.getOldObjectId();
    refUpdate.setNewObjectId(ReceiveId);
    runReceiveHook(repository, refUpdate, SVNErrorCode.REPOS_HOOK_FAILURE, "pre-receive", userInfo);
    runUpdateHook(repository, refUpdate, "update", userInfo);
    final RefUpdate.Result result = refUpdate.update();
    switch(result) {
        case REJECTED:
        case LOCK_FAILURE:
            return false;
        case NEW:
        case FAST_FORWARD:
            runReceiveHook(repository, refUpdate, SVNErrorCode.REPOS_POST_COMMIT_HOOK_FAILED, "post-receive", userInfo);
            return true;
        default:
            log.error("Unexpected push error: {}", result);
            throw new SVNException(SVNErrorMessage.create(SVNErrorCode.IO_WRITE_ERROR, result.name()));
    }
}

11 View Complete Implementation : CreateProject.java
Copyright Apache License 2.0
Author : gerrit-review
private ProjectState createProject(CreateProjectArgs args) throws BadRequestException, ResourceConflictException, IOException, ConfigInvalidException {
    final Project.NameKey nameKey = args.getProject();
    try {
        final String head = args.permissionsOnly ? RefNames.REFS_CONFIG : args.branch.get(0);
        try (Repository repo = repoManager.openRepository(nameKey)) {
            if (repo.getObjectDatabase().exists()) {
                throw new ResourceConflictException("project \"" + nameKey + "\" exists");
            }
        } catch (RepositoryNotFoundException e) {
        // It does not exist, safe to ignore.
        }
        try (Repository repo = repoManager.createRepository(nameKey)) {
            RefUpdate u = repo.updateRef(Constants.HEAD);
            u.disableRefLog();
            u.link(head);
            createProjectConfig(args);
            if (!args.permissionsOnly && args.createEmptyCommit) {
                createEmptyCommits(repo, nameKey, args.branch);
            }
            fire(nameKey, head);
            return projectCache.get(nameKey);
        }
    } catch (RepositoryCaseMismatchException e) {
        throw new ResourceConflictException("Cannot create " + nameKey.get() + " because the name is already occupied by another project." + " The other project has the same name, only spelled in a" + " different case.");
    } catch (RepositoryNotFoundException badName) {
        throw new BadRequestException("invalid project name: " + nameKey);
    } catch (ConfigInvalidException e) {
        String msg = "Cannot create " + nameKey;
        log.error(msg, e);
        throw e;
    }
}

11 View Complete Implementation : DeleteRef.java
Copyright Apache License 2.0
Author : gerrit-review
private void deleteSingleRef(Repository r) throws IOException, ResourceConflictException {
    String ref = refsToDelete.get(0);
    if (prefix != null && !ref.startsWith(prefix)) {
        ref = prefix + ref;
    }
    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:
        case REJECTED_MISSING_OBJECT:
        case REJECTED_OTHER_REASON:
        default:
            log.error("Cannot delete " + ref + ": " + result.name());
            throw new ResourceConflictException("cannot delete: " + result.name());
    }
}

11 View Complete Implementation : StarredChangesUtil.java
Copyright Apache License 2.0
Author : gerrit-review
private void deleteRef(Repository repo, String refName, ObjectId oldObjectId) throws IOException, OrmException {
    RefUpdate u = repo.updateRef(refName);
    u.setForceUpdate(true);
    u.setExpectedOldObjectId(oldObjectId);
    u.setRefLogIdent(serverIdent);
    u.setRefLogMessage("Unstar change", true);
    RefUpdate.Result result = u.delete();
    switch(result) {
        case FORCED:
            gitRefUpdated.fire(allUsers, u, null);
            return;
        case NEW:
        case NO_CHANGE:
        case FAST_FORWARD:
        case IO_FAILURE:
        case LOCK_FAILURE:
        case NOT_ATTEMPTED:
        case REJECTED:
        case REJECTED_CURRENT_BRANCH:
        case RENAMED:
        case REJECTED_MISSING_OBJECT:
        case REJECTED_OTHER_REASON:
        default:
            throw new OrmException(String.format("Delete star ref %s failed: %s", refName, result.name()));
    }
}

11 View Complete Implementation : RepoSequenceTest.java
Copyright Apache License 2.0
Author : gerrit-review
private ObjectId writeBlob(String sequenceName, String value) {
    String refName = RefNames.REFS_SEQUENCES + sequenceName;
    try (Repository repo = repoManager.openRepository(project);
        ObjectInserter ins = repo.newObjectInserter()) {
        ObjectId newId = ins.insert(OBJ_BLOB, value.getBytes(UTF_8));
        ins.flush();
        RefUpdate ru = repo.updateRef(refName);
        ru.setNewObjectId(newId);
        replacedertThat(ru.forceUpdate()).isAnyOf(RefUpdate.Result.NEW, RefUpdate.Result.FORCED);
        return newId;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

11 View Complete Implementation : ProjectCreator.java
Copyright Apache License 2.0
Author : GerritCodeReview
public ProjectState createProject(CreateProjectArgs args) throws BadRequestException, ResourceConflictException, IOException, ConfigInvalidException {
    final Project.NameKey nameKey = args.getProject();
    try {
        final String head = args.permissionsOnly ? RefNames.REFS_CONFIG : args.branch.get(0);
        try (Repository repo = repoManager.openRepository(nameKey)) {
            if (repo.getObjectDatabase().exists()) {
                throw new ResourceConflictException("project \"" + nameKey + "\" exists");
            }
        } catch (RepositoryNotFoundException e) {
        // It does not exist, safe to ignore.
        }
        try (Repository repo = repoManager.createRepository(nameKey)) {
            RefUpdate u = repo.updateRef(Constants.HEAD);
            u.disableRefLog();
            u.link(head);
            createProjectConfig(args);
            if (!args.permissionsOnly && args.createEmptyCommit) {
                createEmptyCommits(repo, nameKey, args.branch);
            }
            fire(nameKey, head);
            return projectCache.get(nameKey);
        }
    } catch (RepositoryCaseMismatchException e) {
        throw new ResourceConflictException("Cannot create " + nameKey.get() + " because the name is already occupied by another project." + " The other project has the same name, only spelled in a" + " different case.");
    } catch (RepositoryNotFoundException badName) {
        throw new BadRequestException("invalid project name: " + nameKey);
    } catch (ConfigInvalidException e) {
        String msg = "Cannot create " + nameKey;
        logger.atSevere().withCause(e).log(msg);
        throw e;
    }
}

11 View Complete Implementation : CheckAccessIT.java
Copyright Apache License 2.0
Author : GerritCodeReview
@Test
public void noBranches() throws Exception {
    try (Repository repo = repoManager.openRepository(normalProject)) {
        RefUpdate u = repo.updateRef(RefNames.REFS_HEADS + "master");
        u.setForceUpdate(true);
        replacedertThat(u.delete()).isEqualTo(Result.FORCED);
    }
    AccessCheckInput input = new AccessCheckInput();
    input.account = privilegedUser.email();
    AccessCheckInfo info = gApi.projects().name(normalProject.get()).checkAccess(input);
    replacedertThat(info.status).isEqualTo(200);
    replacedertThat(info.message).contains("no branches");
}

10 View Complete Implementation : UpdateRefCommand.java
Copyright Apache License 2.0
Author : apache
@Override
protected void run() throws GitException {
    Repository repository = getRepository();
    try {
        Ref ref = repository.findRef(refName);
        if (ref == null || ref.isSymbolic()) {
            // currently unable to update symbolic references
            result = GitRefUpdateResult.valueOf(RefUpdate.Result.NOT_ATTEMPTED.name());
            return;
        }
        Ref newRef = repository.findRef(revision);
        String name;
        if (newRef == null) {
            ObjectId id = repository.resolve(revision);
            newRef = new ObjectIdRef.Unpeeled(Ref.Storage.LOOSE, id.name(), id.copy());
            name = newRef.getName();
        } else {
            name = revision;
        }
        RefUpdate u = repository.updateRef(ref.getName());
        newRef = repository.peel(newRef);
        ObjectId srcObjectId = newRef.getPeeledObjectId();
        if (srcObjectId == null) {
            srcObjectId = newRef.getObjectId();
        }
        u.setNewObjectId(srcObjectId);
        // NOI18N
        u.setRefLogMessage("merge " + name + ": Fast-forward", false);
        u.update();
        result = GitRefUpdateResult.valueOf((u.getResult() == null ? RefUpdate.Result.NOT_ATTEMPTED : u.getResult()).name());
    } catch (IOException ex) {
        throw new GitException(ex);
    }
}

10 View Complete Implementation : GroupsIT.java
Copyright Apache License 2.0
Author : gerrit-review
private void createGroupBranch(Project.NameKey project, String ref) throws IOException {
    try (Repository r = repoManager.openRepository(project);
        ObjectInserter oi = r.newObjectInserter();
        RevWalk rw = new RevWalk(r)) {
        ObjectId emptyTree = oi.insert(Constants.OBJ_TREE, new byte[] {});
        PersonIdent ident = new PersonIdent(serverIdent.get(), TimeUtil.nowTs());
        CommitBuilder cb = new CommitBuilder();
        cb.setTreeId(emptyTree);
        cb.setCommitter(ident);
        cb.setAuthor(ident);
        cb.setMessage("Create group");
        ObjectId emptyCommit = oi.insert(cb);
        oi.flush();
        RefUpdate updateRef = r.updateRef(ref);
        updateRef.setExpectedOldObjectId(ObjectId.zeroId());
        updateRef.setNewObjectId(emptyCommit);
        replacedertThat(updateRef.update(rw)).isEqualTo(RefUpdate.Result.NEW);
    }
}

10 View Complete Implementation : ProjectResetterTest.java
Copyright Apache License 2.0
Author : GerritCodeReview
private Ref createRef(Repository repo, String ref) throws IOException {
    try (ObjectInserter oi = repo.newObjectInserter();
        RevWalk rw = new RevWalk(repo)) {
        ObjectId emptyCommit = createCommit(repo);
        RefUpdate updateRef = repo.updateRef(ref);
        updateRef.setExpectedOldObjectId(ObjectId.zeroId());
        updateRef.setNewObjectId(emptyCommit);
        replacedertThat(updateRef.update(rw)).isEqualTo(RefUpdate.Result.NEW);
        return repo.exactRef(ref);
    }
}

10 View Complete Implementation : JobsServlet.java
Copyright Apache License 2.0
Author : palantir
public static void updateProjectRef(ObjectId treeId, ObjectInserter objectInserter, Repository repository, CurrentUser currentUser) throws IOException, NoFilepatternException, GitAPIException {
    // Create a branch
    Ref gerritCiRef = repository.getRef("refs/meta/gerrit-ci");
    CommitBuilder commitBuilder = new CommitBuilder();
    commitBuilder.setTreeId(treeId);
    logger.info("treeId: " + treeId);
    if (gerritCiRef != null) {
        ObjectId prevCommit = gerritCiRef.getObjectId();
        logger.info("prevCommit: " + prevCommit);
        commitBuilder.setParentId(prevCommit);
    }
    // build commit
    logger.info("Adding git tree : " + treeId);
    commitBuilder.setMessage("Modify project build rules.");
    final IdentifiedUser iUser = (IdentifiedUser) currentUser;
    PersonIdent user = new PersonIdent(currentUser.getUserName(), iUser.getEmailAddresses().iterator().next());
    commitBuilder.setAuthor(user);
    commitBuilder.setCommitter(user);
    ObjectId commitId = objectInserter.insert(commitBuilder);
    objectInserter.flush();
    logger.info(" Making new commit: " + commitId);
    RefUpdate newRef = repository.updateRef("refs/meta/gerrit-ci");
    newRef.setNewObjectId(commitId);
    newRef.update();
    repository.close();
}

9 View Complete Implementation : ProjectConfigTest.java
Copyright Apache License 2.0
Author : gerrit-review
private void update(RevCommit rev) throws Exception {
    RefUpdate u = db.updateRef(RefNames.REFS_CONFIG);
    u.disableRefLog();
    u.setNewObjectId(rev);
    Result result = u.forceUpdate();
    replacedertWithMessage("Cannot update ref for test: " + result).that(result).isAnyOf(Result.FAST_FORWARD, Result.FORCED, Result.NEW, Result.NO_CHANGE);
}

9 View Complete Implementation : ChangeEditModifier.java
Copyright Apache License 2.0
Author : GerritCodeReview
private void updateReference(Project.NameKey projectName, Repository repository, String refName, ObjectId currentObjectId, ObjectId targetObjectId, Timestamp timestamp) throws IOException {
    RefUpdate ru = repository.updateRef(refName);
    ru.setExpectedOldObjectId(currentObjectId);
    ru.setNewObjectId(targetObjectId);
    ru.setRefLogIdent(getRefLogIdent(timestamp));
    ru.setRefLogMessage("inline edit (amend)", false);
    ru.setForceUpdate(true);
    try (RevWalk revWalk = new RevWalk(repository)) {
        RefUpdate.Result res = ru.update(revWalk);
        String message = "cannot update " + ru.getName() + " in " + projectName + ": " + res;
        if (res == RefUpdate.Result.LOCK_FAILURE) {
            throw new LockFailureException(message, ru);
        }
        if (res != RefUpdate.Result.NEW && res != RefUpdate.Result.FORCED) {
            throw new IOException(message);
        }
    }
}

9 View Complete Implementation : IntBlob.java
Copyright Apache License 2.0
Author : GerritCodeReview
public static RefUpdate tryStore(Repository repo, RevWalk rw, Project.NameKey projectName, String refName, @Nullable ObjectId oldId, int val, GitReferenceUpdated gitRefUpdated) throws IOException {
    ObjectId newId;
    try (ObjectInserter ins = repo.newObjectInserter()) {
        newId = ins.insert(OBJ_BLOB, Integer.toString(val).getBytes(UTF_8));
        ins.flush();
    }
    RefUpdate ru = repo.updateRef(refName);
    if (oldId != null) {
        ru.setExpectedOldObjectId(oldId);
    }
    ru.disableRefLog();
    ru.setNewObjectId(newId);
    // Required for non-commitish updates.
    ru.setForceUpdate(true);
    RefUpdate.Result result = ru.update(rw);
    if (refUpdated(result)) {
        gitRefUpdated.fire(projectName, ru, null);
    }
    return ru;
}

9 View Complete Implementation : ChangeEditModifier.java
Copyright Apache License 2.0
Author : gerrit-review
private void updateReference(Repository repository, String refName, ObjectId currentObjectId, ObjectId targetObjectId, Timestamp timestamp) throws IOException {
    RefUpdate ru = repository.updateRef(refName);
    ru.setExpectedOldObjectId(currentObjectId);
    ru.setNewObjectId(targetObjectId);
    ru.setRefLogIdent(getRefLogIdent(timestamp));
    ru.setRefLogMessage("inline edit (amend)", false);
    ru.setForceUpdate(true);
    try (RevWalk revWalk = new RevWalk(repository)) {
        RefUpdate.Result res = ru.update(revWalk);
        if (res != RefUpdate.Result.NEW && res != RefUpdate.Result.FORCED) {
            throw new IOException("cannot update " + ru.getName() + " in " + repository.getDirectory() + ": " + ru.getResult());
        }
    }
}

9 View Complete Implementation : RepoSequence.java
Copyright Apache License 2.0
Author : gerrit-review
private RefUpdate.Result store(Repository repo, RevWalk rw, @Nullable ObjectId oldId, int val) throws IOException {
    ObjectId newId;
    try (ObjectInserter ins = repo.newObjectInserter()) {
        newId = ins.insert(OBJ_BLOB, Integer.toString(val).getBytes(UTF_8));
        ins.flush();
    }
    RefUpdate ru = repo.updateRef(refName);
    if (oldId != null) {
        ru.setExpectedOldObjectId(oldId);
    }
    ru.disableRefLog();
    ru.setNewObjectId(newId);
    // Required for non-commitish updates.
    ru.setForceUpdate(true);
    RefUpdate.Result result = ru.update(rw);
    if (refUpdated(result)) {
        gitRefUpdated.fire(projectName, ru, null);
    }
    return result;
}

9 View Complete Implementation : DeleteRef.java
Copyright Apache License 2.0
Author : gerrit-review
private ReceiveCommand createDeleteCommand(ProjectResource project, Repository r, String refName) throws OrmException, IOException, ResourceConflictException, PermissionBackendException {
    Ref ref = r.getRefDatabase().getRef(refName);
    ReceiveCommand command;
    if (ref == null) {
        command = new ReceiveCommand(ObjectId.zeroId(), ObjectId.zeroId(), refName);
        command.setResult(Result.REJECTED_OTHER_REASON, "it doesn't exist or you do not have permission to delete it");
        return command;
    }
    command = new ReceiveCommand(ref.getObjectId(), ObjectId.zeroId(), ref.getName());
    try {
        permissionBackend.user(identifiedUser).project(project.getNameKey()).ref(refName).check(RefPermission.DELETE);
    } catch (AuthException denied) {
        command.setResult(Result.REJECTED_OTHER_REASON, "it doesn't exist or you do not have permission to delete it");
    }
    if (!refName.startsWith(R_TAGS)) {
        Branch.NameKey branchKey = new Branch.NameKey(project.getNameKey(), ref.getName());
        if (!queryProvider.get().setLimit(1).byBranchOpen(branchKey).isEmpty()) {
            command.setResult(Result.REJECTED_OTHER_REASON, "it has open changes");
        }
    }
    RefUpdate u = r.updateRef(refName);
    u.setForceUpdate(true);
    u.setExpectedOldObjectId(r.exactRef(refName).getObjectId());
    u.setNewObjectId(ObjectId.zeroId());
    refDeletionValidator.validateRefOperation(project.getName(), identifiedUser.get(), u);
    return command;
}

9 View Complete Implementation : StarredChangesUtil.java
Copyright Apache License 2.0
Author : gerrit-review
private void updateLabels(Repository repo, String refName, ObjectId oldObjectId, Collection<String> labels) throws IOException, OrmException, InvalidLabelsException {
    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);
        u.setRefLogMessage("Update star labels", true);
        RefUpdate.Result result = u.update(rw);
        switch(result) {
            case NEW:
            case FORCED:
            case NO_CHANGE:
            case FAST_FORWARD:
                gitRefUpdated.fire(allUsers, u, null);
                return;
            case IO_FAILURE:
            case LOCK_FAILURE:
            case NOT_ATTEMPTED:
            case REJECTED:
            case REJECTED_CURRENT_BRANCH:
            case RENAMED:
            case REJECTED_MISSING_OBJECT:
            case REJECTED_OTHER_REASON:
            default:
                throw new OrmException(String.format("Update star labels on ref %s failed: %s", refName, result.name()));
        }
    }
}

8 View Complete Implementation : ConsistencyChecker.java
Copyright Apache License 2.0
Author : GerritCodeReview
private void fixPatchSetRef(ProblemInfo p, PatchSet ps) {
    try {
        RefUpdate ru = repo.updateRef(ps.id().toRefName());
        ru.setForceUpdate(true);
        ru.setNewObjectId(ps.commitId());
        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;
            case IO_FAILURE:
            case LOCK_FAILURE:
            case NOT_ATTEMPTED:
            case REJECTED:
            case REJECTED_CURRENT_BRANCH:
            case RENAMED:
            case REJECTED_MISSING_OBJECT:
            case REJECTED_OTHER_REASON:
            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";
        logger.atWarning().withCause(e).log("%s %s", msg, ps.id().toRefName());
        p.status = Status.FIX_FAILED;
        p.outcome = msg;
    }
}

8 View Complete Implementation : ConsistencyCheckerIT.java
Copyright Apache License 2.0
Author : GerritCodeReview
private void deleteUserBranch(Account.Id accountId) throws IOException {
    try (Repository repo = repoManager.openRepository(allUsers)) {
        String refName = RefNames.refsUsers(accountId);
        Ref ref = repo.exactRef(refName);
        if (ref == null) {
            return;
        }
        RefUpdate ru = repo.updateRef(refName);
        ru.setExpectedOldObjectId(ref.getObjectId());
        ru.setNewObjectId(ObjectId.zeroId());
        ru.setForceUpdate(true);
        Result result = ru.delete();
        if (result != Result.FORCED) {
            throw new IOException(String.format("Failed to delete ref %s: %s", refName, result.name()));
        }
    }
}

8 View Complete Implementation : RepoMerger.java
Copyright Apache License 2.0
Author : robinst
private MergedRef mergeBranch(String branch) throws IOException {
    Map<SubtreeConfig, ObjectId> resolvedRefs = resolveRefs("refs/heads/original/", branch);
    Map<SubtreeConfig, RevCommit> parentCommits = new LinkedHashMap<>();
    try (RevWalk revWalk = new RevWalk(repository)) {
        for (SubtreeConfig config : subtreeConfigs) {
            ObjectId objectId = resolvedRefs.get(config);
            if (objectId != null) {
                RevCommit commit = revWalk.parseCommit(objectId);
                parentCommits.put(config, commit);
            }
        }
    }
    MergedRef mergedRef = getMergedRef("branch", branch, parentCommits.keySet());
    ObjectId mergeCommit = new SubtreeMerger(repository).createMergeCommit(parentCommits, mergedRef.getMessage());
    RefUpdate refUpdate = repository.updateRef("refs/heads/" + branch);
    refUpdate.setNewObjectId(mergeCommit);
    refUpdate.update();
    return mergedRef;
}

7 View Complete Implementation : ConsistencyChecker.java
Copyright Apache License 2.0
Author : gerrit-review
private void fixPatchSetRef(ProblemInfo p, PatchSet ps) {
    try {
        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;
            case IO_FAILURE:
            case LOCK_FAILURE:
            case NOT_ATTEMPTED:
            case REJECTED:
            case REJECTED_CURRENT_BRANCH:
            case RENAMED:
            case REJECTED_MISSING_OBJECT:
            case REJECTED_OTHER_REASON:
            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;
    }
}

7 View Complete Implementation : SetHead.java
Copyright Apache License 2.0
Author : gerrit-review
@Override
public String apply(ProjectResource rsrc, HeadInput input) throws AuthException, ResourceNotFoundException, BadRequestException, UnprocessableEnreplacedyException, IOException, PermissionBackendException {
    if (input == null || Strings.isNullOrEmpty(input.ref)) {
        throw new BadRequestException("ref required");
    }
    String ref = RefNames.fullName(input.ref);
    permissionBackend.user(rsrc.getUser()).project(rsrc.getNameKey()).ref(ref).check(RefPermission.SET_HEAD);
    try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) {
        Map<String, Ref> cur = repo.getRefDatabase().exactRef(Constants.HEAD, ref);
        if (!cur.containsKey(ref)) {
            throw new UnprocessableEnreplacedyException(String.format("Ref Not Found: %s", ref));
        }
        final String oldHead = cur.get(Constants.HEAD).getTarget().getName();
        final String newHead = ref;
        if (!oldHead.equals(newHead)) {
            final RefUpdate u = repo.updateRef(Constants.HEAD, true);
            u.setRefLogIdent(identifiedUser.get().newRefLogIdent());
            RefUpdate.Result res = u.link(newHead);
            switch(res) {
                case NO_CHANGE:
                case RENAMED:
                case FORCED:
                case NEW:
                    break;
                case FAST_FORWARD:
                case IO_FAILURE:
                case LOCK_FAILURE:
                case NOT_ATTEMPTED:
                case REJECTED:
                case REJECTED_CURRENT_BRANCH:
                case REJECTED_MISSING_OBJECT:
                case REJECTED_OTHER_REASON:
                default:
                    throw new IOException("Setting HEAD failed with " + res);
            }
            fire(rsrc.getNameKey(), oldHead, newHead);
        }
        return ref;
    } catch (RepositoryNotFoundException e) {
        throw new ResourceNotFoundException(rsrc.getName());
    }
}

7 View Complete Implementation : Schema_146.java
Copyright Apache License 2.0
Author : gerrit-review
public void createUserBranch(Repository repo, ObjectInserter oi, ObjectId emptyTree, Account.Id accountId, Timestamp registeredOn) throws IOException {
    ObjectId id = createInitialEmptyCommit(oi, emptyTree, registeredOn);
    String refName = RefNames.refsUsers(accountId);
    RefUpdate ru = repo.updateRef(refName);
    ru.setExpectedOldObjectId(ObjectId.zeroId());
    ru.setNewObjectId(id);
    ru.setRefLogIdent(serverIdent);
    ru.setRefLogMessage(CREATE_ACCOUNT_MSG, false);
    Result result = ru.update();
    if (result != Result.NEW) {
        throw new IOException(String.format("Failed to update ref %s: %s", refName, result.name()));
    }
}

7 View Complete Implementation : ProjectResetterTest.java
Copyright Apache License 2.0
Author : GerritCodeReview
private Ref updateRef(Repository repo, Ref ref) throws IOException {
    try (ObjectInserter oi = repo.newObjectInserter();
        RevWalk rw = new RevWalk(repo)) {
        ObjectId emptyCommit = createCommit(repo);
        RefUpdate updateRef = repo.updateRef(ref.getName());
        updateRef.setExpectedOldObjectId(ref.getObjectId());
        updateRef.setNewObjectId(emptyCommit);
        updateRef.setForceUpdate(true);
        replacedertThat(updateRef.update(rw)).isEqualTo(RefUpdate.Result.FORCED);
        Ref updatedRef = repo.exactRef(ref.getName());
        replacedertThat(updatedRef.getObjectId()).isNotEqualTo(ref.getObjectId());
        return updatedRef;
    }
}

6 View Complete Implementation : ProjectResetter.java
Copyright Apache License 2.0
Author : GerritCodeReview
private void restoreRefs() throws IOException {
    for (Map.Entry<Project.NameKey, Collection<RefState>> e : savedRefStatesByProject.asMap().entrySet()) {
        try (Repository repo = repoManager.openRepository(e.getKey())) {
            for (RefState refState : e.getValue()) {
                if (refState.match(repo)) {
                    keptRefsByProject.put(e.getKey(), refState.ref());
                    continue;
                }
                Ref ref = repo.exactRef(refState.ref());
                RefUpdate updateRef = repo.updateRef(refState.ref());
                updateRef.setExpectedOldObjectId(ref != null ? ref.getObjectId() : ObjectId.zeroId());
                updateRef.setNewObjectId(refState.id());
                updateRef.setForceUpdate(true);
                RefUpdate.Result result = updateRef.update();
                checkState(result == RefUpdate.Result.FORCED || result == RefUpdate.Result.NEW, "resetting branch %s in %s failed", refState.ref(), e.getKey());
                restoredRefsByProject.put(e.getKey(), refState.ref());
            }
        }
    }
}

6 View Complete Implementation : StarredChangesUtil.java
Copyright Apache License 2.0
Author : GerritCodeReview
private void deleteRef(Repository repo, String refName, ObjectId oldObjectId) throws IOException {
    if (ObjectId.zeroId().equals(oldObjectId)) {
        // ref doesn't exist
        return;
    }
    try (TraceTimer traceTimer = TraceContext.newTimer("Delete star labels", Metadata.builder().noteDbRefName(refName).build())) {
        RefUpdate u = repo.updateRef(refName);
        u.setForceUpdate(true);
        u.setExpectedOldObjectId(oldObjectId);
        u.setRefLogIdent(serverIdent.get());
        u.setRefLogMessage("Unstar change", true);
        RefUpdate.Result result = u.delete();
        switch(result) {
            case FORCED:
                gitRefUpdated.fire(allUsers, u, null);
                return;
            case LOCK_FAILURE:
                throw new LockFailureException(String.format("Delete star ref %s failed", refName), u);
            case NEW:
            case NO_CHANGE:
            case FAST_FORWARD:
            case IO_FAILURE:
            case NOT_ATTEMPTED:
            case REJECTED:
            case REJECTED_CURRENT_BRANCH:
            case RENAMED:
            case REJECTED_MISSING_OBJECT:
            case REJECTED_OTHER_REASON:
            default:
                throw new StorageException(String.format("Delete star ref %s failed: %s", refName, result.name()));
        }
    }
}

6 View Complete Implementation : RepoMerger.java
Copyright Apache License 2.0
Author : robinst
private void deleteOriginalRefs() throws IOException {
    try (RevWalk revWalk = new RevWalk(repository)) {
        Collection<Ref> refs = new ArrayList<>();
        RefDatabase refDatabase = repository.getRefDatabase();
        Map<String, Ref> originalBranches = refDatabase.getRefs("refs/heads/original/");
        Map<String, Ref> originalTags = refDatabase.getRefs("refs/tags/original/");
        refs.addAll(originalBranches.values());
        refs.addAll(originalTags.values());
        for (Ref originalRef : refs) {
            RefUpdate refUpdate = repository.updateRef(originalRef.getName());
            refUpdate.setForceUpdate(true);
            refUpdate.delete(revWalk);
        }
    }
}

5 View Complete Implementation : CheckoutRevisionCommand.java
Copyright Apache License 2.0
Author : apache
@Override
protected void run() throws GitException {
    Repository repository = getRepository();
    try {
        Ref headRef = repository.findRef(Constants.HEAD);
        if (headRef == null) {
            throw new GitException("Corrupted repository, missing HEAD file in .git folder.");
        }
        ObjectId headTree = null;
        try {
            headTree = Utils.findCommit(repository, Constants.HEAD).getTree();
        } catch (GitException.MissingObjectException ex) {
        }
        Ref ref = repository.findRef(revision);
        if (ref != null && !ref.getName().startsWith(Constants.R_HEADS) && !ref.getName().startsWith(Constants.R_REMOTES)) {
            ref = null;
        }
        String fromName = headRef.getTarget().getName();
        if (fromName.startsWith(Constants.R_HEADS)) {
            fromName = fromName.substring(Constants.R_HEADS.length());
        }
        // NOI18N
        String refLogMessage = "checkout: moving from " + fromName;
        cache = repository.lockDirCache();
        DirCacheCheckout dco = null;
        RevCommit commit = null;
        try {
            commit = Utils.findCommit(repository, revision);
            dco = headTree == null ? new DirCacheCheckout(repository, cache, commit.getTree()) : new DirCacheCheckout(repository, headTree, cache, commit.getTree());
            // JGit WA
            if (!failOnConflict) {
                dco.preScanTwoTrees();
                cacheContents(dco.getConflicts());
                dco = headTree == null ? new DirCacheCheckout(repository, cache, commit.getTree()) : new DirCacheCheckout(repository, headTree, cache, commit.getTree());
            }
            // End of JGit WA
            dco.setFailOnConflict(failOnConflict);
            dco.checkout();
            cache.lock();
            File workDir = repository.getWorkTree();
            notify(workDir, dco.getRemoved());
            notify(workDir, dco.getConflicts());
            notify(workDir, dco.getUpdated().keySet());
            // JGit WA
            if (!failOnConflict && dco.getConflicts().size() > 0) {
                mergeConflicts(dco.getConflicts(), cache);
            }
        // End of JGit WA
        } catch (org.eclipse.jgit.dircache.InvalidPathException ex) {
            throw new GitException("Commit " + commit.name() + " cannot be checked out because an invalid file name in one of the files.\n" + "Please remove the file from repository with an external tool and try again.\n\n" + ex.getMessage());
        } catch (CheckoutConflictException ex) {
            List<String> conflicts = dco.getConflicts();
            throw new GitException.CheckoutConflictException(conflicts.toArray(new String[conflicts.size()]), ex);
        } finally {
            cache.unlock();
        }
        if (!monitor.isCanceled()) {
            String toName;
            boolean detach = true;
            if (ref == null) {
                toName = commit.getName();
            } else {
                toName = ref.getName();
                if (toName.startsWith(Constants.R_HEADS)) {
                    detach = false;
                    toName = toName.substring(Constants.R_HEADS.length());
                } else if (toName.startsWith(Constants.R_REMOTES)) {
                    toName = toName.substring(Constants.R_REMOTES.length());
                }
            }
            RefUpdate refUpdate = repository.updateRef(Constants.HEAD, detach);
            refUpdate.setForceUpdate(false);
            // NOI18N
            refUpdate.setRefLogMessage(refLogMessage + " to " + toName, false);
            RefUpdate.Result updateResult;
            if (!detach)
                updateResult = refUpdate.link(ref.getName());
            else {
                refUpdate.setNewObjectId(commit);
                updateResult = refUpdate.forceUpdate();
            }
            boolean ok = false;
            switch(updateResult) {
                case NEW:
                    ok = true;
                    break;
                case NO_CHANGE:
                case FAST_FORWARD:
                case FORCED:
                    ok = true;
                    break;
                default:
                    break;
            }
            if (!ok) {
                throw new GitException("Unexpected result: " + updateResult.name());
            }
        }
    } catch (IOException ex) {
        throw new GitException(ex);
    }
}

5 View Complete Implementation : ProjectResetter.java
Copyright Apache License 2.0
Author : GerritCodeReview
private void deleteNewlyCreatedRefs() throws IOException {
    for (Map.Entry<Project.NameKey, Collection<String>> e : refsPatternByProject.asMap().entrySet()) {
        try (Repository repo = repoManager.openRepository(e.getKey())) {
            Collection<Ref> nonRestoredRefs = repo.getRefDatabase().getRefs().stream().filter(r -> !keptRefsByProject.containsEntry(e.getKey(), r.getName()) && !restoredRefsByProject.containsEntry(e.getKey(), r.getName())).collect(toSet());
            for (String refPattern : e.getValue()) {
                RefPatternMatcher matcher = RefPatternMatcher.getMatcher(refPattern);
                for (Ref ref : nonRestoredRefs) {
                    if (matcher.match(ref.getName(), null) && !deletedRefsByProject.containsEntry(e.getKey(), ref.getName())) {
                        RefUpdate updateRef = repo.updateRef(ref.getName());
                        updateRef.setExpectedOldObjectId(ref.getObjectId());
                        updateRef.setNewObjectId(ObjectId.zeroId());
                        updateRef.setForceUpdate(true);
                        RefUpdate.Result result = updateRef.delete();
                        checkState(result == RefUpdate.Result.FORCED, "deleting branch %s in %s failed", ref.getName(), e.getKey());
                        deletedRefsByProject.put(e.getKey(), ref.getName());
                    }
                }
            }
        }
    }
}

5 View Complete Implementation : StarredChangesUtil.java
Copyright Apache License 2.0
Author : GerritCodeReview
private void updateLabels(Repository repo, String refName, ObjectId oldObjectId, Collection<String> labels) throws IOException, InvalidLabelsException {
    try (TraceTimer traceTimer = TraceContext.newTimer("Update star labels", Metadata.builder().noteDbRefName(refName).resourceCount(labels.size()).build());
        RevWalk rw = new RevWalk(repo)) {
        RefUpdate u = repo.updateRef(refName);
        u.setExpectedOldObjectId(oldObjectId);
        u.setForceUpdate(true);
        u.setNewObjectId(writeLabels(repo, labels));
        u.setRefLogIdent(serverIdent.get());
        u.setRefLogMessage("Update star labels", true);
        RefUpdate.Result result = u.update(rw);
        switch(result) {
            case NEW:
            case FORCED:
            case NO_CHANGE:
            case FAST_FORWARD:
                gitRefUpdated.fire(allUsers, u, null);
                return;
            case LOCK_FAILURE:
                throw new LockFailureException(String.format("Update star labels on ref %s failed", refName), u);
            case IO_FAILURE:
            case NOT_ATTEMPTED:
            case REJECTED:
            case REJECTED_CURRENT_BRANCH:
            case RENAMED:
            case REJECTED_MISSING_OBJECT:
            case REJECTED_OTHER_REASON:
            default:
                throw new StorageException(String.format("Update star labels on ref %s failed: %s", refName, result.name()));
        }
    }
}

5 View Complete Implementation : GitUtils.java
Copyright MIT License
Author : jenkinsci
// TODO - remove once https://github.com/spotbugs/spotbugs/issues/756 is resolved
@SuppressFBWarnings(value = { "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE" }, justification = "JDK11 produces different bytecode - https://github.com/spotbugs/spotbugs/issues/756")
public static void commit(final Repository repo, final String refName, final String path, final byte[] contents, final String name, final String email, final String message, final TimeZone timeZone, final Date when) {
    final PersonIdent author = buildPersonIdent(repo, name, email, timeZone, when);
    try (final ObjectInserter odi = repo.newObjectInserter()) {
        // Create the in-memory index of the new/updated issue.
        final ObjectId headId = repo.resolve(refName + "^{commit}");
        final DirCache index = createTemporaryIndex(repo, headId, path, contents);
        final ObjectId indexTreeId = index.writeTree(odi);
        // Create a commit object
        final CommitBuilder commit = new CommitBuilder();
        commit.setAuthor(author);
        commit.setCommitter(author);
        commit.setEncoding(Constants.CHARACTER_ENCODING);
        commit.setMessage(message);
        // headId can be null if the repository has no commit yet
        if (headId != null) {
            commit.setParentId(headId);
        }
        commit.setTreeId(indexTreeId);
        // Insert the commit into the repository
        final ObjectId commitId = odi.insert(commit);
        odi.flush();
        try (RevWalk revWalk = new RevWalk(repo)) {
            final RevCommit revCommit = revWalk.parseCommit(commitId);
            final RefUpdate ru = repo.updateRef(refName);
            if (headId == null) {
                ru.setExpectedOldObjectId(ObjectId.zeroId());
            } else {
                ru.setExpectedOldObjectId(headId);
            }
            ru.setNewObjectId(commitId);
            ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
            final RefUpdate.Result rc = ru.forceUpdate();
            switch(rc) {
                case NEW:
                case FORCED:
                case FAST_FORWARD:
                    break;
                case REJECTED:
                case LOCK_FAILURE:
                    throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
                default:
                    throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, Constants.HEAD, commitId.toString(), rc));
            }
        }
    } catch (ConcurrentRefUpdateException | IOException | JGitInternalException ex) {
        throw new RuntimeException(ex);
    }
}

4 View Complete Implementation : AccountsUpdate.java
Copyright Apache License 2.0
Author : gerrit-review
public static void deleteUserBranch(Repository repo, Project.NameKey project, GitReferenceUpdated gitRefUpdated, @Nullable IdentifiedUser user, PersonIdent refLogIdent, Account.Id accountId) throws IOException {
    String refName = RefNames.refsUsers(accountId);
    Ref ref = repo.exactRef(refName);
    if (ref == null) {
        return;
    }
    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()));
    }
    gitRefUpdated.fire(project, ru, user != null ? user.getAccount() : null);
}

4 View Complete Implementation : DeleteRef.java
Copyright Apache License 2.0
Author : GerritCodeReview
/**
 * Deletes a single ref from the repository.
 *
 * @param projectState the {@code ProjectState} of the project containing the target ref.
 * @param ref the ref to be deleted.
 * @param prefix the prefix of the ref.
 * @throws IOException
 * @throws ResourceConflictException
 */
public void deleteSingleRef(ProjectState projectState, String ref, @Nullable String prefix) throws IOException, ResourceConflictException, AuthException, PermissionBackendException {
    if (prefix != null && !ref.startsWith(R_REFS)) {
        ref = prefix + ref;
    }
    projectState.checkStatePermitsWrite();
    permissionBackend.currentUser().project(projectState.getNameKey()).ref(ref).check(RefPermission.DELETE);
    try (Repository repository = repoManager.openRepository(projectState.getNameKey())) {
        RefUpdate.Result result;
        RefUpdate u = repository.updateRef(ref);
        u.setExpectedOldObjectId(repository.exactRef(ref).getObjectId());
        u.setNewObjectId(ObjectId.zeroId());
        u.setForceUpdate(true);
        refDeletionValidator.validateRefOperation(projectState.getName(), identifiedUser.get(), u);
        result = u.delete();
        switch(result) {
            case NEW:
            case NO_CHANGE:
            case FAST_FORWARD:
            case FORCED:
                referenceUpdated.fire(projectState.getNameKey(), u, ReceiveCommand.Type.DELETE, identifiedUser.get().state());
                break;
            case REJECTED_CURRENT_BRANCH:
                logger.atFine().log("Cannot delete current branch %s: %s", ref, result.name());
                throw new ResourceConflictException("cannot delete current branch");
            case LOCK_FAILURE:
                throw new LockFailureException(String.format("Cannot delete %s", ref), u);
            case IO_FAILURE:
            case NOT_ATTEMPTED:
            case REJECTED:
            case RENAMED:
            case REJECTED_MISSING_OBJECT:
            case REJECTED_OTHER_REASON:
            default:
                throw new StorageException(String.format("Cannot delete %s: %s", ref, result.name()));
        }
    }
}