Search in sources :

Example 21 with ObjectReader

use of org.eclipse.jgit.lib.ObjectReader in project che by eclipse.

the class JGitDiffPage method commitToIndex.

/**
     * Show changes between specified revision and index. If
     * <code>commitId == null</code> then view changes between HEAD and index.
     *
     * @param commitId
     *            id of commit, pass <code>null</code> is the same as pass HEAD
     * @param formatter
     *            diff formatter
     * @return list of diff entries
     * @throws IOException
     *             if any i/o errors occurs
     */
private List<DiffEntry> commitToIndex(String commitId, DiffFormatter formatter) throws IOException {
    if (commitId == null) {
        commitId = Constants.HEAD;
    }
    ObjectId commitA = repository.resolve(commitId);
    if (commitA == null) {
        throw new IllegalArgumentException("Invalid commit id " + commitId);
    }
    RevTree treeA;
    try (RevWalk revWalkA = new RevWalk(repository)) {
        treeA = revWalkA.parseTree(commitA);
    }
    DirCache dirCache = null;
    List<DiffEntry> diff;
    try (ObjectReader reader = repository.newObjectReader()) {
        dirCache = repository.lockDirCache();
        CanonicalTreeParser iterA = new CanonicalTreeParser();
        iterA.reset(reader, treeA);
        DirCacheIterator iterB = new DirCacheIterator(dirCache);
        if (!params.isNoRenames()) {
            // Use embedded RenameDetector it works well with index and
            // revision history.
            formatter.setDetectRenames(true);
            int renameLimit = params.getRenameLimit();
            if (renameLimit > 0) {
                formatter.getRenameDetector().setRenameLimit(renameLimit);
            }
        }
        diff = formatter.scan(iterA, iterB);
    } finally {
        if (dirCache != null) {
            dirCache.unlock();
        }
    }
    return diff;
}
Also used : DirCache(org.eclipse.jgit.dircache.DirCache) ObjectId(org.eclipse.jgit.lib.ObjectId) ObjectReader(org.eclipse.jgit.lib.ObjectReader) DirCacheIterator(org.eclipse.jgit.dircache.DirCacheIterator) RevWalk(org.eclipse.jgit.revwalk.RevWalk) RevTree(org.eclipse.jgit.revwalk.RevTree) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 22 with ObjectReader

use of org.eclipse.jgit.lib.ObjectReader in project che by eclipse.

the class JGitDiffPage method indexToWorkingTree.

/**
     * Show changes between index and working tree.
     *
     * @param formatter
     *            diff formatter
     * @return list of diff entries
     * @throws IOException
     *             if any i/o errors occurs
     */
private List<DiffEntry> indexToWorkingTree(DiffFormatter formatter) throws IOException {
    DirCache dirCache = null;
    ObjectReader reader = repository.newObjectReader();
    List<DiffEntry> diff;
    try {
        dirCache = repository.lockDirCache();
        DirCacheIterator iterA = new DirCacheIterator(dirCache);
        FileTreeIterator iterB = new FileTreeIterator(repository);
        // Seems bug in DiffFormatter when work with working. Disable detect
        // renames by formatter and do it later.
        formatter.setDetectRenames(false);
        diff = formatter.scan(iterA, iterB);
        if (!params.isNoRenames()) {
            // Detect renames.
            RenameDetector renameDetector = createRenameDetector();
            ContentSource.Pair sourcePairReader = new ContentSource.Pair(ContentSource.create(reader), ContentSource.create(iterB));
            renameDetector.addAll(diff);
            diff = renameDetector.compute(sourcePairReader, NullProgressMonitor.INSTANCE);
        }
    } finally {
        reader.close();
        if (dirCache != null) {
            dirCache.unlock();
        }
    }
    return diff;
}
Also used : DirCache(org.eclipse.jgit.dircache.DirCache) ContentSource(org.eclipse.jgit.diff.ContentSource) RenameDetector(org.eclipse.jgit.diff.RenameDetector) ObjectReader(org.eclipse.jgit.lib.ObjectReader) DirCacheIterator(org.eclipse.jgit.dircache.DirCacheIterator) FileTreeIterator(org.eclipse.jgit.treewalk.FileTreeIterator) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 23 with ObjectReader

use of org.eclipse.jgit.lib.ObjectReader in project gitblit by gitblit.

the class CompressionUtils method zip.

