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

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

113 Examples 7

19 View Complete Implementation : ProjectResetterTest.java
Copyright Apache License 2.0
Author : GerritCodeReview
private void replacedertRef(Repository repo, Ref ref) throws IOException {
    replacedertThat(repo.exactRef(ref.getName()).getObjectId()).isEqualTo(ref.getObjectId());
}

19 View Complete Implementation : RefUpdateUtilRepoTest.java
Copyright Apache License 2.0
Author : GerritCodeReview
@Test
public void deleteRefNoOp() throws Exception {
    String ref = "refs/heads/foo";
    replacedertThat(repo.exactRef(ref)).isNull();
    RefUpdateUtil.deleteChecked(repo, "refs/heads/foo");
    replacedertThat(repo.exactRef(ref)).isNull();
}

19 View Complete Implementation : ListBranches.java
Copyright Apache License 2.0
Author : gerrit-review
BranchInfo toBranchInfo(BranchResource rsrc) throws IOException, ResourceNotFoundException, PermissionBackendException {
    try (Repository db = repoManager.openRepository(rsrc.getNameKey())) {
        Ref r = db.exactRef(rsrc.getRef());
        if (r == null) {
            throw new ResourceNotFoundException();
        }
        return toBranchInfo(rsrc, ImmutableList.of(r)).get(0);
    } catch (RepositoryNotFoundException noRepo) {
        throw new ResourceNotFoundException();
    }
}

19 View Complete Implementation : ProjectResetterTest.java
Copyright Apache License 2.0
Author : GerritCodeReview
private void replacedertDeletedRef(Repository repo, Ref ref) throws IOException {
    replacedertThat(repo.exactRef(ref.getName())).isNull();
}

19 View Complete Implementation : GfsConfiguration.java
Copyright Apache License 2.0
Author : beijunyi
@Nonnull
public GfsConfiguration branch(String name) throws IOException {
    if (commit != null)
        throw new HeadAlreadyDefinedException();
    if (!branchExists(name, repo) && exists(name, repo))
        commit = getCommit(name, repo);
    else {
        branch = RefUtils.fullBranchName(name);
        Ref ref = repo.exactRef(branch);
        if (ref != null)
            commit = getCommit(ref, repo);
    }
    return this;
}

19 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());
    }
}

19 View Complete Implementation : DeleteBranchesIT.java
Copyright Apache License 2.0
Author : GerritCodeReview
private void replacedertBranchesDeleted(List<String> branches) throws Exception {
    try (Repository repo = repoManager.openRepository(project)) {
        for (String branch : branches) {
            replacedertThat(repo.exactRef(branch)).isNull();
        }
    }
}

19 View Complete Implementation : RefState.java
Copyright Apache License 2.0
Author : gerrit-review
public boolean match(Repository repo) throws IOException {
    Ref ref = repo.exactRef(ref());
    ObjectId expected = ref != null ? ref.getObjectId() : ObjectId.zeroId();
    return id().equals(expected);
}

19 View Complete Implementation : DefaultAccess.java
Copyright Apache License 2.0
Author : google
private RepositoryDescription buildDescription(Repository repo, Set<String> branches) throws IOException {
    RepositoryDescription desc = new RepositoryDescription();
    desc.name = getRepositoryName(repo);
    desc.cloneUrl = baseGitUrl + getRelativePath(repo);
    desc.description = loadDescriptionText(repo);
    if (!branches.isEmpty()) {
        desc.branches = Maps.newLinkedHashMap();
        for (String name : branches) {
            Ref ref = repo.exactRef(normalizeRefName(name));
            if ((ref != null) && (ref.getObjectId() != null)) {
                desc.branches.put(name, ref.getObjectId().name());
            }
        }
    }
    return desc;
}

19 View Complete Implementation : GetRefFromName.java
Copyright Apache License 2.0
Author : centic9
public static void main(String[] args) throws IOException {
    try (Repository repository = CookbookHelper.openJGitCookbookRepository()) {
        // the Ref holds an ObjectId for any type of object (tree, commit, blob, tree)
        Ref head = repository.exactRef("refs/heads/master");
        System.out.println("Ref of refs/heads/master: " + head + ": " + head.getName() + " - " + head.getObjectId().getName());
    }
}

