Search in sources :

Example 46 with RevWalk

use of org.eclipse.jgit.revwalk.RevWalk in project gerrit by GerritCodeReview.

the class ReceiveCommits method validateNewCommits.

private void validateNewCommits(RefControl ctl, ReceiveCommand cmd) {
    if (ctl.canForgeAuthor() && ctl.canForgeCommitter() && ctl.canForgeGerritServerIdentity() && ctl.canUploadMerges() && !projectControl.getProjectState().isUseSignedOffBy() && Iterables.isEmpty(rejectCommits) && !RefNames.REFS_CONFIG.equals(ctl.getRefName()) && !(MagicBranch.isMagicBranch(cmd.getRefName()) || NEW_PATCHSET.matcher(cmd.getRefName()).matches())) {
        logDebug("Short-circuiting new commit validation");
        return;
    }
    boolean defaultName = Strings.isNullOrEmpty(user.getAccount().getFullName());
    RevWalk walk = rp.getRevWalk();
    walk.reset();
    walk.sort(RevSort.NONE);
    try {
        RevObject parsedObject = walk.parseAny(cmd.getNewId());
        if (!(parsedObject instanceof RevCommit)) {
            return;
        }
        ListMultimap<ObjectId, Ref> existing = changeRefsById();
        walk.markStart((RevCommit) parsedObject);
        markHeadsAsUninteresting(walk, cmd.getRefName());
        int i = 0;
        for (RevCommit c; (c = walk.next()) != null; ) {
            i++;
            if (existing.keySet().contains(c)) {
                continue;
            } else if (!validCommit(walk, ctl, cmd, c)) {
                break;
            }
            if (defaultName && user.hasEmailAddress(c.getCommitterIdent().getEmailAddress())) {
                try {
                    Account a = db.accounts().get(user.getAccountId());
                    if (a != null && Strings.isNullOrEmpty(a.getFullName())) {
                        a.setFullName(c.getCommitterIdent().getName());
                        db.accounts().update(Collections.singleton(a));
                        user.getAccount().setFullName(a.getFullName());
                        accountCache.evict(a.getId());
                    }
                } catch (OrmException e) {
                    logWarn("Cannot default full_name", e);
                } finally {
                    defaultName = false;
                }
            }
        }
        logDebug("Validated {} new commits", i);
    } catch (IOException err) {
        cmd.setResult(REJECTED_MISSING_OBJECT);
        logError("Invalid pack upload; one or more objects weren't sent", err);
    }
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) Ref(org.eclipse.jgit.lib.Ref) RevObject(org.eclipse.jgit.revwalk.RevObject) ObjectId(org.eclipse.jgit.lib.ObjectId) OrmException(com.google.gwtorm.server.OrmException) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 47 with RevWalk

use of org.eclipse.jgit.revwalk.RevWalk in project gerrit by GerritCodeReview.

the class TagSet method prepare.

void prepare(TagMatcher m) {
    @SuppressWarnings("resource") RevWalk rw = null;
    try {
        for (Ref currentRef : m.include) {
            if (currentRef.isSymbolic()) {
                continue;
            }
            if (currentRef.getObjectId() == null) {
                continue;
            }
            CachedRef savedRef = refs.get(currentRef.getName());
            if (savedRef == null) {
                // If the reference isn't known to the set, return null
                // and force the caller to rebuild the set in a new copy.
                m.newRefs.add(currentRef);
                continue;
            }
            // The reference has not been moved. It can be used as-is.
            ObjectId savedObjectId = savedRef.get();
            if (currentRef.getObjectId().equals(savedObjectId)) {
                m.mask.set(savedRef.flag);
                continue;
            }
            // This is very likely for a branch that fast-forwarded.
            try {
                if (rw == null) {
                    rw = new RevWalk(m.db);
                    rw.setRetainBody(false);
                }
                RevCommit savedCommit = rw.parseCommit(savedObjectId);
                RevCommit currentCommit = rw.parseCommit(currentRef.getObjectId());
                if (rw.isMergedInto(savedCommit, currentCommit)) {
                    // Fast-forward. Safely update the reference in-place.
                    savedRef.compareAndSet(savedObjectId, currentRef.getObjectId());
                    m.mask.set(savedRef.flag);
                    continue;
                }
                // The branch rewound. Walk the list of commits removed from
                // the reference. If any matches to a tag, this has to be removed.
                boolean err = false;
                rw.reset();
                rw.markStart(savedCommit);
                rw.markUninteresting(currentCommit);
                rw.sort(RevSort.TOPO, true);
                RevCommit c;
                while ((c = rw.next()) != null) {
                    Tag tag = tags.get(c);
                    if (tag != null && tag.refFlags.get(savedRef.flag)) {
                        m.lostRefs.add(new TagMatcher.LostRef(tag, savedRef.flag));
                        err = true;
                    }
                }
                if (!err) {
                    // All of the tags are still reachable. Update in-place.
                    savedRef.compareAndSet(savedObjectId, currentRef.getObjectId());
                    m.mask.set(savedRef.flag);
                }
            } catch (IOException err) {
                // Defer a cache update until later. No conclusion can be made
                // based on an exception reading from the repository storage.
                log.warn("Error checking tags of " + projectName, err);
            }
        }
    } finally {
        if (rw != null) {
            rw.close();
        }
    }
}
Also used : Ref(org.eclipse.jgit.lib.Ref) ObjectId(org.eclipse.jgit.lib.ObjectId) AnyObjectId(org.eclipse.jgit.lib.AnyObjectId) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 48 with RevWalk