/**
	 * Zips the contents of the tree at the (optionally) specified revision and
	 * the (optionally) specified basepath to the supplied outputstream.
	 *
	 * @param repository
	 * @param basePath
	 *            if unspecified, entire repository is assumed.
	 * @param objectId
	 *            if unspecified, HEAD is assumed.
	 * @param os
	 * @return true if repository was successfully zipped to supplied output
	 *         stream
	 */
public static boolean zip(Repository repository, IFilestoreManager filestoreManager, String basePath, String objectId, OutputStream os) {
    RevCommit commit = JGitUtils.getCommit(repository, objectId);
    if (commit == null) {
        return false;
    }
    boolean success = false;
    RevWalk rw = new RevWalk(repository);
    TreeWalk tw = new TreeWalk(repository);
    try {
        tw.reset();
        tw.addTree(commit.getTree());
        ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os);
        zos.setComment("Generated by Gitblit");
        if (!StringUtils.isEmpty(basePath)) {
            PathFilter f = PathFilter.create(basePath);
            tw.setFilter(f);
        }
        tw.setRecursive(true);
        MutableObjectId id = new MutableObjectId();
        ObjectReader reader = tw.getObjectReader();
        long modified = commit.getAuthorIdent().getWhen().getTime();
        while (tw.next()) {
            FileMode mode = tw.getFileMode(0);
            if (mode == FileMode.GITLINK || mode == FileMode.TREE) {
                continue;
            }
            tw.getObjectId(id, 0);
            ObjectLoader loader = repository.open(id);
            ZipArchiveEntry entry = new ZipArchiveEntry(tw.getPathString());
            FilestoreModel filestoreItem = null;
            if (JGitUtils.isPossibleFilestoreItem(loader.getSize())) {
                filestoreItem = JGitUtils.getFilestoreItem(tw.getObjectReader().open(id));
            }
            final long size = (filestoreItem == null) ? loader.getSize() : filestoreItem.getSize();
            entry.setSize(size);
            entry.setComment(commit.getName());
            entry.setUnixMode(mode.getBits());
            entry.setTime(modified);
            zos.putArchiveEntry(entry);
            if (filestoreItem == null) {
                //Copy repository stored file
                loader.copyTo(zos);
            } else {
                //Copy filestore file
                try (FileInputStream streamIn = new FileInputStream(filestoreManager.getStoragePath(filestoreItem.oid))) {
                    IOUtils.copyLarge(streamIn, zos);
                } catch (Throwable e) {
                    LOGGER.error(MessageFormat.format("Failed to archive filestore item {0}", filestoreItem.oid), e);
                    //Handle as per other errors 
                    throw e;
                }
            }
            zos.closeArchiveEntry();
        }
        zos.finish();
        success = true;
    } catch (IOException e) {
        error(e, repository, "{0} failed to zip files from commit {1}", commit.getName());
    } finally {
        tw.close();
        rw.dispose();
    }
    return success;
}
Also used : FileMode(org.eclipse.jgit.lib.FileMode) PathFilter(org.eclipse.jgit.treewalk.filter.PathFilter) FilestoreModel(com.gitblit.models.FilestoreModel) ZipArchiveOutputStream(org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) FileInputStream(java.io.FileInputStream) MutableObjectId(org.eclipse.jgit.lib.MutableObjectId) ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) ObjectReader(org.eclipse.jgit.lib.ObjectReader) ObjectLoader(org.eclipse.jgit.lib.ObjectLoader) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 24 with ObjectReader

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

the class ReviewProjectAccess method updateProjectConfig.