19 View Complete Implementation : NoteDbChecker.java
Copyright Apache License 2.0
Author : gerrit-review
public void replacedertNoChangeRef(Project.NameKey project, Change.Id changeId) throws Exception {
    try (Repository repo = repoManager.openRepository(project)) {
        replacedertThat(repo.exactRef(RefNames.changeMetaRef(changeId))).isNull();
    }
}

19 View Complete Implementation : Schema_159_to_160_Test.java
Copyright Apache License 2.0
Author : gerrit-review
private ObjectId metaRef(Account.Id id) throws Exception {
    try (Repository repo = repoManager.openRepository(allUsersName)) {
        return repo.exactRef(RefNames.refsUsers(id)).getObjectId();
    }
}

18 View Complete Implementation : AccountConfig.java
Copyright Apache License 2.0
Author : GerritCodeReview
@Override
protected void onLoad() throws IOException, ConfigInvalidException {
    if (revision != null) {
        rw.reset();
        rw.markStart(revision);
        rw.sort(RevSort.REVERSE);
        Timestamp registeredOn = new Timestamp(rw.next().getCommitTime() * 1000L);
        Config accountConfig = readConfig(AccountProperties.ACCOUNT_CONFIG);
        loadedAccountProperties = Optional.of(new AccountProperties(accountId, registeredOn, accountConfig, revision));
        projecreplacedches = new Projecreplacedches(accountId, readConfig(Projecreplacedches.WATCH_CONFIG), this);
        preferences = new StoredPreferences(accountId, readConfig(StoredPreferences.PREFERENCES_CONFIG), StoredPreferences.readDefaultConfig(allUsersName, repo), this);
        projecreplacedches.parse();
        preferences.parse();
    } else {
        loadedAccountProperties = Optional.empty();
        projecreplacedches = new Projecreplacedches(accountId, new Config(), this);
        preferences = new StoredPreferences(accountId, new Config(), StoredPreferences.readDefaultConfig(allUsersName, repo), this);
    }
    Ref externalIdsRef = repo.exactRef(RefNames.REFS_EXTERNAL_IDS);
    externalIdsRev = Optional.ofNullable(externalIdsRef).map(Ref::getObjectId);
}

18 View Complete Implementation : IntBlob.java
Copyright Apache License 2.0
Author : GerritCodeReview
private static Optional<IntBlob> parse(Repository repo, String refName, ObjectReader or) throws IOException {
    Ref ref = repo.exactRef(refName);
    if (ref == null) {
        return Optional.empty();
    }
    ObjectId id = ref.getObjectId();
    ObjectLoader ol = or.open(id, OBJ_BLOB);
    if (ol.getType() != OBJ_BLOB) {
        // In theory this should be thrown by open but not all implementations may do it properly
        // (certainly InMemoryRepository doesn't).
        throw new IncorrectObjectTypeException(id, OBJ_BLOB);
    }
    String str = CharMatcher.whitespace().trimFrom(new String(ol.getCachedBytes(), UTF_8));
    Integer value = Ints.tryParse(str);
    if (value == null) {
        throw new StorageException("invalid value in " + refName + " blob at " + id.name());
    }
    return Optional.of(IntBlob.create(id, value));
}

18 View Complete Implementation : DeleteBranchesIT.java
Copyright Apache License 2.0
Author : GerritCodeReview
private void replacedertBranches(List<String> branches) throws Exception {
    List<String> expected = Lists.newArrayList("HEAD", RefNames.REFS_CONFIG, "refs/heads/master");
    expected.addAll(branches.stream().map(this::prefixRef).collect(toList()));
    try (Repository repo = repoManager.openRepository(project)) {
        for (String branch : expected) {
            replacedertThat(repo.exactRef(branch)).isNotNull();
        }
    }
}

18 View Complete Implementation : RefUpdateUtilRepoTest.java
Copyright Apache License 2.0
Author : GerritCodeReview
@Test
public void deleteRef() throws Exception {
    String ref = "refs/heads/foo";
    try (TestRepository<Repository> tr = new TestRepository<>(repo)) {
        tr.branch(ref).commit().create();
    }
    replacedertThat(repo.exactRef(ref)).isNotNull();
    RefUpdateUtil.deleteChecked(repo, "refs/heads/foo");
    replacedertThat(repo.exactRef(ref)).isNull();
}

