Search in sources :

Example 36 with ObjectReader

use of org.eclipse.jgit.lib.ObjectReader in project gerrit by GerritCodeReview.

the class FileContentUtil method downloadContent.

public BinaryResult downloadContent(ProjectState project, ObjectId revstr, String path, @Nullable Integer parent) throws ResourceNotFoundException, IOException {
    try (Repository repo = openRepository(project);
        RevWalk rw = new RevWalk(repo)) {
        String suffix = "new";
        RevCommit commit = rw.parseCommit(revstr);
        if (parent != null && parent > 0) {
            if (commit.getParentCount() == 1) {
                suffix = "old";
            } else {
                suffix = "old" + parent;
            }
            commit = rw.parseCommit(commit.getParent(parent - 1));
        }
        ObjectReader reader = rw.getObjectReader();
        TreeWalk tw = TreeWalk.forPath(reader, path, commit.getTree());
        if (tw == null) {
            throw new ResourceNotFoundException();
        }
        int mode = tw.getFileMode(0).getObjectType();
        if (mode != Constants.OBJ_BLOB) {
            throw new ResourceNotFoundException();
        }
        ObjectId id = tw.getObjectId(0);
        ObjectLoader obj = repo.open(id, OBJ_BLOB);
        byte[] raw;
        try {
            raw = obj.getCachedBytes(MAX_SIZE);
        } catch (LargeObjectException e) {
            raw = null;
        }
        MimeType contentType = registry.getMimeType(path, raw);
        return registry.isSafeInline(contentType) ? wrapBlob(path, obj, raw, contentType, suffix) : zipBlob(path, obj, commit, suffix);
    }
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) RevWalk(org.eclipse.jgit.revwalk.RevWalk) MimeType(eu.medsea.mimeutil.MimeType) LargeObjectException(org.eclipse.jgit.errors.LargeObjectException) Repository(org.eclipse.jgit.lib.Repository) ObjectReader(org.eclipse.jgit.lib.ObjectReader) ObjectLoader(org.eclipse.jgit.lib.ObjectLoader) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 37 with ObjectReader

use of org.eclipse.jgit.lib.ObjectReader in project gerrit by GerritCodeReview.

the class FileContentUtil method getContent.

public BinaryResult getContent(Repository repo, ProjectState project, ObjectId revstr, String path) throws IOException, ResourceNotFoundException {
    try (RevWalk rw = new RevWalk(repo)) {
        RevCommit commit = rw.parseCommit(revstr);
        ObjectReader reader = rw.getObjectReader();
        TreeWalk tw = TreeWalk.forPath(reader, path, commit.getTree());
        if (tw == null) {
            throw new ResourceNotFoundException();
        }
        org.eclipse.jgit.lib.FileMode mode = tw.getFileMode(0);
        ObjectId id = tw.getObjectId(0);
        if (mode == org.eclipse.jgit.lib.FileMode.GITLINK) {
            return BinaryResult.create(id.name()).setContentType(X_GIT_GITLINK).base64();
        }
        ObjectLoader obj = repo.open(id, OBJ_BLOB);
        byte[] raw;
        try {
            raw = obj.getCachedBytes(MAX_SIZE);
        } catch (LargeObjectException e) {
            raw = null;
        }
        String type;
        if (mode == org.eclipse.jgit.lib.FileMode.SYMLINK) {
            type = X_GIT_SYMLINK;
        } else {
            type = registry.getMimeType(path, raw).toString();
            type = resolveContentType(project, path, FileMode.FILE, type);
        }
        return asBinaryResult(raw, obj).setContentType(type).base64();
    }
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) RevWalk(org.eclipse.jgit.revwalk.RevWalk) LargeObjectException(org.eclipse.jgit.errors.LargeObjectException) ObjectReader(org.eclipse.jgit.lib.ObjectReader) ObjectLoader(org.eclipse.jgit.lib.ObjectLoader) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 38 with ObjectReader

use of org.eclipse.jgit.lib.ObjectReader in project gerrit by GerritCodeReview.

the class GetBlame method apply.

