Search in sources :

Example 21 with MissingObjectException

use of org.eclipse.jgit.errors.MissingObjectException in project gerrit by GerritCodeReview.

the class CommentContextLoader method getContext.

/**
 * Load the comment context for multiple contextInputs at once. This method will open the
 * repository and read the source files for all necessary contextInputs' file paths.
 *
 * @param contextInputs a list of contextInputs.
 * @return a Map where all entries consist of the input contextInputs and the values are their
 *     corresponding {@link CommentContext}.
 */
public Map<ContextInput, CommentContext> getContext(Collection<ContextInput> contextInputs) throws IOException {
    ImmutableMap.Builder<ContextInput, CommentContext> result = ImmutableMap.builderWithExpectedSize(Iterables.size(contextInputs));
    // Group contextInputs by commit ID so that each commit is parsed only once
    Map<ObjectId, List<ContextInput>> commentsByCommitId = contextInputs.stream().collect(groupingBy(ContextInput::commitId));
    try (Repository repo = repoManager.openRepository(project);
        RevWalk rw = new RevWalk(repo)) {
        for (ObjectId commitId : commentsByCommitId.keySet()) {
            RevCommit commit;
            try {
                commit = rw.parseCommit(commitId);
            } catch (IncorrectObjectTypeException | MissingObjectException e) {
                logger.atWarning().log("Commit %s is missing or has an incorrect object type", commitId);
                commentsByCommitId.get(commitId).forEach(contextInput -> result.put(contextInput, CommentContext.empty()));
                continue;
            }
            for (ContextInput contextInput : commentsByCommitId.get(commitId)) {
                Optional<Range> range = getStartAndEndLines(contextInput);
                if (!range.isPresent()) {
                    result.put(contextInput, CommentContext.empty());
                    continue;
                }
                String filePath = contextInput.filePath();
                switch(filePath) {
                    case COMMIT_MSG:
                        result.put(contextInput, getContextForCommitMessage(rw.getObjectReader(), commit, range.get(), contextInput.contextPadding()));
                        break;
                    case MERGE_LIST:
                        result.put(contextInput, getContextForMergeList(rw.getObjectReader(), commit, range.get(), contextInput.contextPadding()));
                        break;
                    default:
                        result.put(contextInput, getContextForFilePath(repo, rw, commit, filePath, range.get(), contextInput.contextPadding()));
                }
            }
        }
        return result.build();
    }
}
Also used : Iterables(com.google.common.collect.Iterables) ComparisonType(com.google.gerrit.server.patch.ComparisonType) RevCommit(org.eclipse.jgit.revwalk.RevCommit) ProjectCache(com.google.gerrit.server.project.ProjectCache) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) SrcContentResolver(com.google.gerrit.server.patch.SrcContentResolver) Inject(com.google.inject.Inject) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) MERGE_LIST(com.google.gerrit.entities.Patch.MERGE_LIST) Comment(com.google.gerrit.entities.Comment) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException) MimeType(eu.medsea.mimeutil.MimeType) Assisted(com.google.inject.assistedinject.Assisted) RevWalk(org.eclipse.jgit.revwalk.RevWalk) PatchScript(com.google.gerrit.common.data.PatchScript) ContextLineInfo(com.google.gerrit.extensions.common.ContextLineInfo) FileContentUtil(com.google.gerrit.server.change.FileContentUtil) Map(java.util.Map) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) ProjectCache.illegalState(com.google.gerrit.server.project.ProjectCache.illegalState) ImmutableMap(com.google.common.collect.ImmutableMap) Text(com.google.gerrit.server.patch.Text) Collection(java.util.Collection) FileTypeRegistry(com.google.gerrit.server.mime.FileTypeRegistry) ProjectState(com.google.gerrit.server.project.ProjectState) IOException(java.io.IOException) CommentContext(com.google.gerrit.entities.CommentContext) COMMIT_MSG(com.google.gerrit.entities.Patch.COMMIT_MSG) ObjectId(org.eclipse.jgit.lib.ObjectId) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) GitRepositoryManager(com.google.gerrit.server.git.GitRepositoryManager) AutoValue(com.google.auto.value.AutoValue) Project(com.google.gerrit.entities.Project) Optional(java.util.Optional) MimeUtil2(eu.medsea.mimeutil.MimeUtil2) ObjectReader(org.eclipse.jgit.lib.ObjectReader) FluentLogger(com.google.common.flogger.FluentLogger) Repository(org.eclipse.jgit.lib.Repository) ObjectId(org.eclipse.jgit.lib.ObjectId) CommentContext(com.google.gerrit.entities.CommentContext) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) ImmutableMap(com.google.common.collect.ImmutableMap) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException) Repository(org.eclipse.jgit.lib.Repository) List(java.util.List) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 22 with MissingObjectException

use of org.eclipse.jgit.errors.MissingObjectException in project gerrit by GerritCodeReview.