18 View Complete Implementation : ExternalIdReader.java
Copyright Apache License 2.0
Author : gerrit-review
public static ObjectId readRevision(Repository repo) throws IOException {
    Ref ref = repo.exactRef(RefNames.REFS_EXTERNAL_IDS);
    return ref != null ? ref.getObjectId() : ObjectId.zeroId();
}

18 View Complete Implementation : CreateProjectIT.java
Copyright Apache License 2.0
Author : gerrit-review
private void replacedertHead(String projectName, String expectedRef) throws Exception {
    try (Repository repo = repoManager.openRepository(new Project.NameKey(projectName))) {
        replacedertThat(repo.exactRef(Constants.HEAD).getTarget().getName()).isEqualTo(expectedRef);
    }
}

18 View Complete Implementation : NoteDbOnlyIT.java
Copyright Apache License 2.0
Author : gerrit-review
private Optional<ObjectId> getRef(String name) throws Exception {
    try (Repository repo = repoManager.openRepository(project)) {
        return Optional.ofNullable(repo.exactRef(name)).map(Ref::getObjectId);
    }
}

17 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);
}

17 View Complete Implementation : BranchesCollection.java
Copyright Apache License 2.0
Author : gerrit-review
@Override
public BranchResource parse(ProjectResource parent, IdString id) throws ResourceNotFoundException, IOException, PermissionBackendException {
    Project.NameKey project = parent.getNameKey();
    try (Repository repo = repoManager.openRepository(project)) {
        Ref ref = repo.exactRef(RefNames.fullName(id.get()));
        if (ref == null) {
            throw new ResourceNotFoundException(id);
        }
        // ListBranches checks the target of a symbolic reference to determine access
        // rights on the symbolic reference itself. This check prevents seeing a hidden
        // branch simply because the symbolic reference name was visible.
        permissionBackend.user(user).project(project).ref(ref.isSymbolic() ? ref.getTarget().getName() : ref.getName()).check(RefPermission.READ);
        return new BranchResource(parent.getProjectState(), parent.getUser(), ref);
    } catch (AuthException notAllowed) {
        throw new ResourceNotFoundException(id);
    } catch (RepositoryNotFoundException noRepo) {
        throw new ResourceNotFoundException();
    }
}

17 View Complete Implementation : RepoSequenceTest.java
Copyright Apache License 2.0
Author : gerrit-review
private String readBlob(String sequenceName) throws Exception {
    String refName = RefNames.REFS_SEQUENCES + sequenceName;
    try (Repository repo = repoManager.openRepository(project);
        RevWalk rw = new RevWalk(repo)) {
        ObjectId id = repo.exactRef(refName).getObjectId();
        return new String(rw.getObjectReader().open(id).getCachedBytes(), UTF_8);
    }
}

17 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());
            }
        }
    }
}

17 View Complete Implementation : StalenessChecker.java
Copyright Apache License 2.0
Author : GerritCodeReview
private static StalenessCheckResult refsAreStale(GitRepositoryManager repoManager, Change.Id id, Project.NameKey project, SetMultimap<Project.NameKey, RefState> allStates, ListMultimap<Project.NameKey, RefStatePattern> allPatterns) {
    try (Repository repo = repoManager.openRepository(project)) {
        Set<RefState> states = allStates.get(project);
        for (RefState state : states) {
            if (!state.match(repo)) {
                return StalenessCheckResult.stale("Ref states don't match for doreplacedent %s (%s != %s)", id, state, repo.exactRef(state.ref()));
            }
        }
        for (RefStatePattern pattern : allPatterns.get(project)) {
            if (!pattern.match(repo, states)) {
                return StalenessCheckResult.stale("Ref patterns don't match for doreplacedent %s. Pattern: %s States: %s", id, pattern, states);
            }
        }
        return StalenessCheckResult.notStale();
    } catch (IOException e) {
        logger.atWarning().withCause(e).log("error checking staleness of %s in %s", id, project);
        return StalenessCheckResult.stale("Exceptions while processing doreplacedent %s", e.getMessage());
    }
}

17 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()));
        }
    }
}