@Override
public Response<List<BlameInfo>> apply(FileResource resource) throws RestApiException, OrmException, IOException, InvalidChangeOperationException {
    if (!allowBlame) {
        throw new BadRequestException("blame is disabled");
    }
    Project.NameKey project = resource.getRevision().getChange().getProject();
    try (Repository repository = repoManager.openRepository(project);
        ObjectInserter ins = repository.newObjectInserter();
        ObjectReader reader = ins.newReader();
        RevWalk revWalk = new RevWalk(reader)) {
        String refName = resource.getRevision().getEdit().isPresent() ? resource.getRevision().getEdit().get().getRefName() : resource.getRevision().getPatchSet().getRefName();
        Ref ref = repository.findRef(refName);
        if (ref == null) {
            throw new ResourceNotFoundException("unknown ref " + refName);
        }
        ObjectId objectId = ref.getObjectId();
        RevCommit revCommit = revWalk.parseCommit(objectId);
        RevCommit[] parents = revCommit.getParents();
        String path = resource.getPatchKey().getFileName();
        List<BlameInfo> result;
        if (!base) {
            result = blame(revCommit, path, repository, revWalk);
        } else if (parents.length == 0) {
            throw new ResourceNotFoundException("Initial commit doesn't have base");
        } else if (parents.length == 1) {
            result = blame(parents[0], path, repository, revWalk);
        } else if (parents.length == 2) {
            ObjectId automerge = autoMerger.merge(repository, revWalk, ins, revCommit, mergeStrategy);
            result = blame(automerge, path, repository, revWalk);
        } else {
            throw new ResourceNotFoundException("Cannot generate blame for merge commit with more than 2 parents");
        }
        Response<List<BlameInfo>> r = Response.ok(result);
        if (resource.isCacheable()) {
            r.caching(CacheControl.PRIVATE(7, TimeUnit.DAYS));
        }
        return r;
    }
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) RevWalk(org.eclipse.jgit.revwalk.RevWalk) BlameInfo(com.google.gerrit.extensions.common.BlameInfo) Project(com.google.gerrit.reviewdb.client.Project) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ObjectReader(org.eclipse.jgit.lib.ObjectReader) ArrayList(java.util.ArrayList) List(java.util.List) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 39 with ObjectReader

use of org.eclipse.jgit.lib.ObjectReader in project indy by Commonjava.

the class GitManager method verifyChangesExist.

private boolean verifyChangesExist(final Collection<String> paths) throws GitSubsystemException {
    return lockAnd(me -> {
        try {
            final DiffFormatter formatter = new DiffFormatter(System.out);
            formatter.setRepository(repo);
            final ObjectId oid = repo.resolve(Constants.HEAD);
            if (oid == null) {
                return true;
            }
            final RevWalk walk = new RevWalk(repo);
            final RevCommit commit = walk.parseCommit(oid);
            final RevTree treeWalk = walk.parseTree(commit);
            final List<TreeFilter> filters = new ArrayList<>();
            for (final String path : paths) {
                filters.add(PathFilter.create(path));
            }
            filters.add(TreeFilter.ANY_DIFF);
            walk.setTreeFilter(AndTreeFilter.create(filters));
            final CanonicalTreeParser tree = new CanonicalTreeParser();
            final ObjectReader oldReader = repo.newObjectReader();
            try {
                tree.reset(oldReader, treeWalk.getId());
            } finally {
                oldReader.release();
            }
            walk.dispose();
            final FileTreeIterator files = new FileTreeIterator(repo);
            final List<DiffEntry> entries = formatter.scan(tree, files);
            return entries != null && !entries.isEmpty();
        } catch (final IOException e) {
            throw new GitSubsystemException("Failed to scan for actual changes among: %s. Reason: %s", e, paths, e.getMessage());
        }
    });
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) ArrayList(java.util.ArrayList) JoinString(org.commonjava.maven.atlas.ident.util.JoinString) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) TreeFilter(org.eclipse.jgit.treewalk.filter.TreeFilter) AndTreeFilter(org.eclipse.jgit.treewalk.filter.AndTreeFilter) ObjectReader(org.eclipse.jgit.lib.ObjectReader) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) FileTreeIterator(org.eclipse.jgit.treewalk.FileTreeIterator) RevTree(org.eclipse.jgit.revwalk.RevTree) RevCommit(org.eclipse.jgit.revwalk.RevCommit) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 40 with ObjectReader

use of org.eclipse.jgit.lib.ObjectReader in project gerrit by GerritCodeReview.

the class ReceiveCommits method insertChangesAndPatchSets.