use of org.eclipse.jgit.revwalk.RevWalk in project gerrit by GerritCodeReview.

the class NotesBranchUtil method commitNotes.

private void commitNotes(NoteMap notes, String notesBranch, PersonIdent commitAuthor, String commitMessage) throws IOException, ConcurrentRefUpdateException {
    try {
        revWalk = new RevWalk(db);
        reader = db.newObjectReader();
        loadBase(notesBranch);
        if (overwrite) {
            addAllNotes(notes);
        } else {
            addNewNotes(notes);
        }
        if (base != null) {
            oursCommit = createCommit(ours, commitAuthor, commitMessage, baseCommit);
        } else {
            oursCommit = createCommit(ours, commitAuthor, commitMessage);
        }
        updateRef(notesBranch);
    } finally {
        revWalk.close();
        reader.close();
    }
}
Also used : RevWalk(org.eclipse.jgit.revwalk.RevWalk)

Example 49 with RevWalk

use of org.eclipse.jgit.revwalk.RevWalk in project gerrit by GerritCodeReview.

the class CreateTag method apply.

@Override
public TagInfo apply(ProjectResource resource, TagInput input) throws RestApiException, IOException, PermissionBackendException {
    if (input == null) {
        input = new TagInput();
    }
    if (input.ref != null && !ref.equals(input.ref)) {
        throw new BadRequestException("ref must match URL");
    }
    if (input.revision == null) {
        input.revision = Constants.HEAD;
    }
    ref = RefUtil.normalizeTagRef(ref);
    RefControl refControl = resource.getControl().controlForRef(ref);
    PermissionBackend.ForRef perm = permissionBackend.user(identifiedUser).project(resource.getNameKey()).ref(ref);
    try (Repository repo = repoManager.openRepository(resource.getNameKey())) {
        ObjectId revid = RefUtil.parseBaseRevision(repo, resource.getNameKey(), input.revision);
        RevWalk rw = RefUtil.verifyConnected(repo, revid);
        RevObject object = rw.parseAny(revid);
        rw.reset();
        boolean isAnnotated = Strings.emptyToNull(input.message) != null;
        boolean isSigned = isAnnotated && input.message.contains("-----BEGIN PGP SIGNATURE-----\n");
        if (isSigned) {
            throw new MethodNotAllowedException("Cannot create signed tag \"" + ref + "\"");
        } else if (isAnnotated && !refControl.canPerform(Permission.CREATE_TAG)) {
            throw new AuthException("Cannot create annotated tag \"" + ref + "\"");
        } else {
            perm.check(RefPermission.CREATE);
        }
        if (repo.getRefDatabase().exactRef(ref) != null) {
            throw new ResourceConflictException("tag \"" + ref + "\" already exists");
        }
        try (Git git = new Git(repo)) {
            TagCommand tag = git.tag().setObjectId(object).setName(ref.substring(R_TAGS.length())).setAnnotated(isAnnotated).setSigned(isSigned);
            if (isAnnotated) {
                tag.setMessage(input.message).setTagger(identifiedUser.get().newCommitterIdent(TimeUtil.nowTs(), TimeZone.getDefault()));
            }
            Ref result = tag.call();
            tagCache.updateFastForward(resource.getNameKey(), ref, ObjectId.zeroId(), result.getObjectId());
            referenceUpdated.fire(resource.getNameKey(), ref, ObjectId.zeroId(), result.getObjectId(), identifiedUser.get().getAccount());
            try (RevWalk w = new RevWalk(repo)) {
                return ListTags.createTagInfo(perm, result, w);
            }
        }
    } catch (InvalidRevisionException e) {
        throw new BadRequestException("Invalid base revision");
    } catch (GitAPIException e) {
        log.error("Cannot create tag \"" + ref + "\"", e);
        throw new IOException(e);
    }
}
Also used : MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) ObjectId(org.eclipse.jgit.lib.ObjectId) RevObject(org.eclipse.jgit.revwalk.RevObject) AuthException(com.google.gerrit.extensions.restapi.AuthException) TagInput(com.google.gerrit.extensions.api.projects.TagInput) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) TagCommand(org.eclipse.jgit.api.TagCommand) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Repository(org.eclipse.jgit.lib.Repository) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Ref(org.eclipse.jgit.lib.Ref) Git(org.eclipse.jgit.api.Git) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) InvalidRevisionException(com.google.gerrit.server.project.RefUtil.InvalidRevisionException)