17 View Complete Implementation : AllProjectsCreatorTestUtil.java
Copyright Apache License 2.0
Author : GerritCodeReview
// Loads the "project.config" from the All-Projects repo.
public static Config readAllProjectsConfig(GitRepositoryManager repoManager, AllProjectsName allProjectsName) throws IOException, ConfigInvalidException {
    try (Repository repo = repoManager.openRepository(allProjectsName)) {
        Ref configRef = repo.exactRef(RefNames.REFS_CONFIG);
        return new BlobBasedConfig(null, repo, configRef.getObjectId(), "project.config");
    }
}

17 View Complete Implementation : PushAccountIT.java
Copyright Apache License 2.0
Author : GerritCodeReview
@Test
public void cannotCreateNonUserBranchUnderRefsUsersWithAccessDatabaseCapability() throws Exception {
    projectOperations.allProjectsForUpdate().add(allowCapability(GlobalCapability.ACCESS_DATABASE).group(REGISTERED_USERS)).update();
    projectOperations.project(allUsers).forUpdate().add(allow(Permission.CREATE).ref(RefNames.REFS_USERS + "*").group(adminGroupUuid())).add(allow(Permission.PUSH).ref(RefNames.REFS_USERS + "*").group(adminGroupUuid())).update();
    String userRef = RefNames.REFS_USERS + "foo";
    TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers);
    PushOneCommit.Result r = pushFactory.create(admin.newIdent(), allUsersRepo).to(userRef);
    r.replacedertErrorStatus();
    replacedertThat(r.getMessage()).contains("Not allowed to create non-user branch under refs/users/.");
    try (Repository repo = repoManager.openRepository(allUsers)) {
        replacedertThat(repo.exactRef(userRef)).isNull();
    }
}

17 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;
    }
}

17 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);
    }
}

17 View Complete Implementation : CreateProjectIT.java
Copyright Apache License 2.0
Author : GerritCodeReview
private void replacedertHead(String projectName, String expectedRef) throws Exception {
    try (Repository repo = repoManager.openRepository(Project.nameKey(projectName))) {
        replacedertThat(repo.exactRef(Constants.HEAD).getTarget().getName()).isEqualTo(expectedRef);
    }
}

17 View Complete Implementation : AbstractGroupTest.java
Copyright Apache License 2.0
Author : GerritCodeReview
protected Timestamp getTipTimestamp(AccountGroup.UUID uuid) throws Exception {
    try (RevWalk rw = new RevWalk(allUsersRepo)) {
        Ref ref = allUsersRepo.exactRef(RefNames.refsGroups(uuid));
        return ref == null ? null : new Timestamp(rw.parseCommit(ref.getObjectId()).getAuthorIdent().getWhen().getTime());
    }
}

16 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;
}

16 View Complete Implementation : SubmitByFastForwardIT.java
Copyright Apache License 2.0
Author : gerrit-review
@Test
public void repairChangeStateAfterFailure() throws Exception {
    // In NoteDb-only mode, repo and meta updates are atomic (at least in InMemoryRepository).
    replacedume().that(notesMigration.disableChangeReviewDb()).isFalse();
    PushOneCommit.Result change = createChange("Change 1", "a.txt", "content");
    Change.Id id = change.getChange().getId();
    TestSubmitInput failInput = new TestSubmitInput();
    failInput.failAfterRefUpdates = true;
    submit(change.getChangeId(), failInput, ResourceConflictException.clreplaced, "Failing after ref updates");
    // Bad: ref advanced but change wasn't updated.
    PatchSet.Id psId = new PatchSet.Id(id, 1);
    ChangeInfo info = gApi.changes().id(id.get()).get();
    replacedertThat(info.status).isEqualTo(ChangeStatus.NEW);
    replacedertThat(info.revisions.get(info.currentRevision)._number).isEqualTo(1);
    ObjectId rev;
    try (Repository repo = repoManager.openRepository(project);
        RevWalk rw = new RevWalk(repo)) {
        rev = repo.exactRef(psId.toRefName()).getObjectId();
        replacedertThat(rev).isNotNull();
        replacedertThat(repo.exactRef("refs/heads/master").getObjectId()).isEqualTo(rev);
    }
    submit(change.getChangeId());
    // Change status was updated, and branch tip stayed the same.
    info = gApi.changes().id(id.get()).get();
    replacedertThat(info.status).isEqualTo(ChangeStatus.MERGED);
    replacedertThat(info.revisions.get(info.currentRevision)._number).isEqualTo(1);
    replacedertThat(Iterables.getLast(info.messages).message).isEqualTo("Change has been successfully merged by Administrator");
    try (Repository repo = repoManager.openRepository(project)) {
        replacedertThat(repo.exactRef("refs/heads/master").getObjectId()).isEqualTo(rev);
    }
    replacedertRefUpdatedEvents();
    replacedertChangeMergedEvents(change.getChangeId(), getRemoteHead().name());
}