the class Reachable method fromRefs.

boolean fromRefs(Project.NameKey project, Repository repo, RevCommit commit, List<Ref> refs, Optional<CurrentUser> optionalUserProvider) {
    try (RevWalk rw = new RevWalk(repo)) {
        Collection<Ref> filtered = optionalUserProvider.map(permissionBackend::user).orElse(permissionBackend.currentUser()).project(project).filter(refs, repo, RefFilterOptions.defaults());
        Collection<RevCommit> visible = new ArrayList<>();
        for (Ref r : filtered) {
            try {
                visible.add(rw.parseCommit(r.getObjectId()));
            } catch (IncorrectObjectTypeException notCommit) {
                // is common in the Linux kernel or git.git repository.
                continue;
            } catch (MissingObjectException notHere) {
                // Log the problem with this branch, but keep processing.
                logger.atWarning().log("Reference %s in %s points to dangling object %s", r.getName(), repo.getDirectory(), r.getObjectId());
                continue;
            }
        }
        // from the reachability check, do the trace here:
        try (TraceTimer timer = TraceContext.newTimer("ReachabilityChecker.areAllReachable", Metadata.builder().projectName(project.get()).resourceCount(refs.size()).build())) {
            ReachabilityChecker checker = rw.getObjectReader().createReachabilityChecker(rw);
            Optional<RevCommit> unreachable = checker.areAllReachable(ImmutableList.of(rw.parseCommit(commit)), visible.stream());
            return !unreachable.isPresent();
        }
    } catch (IOException | PermissionBackendException e) {
        logger.atSevere().withCause(e).log("Cannot verify permissions to commit object %s in repository %s", commit.name(), project);
        return false;
    }
}
Also used : ReachabilityChecker(org.eclipse.jgit.revwalk.ReachabilityChecker) ArrayList(java.util.ArrayList) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException) Ref(org.eclipse.jgit.lib.Ref) TraceTimer(com.google.gerrit.server.logging.TraceContext.TraceTimer) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 23 with MissingObjectException

use of org.eclipse.jgit.errors.MissingObjectException in project gerrit by GerritCodeReview.

the class RefUtil method verifyConnected.

public static RevWalk verifyConnected(Repository repo, ObjectId revid) throws InvalidRevisionException {
    try {
        ObjectWalk rw = new ObjectWalk(repo);
        try {
            rw.markStart(rw.parseCommit(revid));
        } catch (IncorrectObjectTypeException err) {
            throw new InvalidRevisionException(revid.name(), err);
        }
        RefDatabase refDb = repo.getRefDatabase();
        Iterable<Ref> refs = Iterables.concat(refDb.getRefsByPrefix(Constants.R_HEADS), refDb.getRefsByPrefix(Constants.R_TAGS));
        Ref rc = refDb.exactRef(RefNames.REFS_CONFIG);
        if (rc != null) {
            refs = Iterables.concat(refs, Collections.singleton(rc));
        }
        for (Ref r : refs) {
            try {
                rw.markUninteresting(rw.parseAny(r.getObjectId()));
            } catch (MissingObjectException err) {
                continue;
            }
        }
        rw.checkConnectivity();
        return rw;
    } catch (IncorrectObjectTypeException | MissingObjectException err) {
        throw new InvalidRevisionException(revid.name(), err);
    } catch (IOException err) {
        logger.atSevere().withCause(err).log("Repository \"%s\" may be corrupt; suggest running git fsck", repo.getDirectory());
        throw new InvalidRevisionException(revid.name());
    }
}
Also used : ObjectWalk(org.eclipse.jgit.revwalk.ObjectWalk) Ref(org.eclipse.jgit.lib.Ref) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) IOException(java.io.IOException) RefDatabase(org.eclipse.jgit.lib.RefDatabase) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException)

Example 24 with MissingObjectException

use of org.eclipse.jgit.errors.MissingObjectException in project gerrit by GerritCodeReview.

the class BanCommit method ban.

/**
 * Bans a list of commits from the given project.
 *
 * <p>The user must be specified, so it can be checked for the {@code BAN_COMMIT} permission.
 */
