Search in sources :

Example 56 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 57 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 58 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)

Example 59 with ObjectReader

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

the class VersionedMetaData method openUpdate.

/**
   * Open a batch of updates to the same metadata ref.
   *
   * <p>This allows making multiple commits to a single metadata ref, at the end of which is a
   * single ref update. For batching together updates to multiple refs (each consisting of one or
   * more commits against their respective refs), create the {@link MetaDataUpdate} with a {@link
   * BatchRefUpdate}.
   *
   * <p>A ref update produced by this {@link BatchMetaDataUpdate} is only committed if there is no
   * associated {@link BatchRefUpdate}. As a result, the configured ref updated event is not fired
   * if there is an associated batch.
   *
   * @param update helper info about the update.
   * @throws IOException if the update failed.
   */
public BatchMetaDataUpdate openUpdate(final MetaDataUpdate update) throws IOException {
    final Repository db = update.getRepository();
    reader = db.newObjectReader();
    inserter = db.newObjectInserter();
    final RevWalk rw = new RevWalk(reader);
    final RevTree tree = revision != null ? rw.parseTree(revision) : null;
    newTree = readTree(tree);
    return new BatchMetaDataUpdate() {

        AnyObjectId src = revision;

        AnyObjectId srcTree = tree;

        @Override
        public void write(CommitBuilder commit) throws IOException {
            write(VersionedMetaData.this, commit);
        }

        private boolean doSave(VersionedMetaData config, CommitBuilder commit) throws IOException {
            DirCache nt = config.newTree;
            ObjectReader r = config.reader;
            ObjectInserter i = config.inserter;
            try {
                config.newTree = newTree;
                config.reader = reader;
                config.inserter = inserter;
                return config.onSave(commit);
            } catch (ConfigInvalidException e) {
                throw new IOException("Cannot update " + getRefName() + " in " + db.getDirectory() + ": " + e.getMessage(), e);
            } finally {
                config.newTree = nt;
                config.reader = r;
                config.inserter = i;
            }
        }

        @Override
        public void write(VersionedMetaData config, CommitBuilder commit) throws IOException {
            if (!doSave(config, commit)) {
                return;
            }
            ObjectId res = newTree.writeTree(inserter);
            if (res.equals(srcTree) && !update.allowEmpty() && (commit.getTreeId() == null)) {
                // If there are no changes to the content, don't create the commit.
                return;
            }
            // the tree for the updated DirCache.
            if (commit.getTreeId() == null) {
                commit.setTreeId(res);
            } else {
                // In this case, the caller populated the tree without using DirCache.
                res = commit.getTreeId();
            }
            if (src != null) {
                commit.addParentId(src);
            }
            if (update.insertChangeId()) {
                ObjectId id = ChangeIdUtil.computeChangeId(res, getRevision(), commit.getAuthor(), commit.getCommitter(), commit.getMessage());
                commit.setMessage(ChangeIdUtil.insertId(commit.getMessage(), id));
            }
            src = inserter.insert(commit);
            srcTree = res;
        }

        @Override
        public RevCommit createRef(String refName) throws IOException {
            if (Objects.equals(src, revision)) {
                return revision;
            }
            return updateRef(ObjectId.zeroId(), src, refName);
        }

        @Override
        public void removeRef(String refName) throws IOException {
            RefUpdate ru = db.updateRef(refName);
            ru.setForceUpdate(true);
            if (revision != null) {
                ru.setExpectedOldObjectId(revision);
            }
            RefUpdate.Result result = ru.delete();
            switch(result) {
                case FORCED:
                    update.fireGitRefUpdatedEvent(ru);
                    return;
                case LOCK_FAILURE:
                    throw new LockFailureException("Cannot delete " + ru.getName() + " in " + db.getDirectory() + ": " + ru.getResult());
                case FAST_FORWARD:
                case IO_FAILURE:
                case NEW:
                case NOT_ATTEMPTED:
                case NO_CHANGE:
                case REJECTED:
                case REJECTED_CURRENT_BRANCH:
                case RENAMED:
                default:
                    throw new IOException("Cannot delete " + ru.getName() + " in " + db.getDirectory() + ": " + ru.getResult());
            }
        }

        @Override
        public RevCommit commit() throws IOException {
            return commitAt(revision);
        }

        @Override
        public RevCommit commitAt(ObjectId expected) throws IOException {
            if (Objects.equals(src, expected)) {
                return revision;
            }
            return updateRef(MoreObjects.firstNonNull(expected, ObjectId.zeroId()), src, getRefName());
        }

        @Override
        public void close() {
            newTree = null;
            rw.close();
            if (inserter != null) {
                inserter.close();
                inserter = null;
            }
            if (reader != null) {
                reader.close();
                reader = null;
            }
        }

        private RevCommit updateRef(AnyObjectId oldId, AnyObjectId newId, String refName) throws IOException {
            BatchRefUpdate bru = update.getBatch();
            if (bru != null) {
                bru.addCommand(new ReceiveCommand(oldId.toObjectId(), newId.toObjectId(), refName));
                inserter.flush();
                revision = rw.parseCommit(newId);
                return revision;
            }
            RefUpdate ru = db.updateRef(refName);
            ru.setExpectedOldObjectId(oldId);
            ru.setNewObjectId(src);
            ru.setRefLogIdent(update.getCommitBuilder().getAuthor());
            String message = update.getCommitBuilder().getMessage();
            if (message == null) {
                message = "meta data update";
            }
            try (BufferedReader reader = new BufferedReader(new StringReader(message))) {
                // read the subject line and use it as reflog message
                ru.setRefLogMessage("commit: " + reader.readLine(), true);
            }
            inserter.flush();
            RefUpdate.Result result = ru.update();
            switch(result) {
                case NEW:
                case FAST_FORWARD:
                    revision = rw.parseCommit(ru.getNewObjectId());
                    update.fireGitRefUpdatedEvent(ru);
                    return revision;
                case LOCK_FAILURE:
                    throw new LockFailureException("Cannot update " + ru.getName() + " in " + db.getDirectory() + ": " + ru.getResult());
                case FORCED:
                case IO_FAILURE:
                case NOT_ATTEMPTED:
                case NO_CHANGE:
                case REJECTED:
                case REJECTED_CURRENT_BRANCH:
                case RENAMED:
                default:
                    throw new IOException("Cannot update " + ru.getName() + " in " + db.getDirectory() + ": " + ru.getResult());
            }
        }
    };
}
Also used : ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) AnyObjectId(org.eclipse.jgit.lib.AnyObjectId) ObjectId(org.eclipse.jgit.lib.ObjectId) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) AnyObjectId(org.eclipse.jgit.lib.AnyObjectId) DirCache(org.eclipse.jgit.dircache.DirCache) Repository(org.eclipse.jgit.lib.Repository) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) ObjectReader(org.eclipse.jgit.lib.ObjectReader) RevTree(org.eclipse.jgit.revwalk.RevTree) BatchRefUpdate(org.eclipse.jgit.lib.BatchRefUpdate) RefUpdate(org.eclipse.jgit.lib.RefUpdate) BatchRefUpdate(org.eclipse.jgit.lib.BatchRefUpdate)