16 View Complete Implementation : VersionedMetaDataTest.java
Copyright Apache License 2.0
Author : gerrit-review
private ImmutableList<String> log(MyMetaData d) throws Exception {
    try (RevWalk rw = new RevWalk(repo)) {
        Ref ref = repo.exactRef(d.getRefName());
        if (ref == null) {
            return ImmutableList.of();
        }
        rw.sort(RevSort.REVERSE);
        rw.setRetainBody(true);
        rw.markStart(rw.parseCommit(ref.getObjectId()));
        return Streams.stream(rw).map(RevCommit::getFullMessage).collect(toImmutableList());
    }
}

16 View Complete Implementation : RepoViewTest.java
Copyright Apache License 2.0
Author : gerrit-review
@Test
public void getRefsRescansWhenNotCaching() throws Exception {
    ObjectId oldMaster = repo.exactRef(MASTER).getObjectId();
    replacedertThat(view.getRefs(R_HEADS)).containsExactly("master", oldMaster);
    ObjectId newBranch = tr.branch(BRANCH).commit().create();
    replacedertThat(view.getRefs(R_HEADS)).containsExactly("master", oldMaster, "branch", newBranch);
}

16 View Complete Implementation : RepoViewTest.java
Copyright Apache License 2.0
Author : gerrit-review
@Test
public void getRefsOverwritesCachedValueWithCommand() throws Exception {
    ObjectId master1 = repo.exactRef(MASTER).getObjectId();
    replacedertThat(view.getRef(MASTER)).hasValue(master1);
    ObjectId master2 = tr.commit().create();
    view.getCommands().add(new ReceiveCommand(master1, master2, MASTER));
    replacedertThat(repo.exactRef(MASTER).getObjectId()).isEqualTo(master1);
    replacedertThat(view.getRef(MASTER)).hasValue(master2);
    replacedertThat(view.getRefs(R_HEADS)).containsExactly("master", master2);
    view.getCommands().add(new ReceiveCommand(master2, ObjectId.zeroId(), MASTER));
    replacedertThat(repo.exactRef(MASTER).getObjectId()).isEqualTo(master1);
    replacedertThat(view.getRef(MASTER)).isEmpty();
    replacedertThat(view.getRefs(R_HEADS)).isEmpty();
}

16 View Complete Implementation : RepoViewTest.java
Copyright Apache License 2.0
Author : gerrit-review
@Test
public void getRef() throws Exception {
    ObjectId oldMaster = repo.exactRef(MASTER).getObjectId();
    replacedertThat(repo.exactRef(MASTER).getObjectId()).isEqualTo(oldMaster);
    replacedertThat(repo.exactRef(BRANCH)).isNull();
    replacedertThat(view.getRef(MASTER)).hasValue(oldMaster);
    replacedertThat(view.getRef(BRANCH)).isEmpty();
    tr.branch(MASTER).commit().create();
    tr.branch(BRANCH).commit().create();
    replacedertThat(repo.exactRef(MASTER).getObjectId()).isNotEqualTo(oldMaster);
    replacedertThat(repo.exactRef(BRANCH)).isNotNull();
    replacedertThat(view.getRef(MASTER)).hasValue(oldMaster);
    replacedertThat(view.getRef(BRANCH)).isEmpty();
}