public BanCommitResult ban(Project.NameKey project, CurrentUser user, List<ObjectId> commitsToBan, String reason) throws AuthException, IOException, PermissionBackendException {
    permissionBackend.user(user).project(project).check(ProjectPermission.BAN_COMMIT);
    final BanCommitResult result = new BanCommitResult();
    NoteMap banCommitNotes = NoteMap.newEmptyMap();
    // Add a note for each banned commit to notes.
    try (Repository repo = repoManager.openRepository(project);
        RevWalk revWalk = new RevWalk(repo);
        ObjectInserter inserter = repo.newObjectInserter()) {
        ObjectId noteId = null;
        for (ObjectId commitToBan : commitsToBan) {
            try {
                revWalk.parseCommit(commitToBan);
            } catch (MissingObjectException e) {
            // Ignore exception, non-existing commits can be banned.
            } catch (IncorrectObjectTypeException e) {
                result.notACommit(commitToBan);
                continue;
            }
            if (noteId == null) {
                noteId = createNoteContent(reason, inserter);
            }
            banCommitNotes.set(commitToBan, noteId);
        }
        NotesBranchUtil notesBranchUtil = notesBranchUtilFactory.create(project, repo, inserter);
        NoteMap newlyCreated = notesBranchUtil.commitNewNotes(banCommitNotes, REFS_REJECT_COMMITS, createPersonIdent(), buildCommitMessage(commitsToBan, reason));
        for (Note n : banCommitNotes) {
            if (newlyCreated.contains(n)) {
                result.commitBanned(n);
            } else {
                result.commitAlreadyBanned(n);
            }
        }
        return result;
    }
}
Also used : Repository(org.eclipse.jgit.lib.Repository) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) ObjectId(org.eclipse.jgit.lib.ObjectId) Note(org.eclipse.jgit.notes.Note) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) NoteMap(org.eclipse.jgit.notes.NoteMap) RevWalk(org.eclipse.jgit.revwalk.RevWalk) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException)

Example 25 with MissingObjectException

use of org.eclipse.jgit.errors.MissingObjectException in project gerrit by GerritCodeReview.

the class CreateChange method getParentCommit.

@Nullable
private ObjectId getParentCommit(Repository repo, RevWalk revWalk, String inputBranch, @Nullable Boolean newBranch, @Nullable PatchSet basePatchSet, @Nullable String baseCommit, @Nullable MergeInput mergeInput) throws BadRequestException, IOException, UnprocessableEntityException, ResourceConflictException {
    if (basePatchSet != null) {
        return basePatchSet.commitId();
    }
    Ref destRef = repo.getRefDatabase().exactRef(inputBranch);
    ObjectId parentCommit;
    if (baseCommit != null) {
        try {
            parentCommit = ObjectId.fromString(baseCommit);
        } catch (InvalidObjectIdException e) {
            throw new UnprocessableEntityException(String.format("Base %s doesn't represent a valid SHA-1", baseCommit), e);
        }
        RevCommit parentRevCommit;
        try {
            parentRevCommit = revWalk.parseCommit(parentCommit);
        } catch (MissingObjectException e) {
            throw new UnprocessableEntityException(String.format("Base %s doesn't exist", baseCommit), e);
        }
        if (destRef == null) {
            throw new BadRequestException("Destination branch does not exist");
        }
        RevCommit destRefRevCommit = revWalk.parseCommit(destRef.getObjectId());
        if (!revWalk.isMergedInto(parentRevCommit, destRefRevCommit)) {
            throw new BadRequestException(String.format("Commit %s doesn't exist on ref %s", baseCommit, inputBranch));
        }
    } else {
        if (destRef != null) {
            if (Boolean.TRUE.equals(newBranch)) {
                throw new ResourceConflictException(String.format("Branch %s already exists.", inputBranch));
            }
            parentCommit = destRef.getObjectId();
        } else {
            if (Boolean.TRUE.equals(newBranch)) {
                if (mergeInput != null) {
                    throw new BadRequestException("Cannot create merge: destination branch does not exist");
                }
                parentCommit = null;
            } else {
                throw new BadRequestException("Destination branch does not exist");
            }
        }
    }
    return parentCommit;
}
Also used : UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) Ref(org.eclipse.jgit.lib.Ref) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ObjectId(org.eclipse.jgit.lib.ObjectId) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) InvalidObjectIdException(org.eclipse.jgit.errors.InvalidObjectIdException) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException) RevCommit(org.eclipse.jgit.revwalk.RevCommit) Nullable(com.google.gerrit.common.Nullable)

Aggregations

MissingObjectException (org.eclipse.jgit.errors.MissingObjectException)31 IncorrectObjectTypeException (org.eclipse.jgit.errors.IncorrectObjectTypeException)22 ObjectId (org.eclipse.jgit.lib.ObjectId)17 RevCommit (org.eclipse.jgit.revwalk.RevCommit)16 RevWalk (org.eclipse.jgit.revwalk.RevWalk)16 IOException (java.io.IOException)13 Repository (org.eclipse.jgit.lib.Repository)12 ArrayList (java.util.ArrayList)7 Ref (org.eclipse.jgit.lib.Ref)6 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)5 Map (java.util.Map)5 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)4 TreeWalk (org.eclipse.jgit.treewalk.TreeWalk)4 ImmutableMap (com.google.common.collect.ImmutableMap)3 Iterables (com.google.common.collect.Iterables)3 Nullable (com.google.gerrit.common.Nullable)3 Change (com.google.gerrit.entities.Change)3 PatchSet (com.google.gerrit.entities.PatchSet)3 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)3 InvalidObjectIdException (org.eclipse.jgit.errors.InvalidObjectIdException)3