// TODO(dborowitz): Hack MetaDataUpdate so it can be created within a BatchUpdate and we can avoid
// calling setUpdateRef(false).
@SuppressWarnings("deprecation")
@Override
protected Change.Id updateProjectConfig(ProjectControl projectControl, ProjectConfig config, MetaDataUpdate md, boolean parentProjectUpdate) throws IOException, OrmException, PermissionDeniedException {
    RefControl refsMetaConfigControl = projectControl.controlForRef(RefNames.REFS_CONFIG);
    if (!refsMetaConfigControl.isVisible()) {
        throw new PermissionDeniedException(RefNames.REFS_CONFIG + " not visible");
    }
    if (!projectControl.isOwner() && !refsMetaConfigControl.canUpload()) {
        throw new PermissionDeniedException("cannot upload to " + RefNames.REFS_CONFIG);
    }
    md.setInsertChangeId(true);
    Change.Id changeId = new Change.Id(seq.nextChangeId());
    RevCommit commit = config.commitToNewRef(md, new PatchSet.Id(changeId, Change.INITIAL_PATCH_SET_ID).toRefName());
    if (commit.getId().equals(base)) {
        return null;
    }
    try (ObjectInserter objInserter = md.getRepository().newObjectInserter();
        ObjectReader objReader = objInserter.newReader();
        RevWalk rw = new RevWalk(objReader);
        BatchUpdate bu = updateFactory.create(db, config.getProject().getNameKey(), projectControl.getUser(), TimeUtil.nowTs())) {
        bu.setRepository(md.getRepository(), rw, objInserter);
        bu.insertChange(changeInserterFactory.create(changeId, commit, RefNames.REFS_CONFIG).setValidate(false).setUpdateRef(// Created by commitToNewRef.
        false));
        bu.execute();
    } catch (UpdateException | RestApiException e) {
        throw new IOException(e);
    }
    ChangeResource rsrc;
    try {
        rsrc = changes.parse(changeId);
    } catch (ResourceNotFoundException e) {
        throw new IOException(e);
    }
    addProjectOwnersAsReviewers(rsrc);
    if (parentProjectUpdate) {
        addAdministratorsAsReviewers(rsrc);
    }
    return changeId;
}
Also used : RefControl(com.google.gerrit.server.project.RefControl) Change(com.google.gerrit.reviewdb.client.Change) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) ChangeResource(com.google.gerrit.server.change.ChangeResource) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) PermissionDeniedException(com.google.gerrit.common.errors.PermissionDeniedException) ObjectReader(org.eclipse.jgit.lib.ObjectReader) ObjectId(org.eclipse.jgit.lib.ObjectId) UpdateException(com.google.gerrit.server.update.UpdateException) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 25 with ObjectReader

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

the class RebuildNoteDb method rebuildProject.

private boolean rebuildProject(ReviewDb db, ImmutableListMultimap<Project.NameKey, Change.Id> allChanges, Project.NameKey project, Repository allUsersRepo) throws IOException, OrmException {
    checkArgument(allChanges.containsKey(project));
    boolean ok = true;
    ProgressMonitor pm = new TextProgressMonitor(new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out, UTF_8))));
    pm.beginTask(FormatUtil.elide(project.get(), 50), allChanges.get(project).size());
    try (NoteDbUpdateManager manager = updateManagerFactory.create(project);
        ObjectInserter allUsersInserter = allUsersRepo.newObjectInserter();
        ObjectReader reader = allUsersInserter.newReader();
        RevWalk allUsersRw = new RevWalk(reader)) {
        manager.setAllUsersRepo(allUsersRepo, allUsersRw, allUsersInserter, new ChainedReceiveCommands(allUsersRepo));
        for (Change.Id changeId : allChanges.get(project)) {
            try {
                rebuilder.buildUpdates(manager, bundleReader.fromReviewDb(db, changeId));
            } catch (NoPatchSetsException e) {
                log.warn(e.getMessage());
            } catch (Throwable t) {
                log.error("Failed to rebuild change " + changeId, t);
                ok = false;
            }
            pm.update(1);
        }
        manager.execute();
    } finally {
        pm.endTask();
    }
    return ok;
}
Also used : ChainedReceiveCommands(com.google.gerrit.server.update.ChainedReceiveCommands) NoteDbUpdateManager(com.google.gerrit.server.notedb.NoteDbUpdateManager) Change(com.google.gerrit.reviewdb.client.Change) TextProgressMonitor(org.eclipse.jgit.lib.TextProgressMonitor) RevWalk(org.eclipse.jgit.revwalk.RevWalk) BufferedWriter(java.io.BufferedWriter) TextProgressMonitor(org.eclipse.jgit.lib.TextProgressMonitor) NullProgressMonitor(org.eclipse.jgit.lib.NullProgressMonitor) ProgressMonitor(org.eclipse.jgit.lib.ProgressMonitor) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) NoPatchSetsException(com.google.gerrit.server.notedb.rebuild.ChangeRebuilder.NoPatchSetsException) OutputStreamWriter(java.io.OutputStreamWriter) ObjectReader(org.eclipse.jgit.lib.ObjectReader) PrintWriter(java.io.PrintWriter)

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