Example 50 with RevWalk

use of org.eclipse.jgit.revwalk.RevWalk in project gerrit by GerritCodeReview.

the class CheckMergeability method apply.

@Override
public MergeableInfo apply(BranchResource resource) throws IOException, BadRequestException, ResourceNotFoundException {
    if (!(submitType.equals(SubmitType.MERGE_ALWAYS) || submitType.equals(SubmitType.MERGE_IF_NECESSARY))) {
        throw new BadRequestException("Submit type: " + submitType + " is not supported");
    }
    MergeableInfo result = new MergeableInfo();
    result.submitType = submitType;
    result.strategy = strategy;
    try (Repository git = gitManager.openRepository(resource.getNameKey());
        RevWalk rw = new RevWalk(git);
        ObjectInserter inserter = new InMemoryInserter(git)) {
        Merger m = MergeUtil.newMerger(inserter, git.getConfig(), strategy);
        Ref destRef = git.getRefDatabase().exactRef(resource.getRef());
        if (destRef == null) {
            throw new ResourceNotFoundException(resource.getRef());
        }
        RevCommit targetCommit = rw.parseCommit(destRef.getObjectId());
        RevCommit sourceCommit = MergeUtil.resolveCommit(git, rw, source);
        if (!resource.getControl().canReadCommit(db.get(), git, sourceCommit)) {
            throw new BadRequestException("do not have read permission for: " + source);
        }
        if (rw.isMergedInto(sourceCommit, targetCommit)) {
            result.mergeable = true;
            result.commitMerged = true;
            result.contentMerged = true;
            return result;
        }
        if (m.merge(false, targetCommit, sourceCommit)) {
            result.mergeable = true;
            result.commitMerged = false;
            result.contentMerged = m.getResultTreeId().equals(targetCommit.getTree());
        } else {
            result.mergeable = false;
            if (m instanceof ResolveMerger) {
                result.conflicts = ((ResolveMerger) m).getUnmergedPaths();
            }
        }
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(e.getMessage());
    }
    return result;
}
Also used : Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) Merger(org.eclipse.jgit.merge.Merger) ResolveMerger(org.eclipse.jgit.merge.ResolveMerger) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) MergeableInfo(com.google.gerrit.extensions.common.MergeableInfo) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) InMemoryInserter(com.google.gerrit.server.git.InMemoryInserter) RevWalk(org.eclipse.jgit.revwalk.RevWalk) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) ResolveMerger(org.eclipse.jgit.merge.ResolveMerger) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Aggregations

RevWalk (org.eclipse.jgit.revwalk.RevWalk)217 RevCommit (org.eclipse.jgit.revwalk.RevCommit)114 Repository (org.eclipse.jgit.lib.Repository)100 ObjectId (org.eclipse.jgit.lib.ObjectId)92 IOException (java.io.IOException)67 Ref (org.eclipse.jgit.lib.Ref)35 ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)33 Test (org.junit.Test)33 Change (com.google.gerrit.reviewdb.client.Change)31 ObjectReader (org.eclipse.jgit.lib.ObjectReader)30 ArrayList (java.util.ArrayList)25 PatchSet (com.google.gerrit.reviewdb.client.PatchSet)24 OrmException (com.google.gwtorm.server.OrmException)24 RevTree (org.eclipse.jgit.revwalk.RevTree)24 TreeWalk (org.eclipse.jgit.treewalk.TreeWalk)21 InMemoryRepository (org.eclipse.jgit.internal.storage.dfs.InMemoryRepository)16 IncorrectObjectTypeException (org.eclipse.jgit.errors.IncorrectObjectTypeException)15 BatchRefUpdate (org.eclipse.jgit.lib.BatchRefUpdate)15 PersonIdent (org.eclipse.jgit.lib.PersonIdent)15 Project (com.google.gerrit.reviewdb.client.Project)14