16 View Complete Implementation : RepoViewTest.java
Copyright Apache License 2.0
Author : gerrit-review
@Test
public void getRefsReflectsCommands() throws Exception {
    ObjectId master1 = repo.exactRef(MASTER).getObjectId();
    replacedertThat(view.getRefs(R_HEADS)).containsExactly("master", master1);
    ObjectId master2 = tr.commit().create();
    view.getCommands().add(new ReceiveCommand(master1, master2, MASTER));
    replacedertThat(repo.exactRef(MASTER).getObjectId()).isEqualTo(master1);
    replacedertThat(view.getRef(MASTER)).hasValue(master2);
    replacedertThat(view.getRefs(R_HEADS)).containsExactly("master", master2);
    view.getCommands().add(new ReceiveCommand(master2, ObjectId.zeroId(), MASTER));
    replacedertThat(repo.exactRef(MASTER).getObjectId()).isEqualTo(master1);
    replacedertThat(view.getRef(MASTER)).isEmpty();
    replacedertThat(view.getRefs(R_HEADS)).isEmpty();
}

16 View Complete Implementation : RepoViewTest.java
Copyright Apache License 2.0
Author : gerrit-review
@Test
public void getRefsUsesCachedValueMatchingGetRef() throws Exception {
    ObjectId master1 = repo.exactRef(MASTER).getObjectId();
    replacedertThat(view.getRefs(R_HEADS)).containsExactly("master", master1);
    replacedertThat(view.getRef(MASTER)).hasValue(master1);
    // Doesn't reflect new value for master.
    ObjectId master2 = tr.branch(MASTER).commit().create();
    replacedertThat(repo.exactRef(MASTER).getObjectId()).isEqualTo(master2);
    replacedertThat(view.getRefs(R_HEADS)).containsExactly("master", master1);
    // Branch wasn't previously cached, so does reflect new value.
    ObjectId branch1 = tr.branch(BRANCH).commit().create();
    replacedertThat(view.getRefs(R_HEADS)).containsExactly("master", master1, "branch", branch1);
    // Looking up branch causes it to be cached.
    replacedertThat(view.getRef(BRANCH)).hasValue(branch1);
    ObjectId branch2 = tr.branch(BRANCH).commit().create();
    replacedertThat(repo.exactRef(BRANCH).getObjectId()).isEqualTo(branch2);
    replacedertThat(view.getRefs(R_HEADS)).containsExactly("master", master1, "branch", branch1);
}

16 View Complete Implementation : CommitsCollection.java
Copyright Apache License 2.0
Author : GerritCodeReview
/**
 * @return true if {@code commit} is visible to the caller.
 */
public boolean canRead(ProjectState state, Repository repo, RevCommit commit) throws IOException {
    Project.NameKey project = state.getNameKey();
    if (indexes.getSearchIndex() == null) {
        // No index in slaves, fall back to scanning refs. We must inspect change refs too
        // as the commit might be a patchset of a not yet submitted change.
        return reachable.fromRefs(project, repo, commit, repo.getRefDatabase().getRefs());
    }
    // Check first if any patchset of any change references the commit in question. This is much
    // cheaper than ref visibility filtering and reachability computation.
    List<ChangeData> changes = retryHelper.changeIndexQuery("queryChangesByProjectCommitWithLimit1", q -> q.enforceVisibility(true).setLimit(1).byProjectCommit(project, commit)).call();
    if (!changes.isEmpty()) {
        return true;
    }
    // Maybe the commit was a merge commit of a change. Try to find promising candidates for
    // branches to check, by seeing if its parents were replacedociated to changes.
    Predicate<ChangeData> pred = Predicate.and(new ProjectPredicate(project.get()), Predicate.or(Arrays.stream(commit.getParents()).map(parent -> new CommitPredicate(parent.getId().getName())).collect(toImmutableList())));
    changes = retryHelper.changeIndexQuery("queryChangesByProjectCommit", q -> q.enforceVisibility(true).query(pred)).call();
    Set<Ref> branchesForCommitParents = new HashSet<>(changes.size());
    for (ChangeData cd : changes) {
        Ref ref = repo.exactRef(cd.change().getDest().branch());
        if (ref != null) {
            branchesForCommitParents.add(ref);
        }
    }
    if (reachable.fromRefs(project, repo, commit, branchesForCommitParents.stream().collect(Collectors.toList()))) {
        return true;
    }
    // If we have already checked change refs using the change index, spare any further checks for
    // changes.
    List<Ref> refs = repo.getRefDatabase().getRefs().stream().filter(r -> !r.getName().startsWith(RefNames.REFS_CHANGES)).collect(toImmutableList());
    return reachable.fromRefs(project, repo, commit, refs);
}