private void insertChangesAndPatchSets() {
    ReceiveCommand magicBranchCmd = magicBranch != null ? magicBranch.cmd : null;
    if (magicBranchCmd != null && magicBranchCmd.getResult() != NOT_ATTEMPTED) {
        logWarn(String.format("Skipping change updates on %s because ref update failed: %s %s", project.getName(), magicBranchCmd.getResult(), Strings.nullToEmpty(magicBranchCmd.getMessage())));
        return;
    }
    try (BatchUpdate bu = batchUpdateFactory.create(db, project.getNameKey(), user.materializedCopy(), TimeUtil.nowTs());
        ObjectInserter ins = repo.newObjectInserter();
        ObjectReader reader = ins.newReader();
        RevWalk rw = new RevWalk(reader)) {
        bu.setRepository(repo, rw, ins).updateChangesInParallel();
        bu.setRequestId(receiveId);
        bu.setRefLogMessage("push");
        logDebug("Adding {} replace requests", newChanges.size());
        for (ReplaceRequest replace : replaceByChange.values()) {
            replace.addOps(bu, replaceProgress);
        }
        logDebug("Adding {} create requests", newChanges.size());
        for (CreateRequest create : newChanges) {
            create.addOps(bu);
        }
        logDebug("Adding {} group update requests", newChanges.size());
        updateGroups.forEach(r -> r.addOps(bu));
        logDebug("Adding {} additional ref updates", actualCommands.size());
        actualCommands.forEach(c -> bu.addRepoOnlyOp(new UpdateOneRefOp(c)));
        logDebug("Executing batch");
        try {
            bu.execute();
        } catch (UpdateException e) {
            throw INSERT_EXCEPTION.apply(e);
        }
        if (magicBranchCmd != null) {
            magicBranchCmd.setResult(OK);
        }
        for (ReplaceRequest replace : replaceByChange.values()) {
            String rejectMessage = replace.getRejectMessage();
            if (rejectMessage == null) {
                if (replace.inputCommand.getResult() == NOT_ATTEMPTED) {
                    // Not necessarily the magic branch, so need to set OK on the original value.
                    replace.inputCommand.setResult(OK);
                }
            } else {
                logDebug("Rejecting due to message from ReplaceOp");
                reject(replace.inputCommand, rejectMessage);
            }
        }
    } catch (ResourceConflictException e) {
        addMessage(e.getMessage());
        reject(magicBranchCmd, "conflict");
    } catch (RestApiException | IOException err) {
        logError("Can't insert change/patch set for " + project.getName(), err);
        reject(magicBranchCmd, "internal server error: " + err.getMessage());
    }
    if (magicBranch != null && magicBranch.submit) {
        try {
            submit(newChanges, replaceByChange.values());
        } catch (ResourceConflictException e) {
            addMessage(e.getMessage());
            reject(magicBranchCmd, "conflict");
        } catch (RestApiException | OrmException e) {
            logError("Error submitting changes to " + project.getName(), e);
            reject(magicBranchCmd, "error during submit");
        }
    }
}
Also used : ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) OrmException(com.google.gwtorm.server.OrmException) ObjectReader(org.eclipse.jgit.lib.ObjectReader) UpdateException(com.google.gerrit.server.update.UpdateException) RestApiException(com.google.gerrit.extensions.restapi.RestApiException)

Aggregations

ObjectReader (org.eclipse.jgit.lib.ObjectReader)42 RevWalk (org.eclipse.jgit.revwalk.RevWalk)30 ObjectId (org.eclipse.jgit.lib.ObjectId)22 RevCommit (org.eclipse.jgit.revwalk.RevCommit)22 Repository (org.eclipse.jgit.lib.Repository)17 ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)16 IOException (java.io.IOException)12 RevTree (org.eclipse.jgit.revwalk.RevTree)11 Change (com.google.gerrit.reviewdb.client.Change)10 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)10 DiffEntry (org.eclipse.jgit.diff.DiffEntry)7 TreeWalk (org.eclipse.jgit.treewalk.TreeWalk)7 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)6 ObjectLoader (org.eclipse.jgit.lib.ObjectLoader)6 CanonicalTreeParser (org.eclipse.jgit.treewalk.CanonicalTreeParser)6 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)5 PatchSet (com.google.gerrit.reviewdb.client.PatchSet)5 RestApiException (com.google.gerrit.extensions.restapi.RestApiException)4 Project (com.google.gerrit.reviewdb.client.Project)4 RevId (com.google.gerrit.reviewdb.client.RevId)4