Example 60 with ObjectReader

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

the class PatchListLoader method readPatchList.

public PatchList readPatchList(Repository repo, RevWalk rw, ObjectInserter ins) throws IOException, PatchListNotAvailableException {
    ObjectReader reader = rw.getObjectReader();
    checkArgument(reader.getCreatedFromInserter() == ins);
    RawTextComparator cmp = comparatorFor(key.getWhitespace());
    try (DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE)) {
        RevCommit b = rw.parseCommit(key.getNewId());
        RevObject a = aFor(key, repo, rw, ins, b);
        if (a == null) {
            // TODO(sop) Remove this case.
            // This is an octopus merge commit which should be compared against the
            // auto-merge. However since we don't support computing the auto-merge
            // for octopus merge commits, we fall back to diffing against the first
            // parent, even though this wasn't what was requested.
            //
            ComparisonType comparisonType = ComparisonType.againstParent(1);
            PatchListEntry[] entries = new PatchListEntry[2];
            entries[0] = newCommitMessage(cmp, reader, null, b);
            entries[1] = newMergeList(cmp, reader, null, b, comparisonType);
            return new PatchList(a, b, true, comparisonType, entries);
        }
        ComparisonType comparisonType = getComparisonType(a, b);
        RevCommit aCommit = a instanceof RevCommit ? (RevCommit) a : null;
        RevTree aTree = rw.parseTree(a);
        RevTree bTree = b.getTree();
        df.setReader(reader, repo.getConfig());
        df.setDiffComparator(cmp);
        df.setDetectRenames(true);
        List<DiffEntry> diffEntries = df.scan(aTree, bTree);
        Set<String> paths = null;
        if (key.getOldId() != null && b.getParentCount() == 1) {
            PatchListKey newKey = PatchListKey.againstDefaultBase(key.getNewId(), key.getWhitespace());
            PatchListKey oldKey = PatchListKey.againstDefaultBase(key.getOldId(), key.getWhitespace());
            paths = Stream.concat(patchListCache.get(newKey, project).getPatches().stream(), patchListCache.get(oldKey, project).getPatches().stream()).map(PatchListEntry::getNewName).collect(toSet());
        }
        int cnt = diffEntries.size();
        List<PatchListEntry> entries = new ArrayList<>();
        entries.add(newCommitMessage(cmp, reader, comparisonType.isAgainstParentOrAutoMerge() ? null : aCommit, b));
        boolean isMerge = b.getParentCount() > 1;
        if (isMerge) {
            entries.add(newMergeList(cmp, reader, comparisonType.isAgainstParentOrAutoMerge() ? null : aCommit, b, comparisonType));
        }
        for (int i = 0; i < cnt; i++) {
            DiffEntry e = diffEntries.get(i);
            if (paths == null || paths.contains(e.getNewPath()) || paths.contains(e.getOldPath())) {
                FileHeader fh = toFileHeader(key, df, e);
                long oldSize = getFileSize(reader, e.getOldMode(), e.getOldPath(), aTree);
                long newSize = getFileSize(reader, e.getNewMode(), e.getNewPath(), bTree);
                entries.add(newEntry(aTree, fh, newSize, newSize - oldSize));
            }
        }
        return new PatchList(a, b, isMerge, comparisonType, entries.toArray(new PatchListEntry[entries.size()]));
    }
}
Also used : RevObject(org.eclipse.jgit.revwalk.RevObject) RawTextComparator(org.eclipse.jgit.diff.RawTextComparator) ArrayList(java.util.ArrayList) ObjectReader(org.eclipse.jgit.lib.ObjectReader) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) FileHeader(org.eclipse.jgit.patch.FileHeader) RevTree(org.eclipse.jgit.revwalk.RevTree) RevCommit(org.eclipse.jgit.revwalk.RevCommit) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Aggregations

ObjectReader (org.eclipse.jgit.lib.ObjectReader)115 RevWalk (org.eclipse.jgit.revwalk.RevWalk)69 ObjectId (org.eclipse.jgit.lib.ObjectId)59 RevCommit (org.eclipse.jgit.revwalk.RevCommit)56 Repository (org.eclipse.jgit.lib.Repository)47 ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)31 CanonicalTreeParser (org.eclipse.jgit.treewalk.CanonicalTreeParser)26 IOException (java.io.IOException)24 Test (org.junit.Test)23 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)20 RevTree (org.eclipse.jgit.revwalk.RevTree)19 DiffEntry (org.eclipse.jgit.diff.DiffEntry)18 Ref (org.eclipse.jgit.lib.Ref)17 PersonIdent (org.eclipse.jgit.lib.PersonIdent)14 TreeWalk (org.eclipse.jgit.treewalk.TreeWalk)13 TestRepository (org.eclipse.jgit.junit.TestRepository)12 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)11 Change (com.google.gerrit.reviewdb.client.Change)10 Map (java.util.Map)10 GerritPersonIdent (com.google.gerrit.server.GerritPersonIdent)9