16 View Complete Implementation : StarredChangesUtil.java
Copyright Apache License 2.0
Author : GerritCodeReview
public ObjectId getObjectId(Account.Id accountId, Change.Id changeId) {
    try (Repository repo = repoManager.openRepository(allUsers)) {
        Ref ref = repo.exactRef(RefNames.refsStarredChanges(changeId, accountId));
        return ref != null ? ref.getObjectId() : ObjectId.zeroId();
    } catch (IOException e) {
        logger.atSevere().withCause(e).log("Getting star object ID for account %d on change %d failed", accountId.get(), changeId.get());
        return ObjectId.zeroId();
    }
}

16 View Complete Implementation : PushAccountIT.java
Copyright Apache License 2.0
Author : GerritCodeReview
@Test
public void cannotCreateUserBranch() throws Exception {
    projectOperations.project(allUsers).forUpdate().add(allow(Permission.CREATE).ref(RefNames.REFS_USERS + "*").group(adminGroupUuid())).add(allow(Permission.PUSH).ref(RefNames.REFS_USERS + "*").group(adminGroupUuid())).update();
    String userRef = RefNames.refsUsers(Account.id(seq.nextAccountId()));
    TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers);
    PushOneCommit.Result r = pushFactory.create(admin.newIdent(), allUsersRepo).to(userRef);
    r.replacedertErrorStatus();
    replacedertThat(r.getMessage()).contains("Not allowed to create user branch.");
    try (Repository repo = repoManager.openRepository(allUsers)) {
        replacedertThat(repo.exactRef(userRef)).isNull();
    }
}

16 View Complete Implementation : SubmitOnPushIT.java
Copyright Apache License 2.0
Author : GerritCodeReview
private void replacedertMergeCommit(String branch, String subject) throws Exception {
    try (Repository r = repoManager.openRepository(project);
        RevWalk rw = new RevWalk(r)) {
        RevCommit c = rw.parseCommit(r.exactRef(branch).getObjectId());
        replacedertThat(c.getParentCount()).isEqualTo(2);
        replacedertThat(c.getShortMessage()).isEqualTo("Merge \"" + subject + "\"");
        replacedertThat(c.getAuthorIdent().getEmailAddress()).isEqualTo(admin.email());
        replacedertThat(c.getCommitterIdent().getEmailAddress()).isEqualTo(serverIdent.get().getEmailAddress());
    }
}

16 View Complete Implementation : SubmitOnPushIT.java
Copyright Apache License 2.0
Author : GerritCodeReview
private void replacedertCommit(Project.NameKey project, String branch) throws Exception {
    try (Repository r = repoManager.openRepository(project);
        RevWalk rw = new RevWalk(r)) {
        RevCommit c = rw.parseCommit(r.exactRef(branch).getObjectId());
        replacedertThat(c.getShortMessage()).isEqualTo(PushOneCommit.SUBJECT);
        replacedertThat(c.getAuthorIdent().getEmailAddress()).isEqualTo(admin.email());
        replacedertThat(c.getCommitterIdent().getEmailAddress()).isEqualTo(admin.email());
    }
}

16 View Complete Implementation : GroupNameNotesTest.java
Copyright Apache License 2.0
Author : GerritCodeReview
@Test
public void firstGroupCreationCreatesARootCommit() throws Exception {
    createGroup(groupUuid, groupName);
    Ref ref = repo.exactRef(RefNames.REFS_GROUPNAMES);
    replacedertThat(ref.getObjectId()).isNotNull();
    try (RevWalk revWalk = new RevWalk(repo)) {
        RevCommit revCommit = revWalk.parseCommit(ref.getObjectId());
        replacedertThat(revCommit.getParentCount()).isEqualTo(0);
    }
}

16 View Complete Implementation : GroupNameNotesTest.java
Copyright Apache License 2.0
Author : GerritCodeReview
private String readNameNote(GroupReference g) throws Exception {
    ObjectId k = getNoteKey(g);
    try (RevWalk rw = new RevWalk(repo)) {
        ObjectReader reader = rw.getObjectReader();
        Ref ref = repo.exactRef(RefNames.REFS_GROUPNAMES);
        NoteMap noteMap = NoteMap.read(reader, rw.parseCommit(ref.getObjectId()));
        return new String(reader.open(noteMap.get(k), OBJ_BLOB).getCachedBytes(), UTF_8);
    }
}

15 View Complete Implementation : RepositoryS3.java
Copyright ISC License
Author : berlam
private RevTree getRevTree() throws IOException {
    Ref ref = repository.exactRef(branch.getFullRef());
    RevCommit commit = new RevWalk(repository).parseCommit(ref.getObjectId());
    return commit.getTree();
}

15 View Complete Implementation : WalkRev.java
Copyright Apache License 2.0
Author : centic9
public static void main(String[] args) throws IOException {
    try (Repository repository = CookbookHelper.openJGitCookbookRepository()) {
        Ref head = repository.exactRef("refs/heads/master");
        // a RevWalk allows to walk over commits based on some filtering that is defined
        try (RevWalk walk = new RevWalk(repository)) {
            RevCommit commit = walk.parseCommit(head.getObjectId());
            System.out.println("Start-Commit: " + commit);
            System.out.println("Walking all commits starting at HEAD");
            walk.markStart(commit);
            int count = 0;
            for (RevCommit rev : walk) {
                System.out.println("Commit: " + rev);
                count++;
            }
            System.out.println(count);
            walk.dispose();
        }
    }
}

15 View Complete Implementation : Rebase.java
Copyright Apache License 2.0
Author : gerrit-review
private ObjectId findBaseRev(Repository repo, RevWalk rw, RevisionResource rsrc, RebaseInput input) throws RestApiException, OrmException, IOException, NoSuchChangeException, AuthException, PermissionBackendException {
    Branch.NameKey destRefKey = rsrc.getChange().getDest();
    if (input == null || input.base == null) {
        return rebaseUtil.findBaseRevision(rsrc.getPatchSet(), destRefKey, repo, rw);
    }
    Change change = rsrc.getChange();
    String str = input.base.trim();
    if (str.equals("")) {
        // Remove existing dependency to other patch set.
        Ref destRef = repo.exactRef(destRefKey.get());
        if (destRef == null) {
            throw new ResourceConflictException("can't rebase onto tip of branch " + destRefKey.get() + "; branch doesn't exist");
        }
        return destRef.getObjectId();
    }
    Base base = rebaseUtil.parseBase(rsrc, str);
    if (base == null) {
        throw new ResourceConflictException("base revision is missing: " + str);
    }
    PatchSet.Id baseId = base.patchSet().getId();
    if (change.getId().equals(baseId.getParentKey())) {
        throw new ResourceConflictException("cannot rebase change onto itself");
    }
    permissionBackend.user(rsrc.getUser()).database(dbProvider).change(base.notes()).check(ChangePermission.READ);
    Change baseChange = base.notes().getChange();
    if (!baseChange.getProject().equals(change.getProject())) {
        throw new ResourceConflictException("base change is in wrong project: " + baseChange.getProject());
    } else if (!baseChange.getDest().equals(change.getDest())) {
        throw new ResourceConflictException("base change is targeting wrong branch: " + baseChange.getDest());
    } else if (baseChange.getStatus() == Status.ABANDONED) {
        throw new ResourceConflictException("base change is abandoned: " + baseChange.getKey());
    } else if (isMergedInto(rw, rsrc.getPatchSet(), base.patchSet())) {
        throw new ResourceConflictException("base change " + baseChange.getKey() + " is a descendant of the current change - recursion not allowed");
    }
    return ObjectId.fromString(base.patchSet().getRevision().get());
}

15 View Complete Implementation : GroupsIT.java
Copyright Apache License 2.0
Author : gerrit-review
@Test
@Sandboxed
public void cannotCreateGroupBranch() throws Exception {
    grant(allUsers, RefNames.REFS_GROUPS + "*", Permission.CREATE);
    grant(allUsers, RefNames.REFS_GROUPS + "*", Permission.PUSH);
    String groupRef = RefNames.refsGroups(new AccountGroup.UUID(name("foo")));
    TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers);
    PushOneCommit.Result r = pushFactory.create(db, admin.getIdent(), allUsersRepo).to(groupRef);
    r.replacedertErrorStatus();
    replacedertThat(r.getMessage()).contains("Not allowed to create group branch.");
    try (Repository repo = repoManager.openRepository(allUsers)) {
        replacedertThat(repo.exactRef(groupRef)).isNull();
    }
}