Search in sources :

Example 16 with ObjectReader

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

the class PRED_commit_edits_2 method exec.

@Override
public Operation exec(Prolog engine) throws PrologException {
    engine.setB0();
    Term a1 = arg1.dereference();
    Term a2 = arg2.dereference();
    Pattern fileRegex = getRegexParameter(a1);
    Pattern editRegex = getRegexParameter(a2);
    PatchList pl = StoredValues.PATCH_LIST.get(engine);
    Repository repo = StoredValues.REPOSITORY.get(engine);
    try (ObjectReader reader = repo.newObjectReader();
        RevWalk rw = new RevWalk(reader)) {
        final RevTree aTree;
        final RevTree bTree;
        final RevCommit bCommit = rw.parseCommit(pl.getNewId());
        if (pl.getOldId() != null) {
            aTree = rw.parseTree(pl.getOldId());
        } else {
            // web UI returns no files to match against, just fail.
            return engine.fail();
        }
        bTree = bCommit.getTree();
        for (PatchListEntry entry : pl.getPatches()) {
            String newName = entry.getNewName();
            String oldName = entry.getOldName();
            if (newName.equals("/COMMIT_MSG")) {
                continue;
            }
            if (fileRegex.matcher(newName).find() || (oldName != null && fileRegex.matcher(oldName).find())) {
                List<Edit> edits = entry.getEdits();
                if (edits.isEmpty()) {
                    continue;
                }
                Text tA;
                if (oldName != null) {
                    tA = load(aTree, oldName, reader);
                } else {
                    tA = load(aTree, newName, reader);
                }
                Text tB = load(bTree, newName, reader);
                for (Edit edit : edits) {
                    if (tA != Text.EMPTY) {
                        String aDiff = tA.getString(edit.getBeginA(), edit.getEndA(), true);
                        if (editRegex.matcher(aDiff).find()) {
                            return cont;
                        }
                    }
                    if (tB != Text.EMPTY) {
                        String bDiff = tB.getString(edit.getBeginB(), edit.getEndB(), true);
                        if (editRegex.matcher(bDiff).find()) {
                            return cont;
                        }
                    }
                }
            }
        }
    } catch (IOException err) {
        throw new JavaException(this, 1, err);
    }
    return engine.fail();
}
Also used : Pattern(java.util.regex.Pattern) JavaException(com.googlecode.prolog_cafe.exceptions.JavaException) PatchListEntry(com.google.gerrit.server.patch.PatchListEntry) Edit(org.eclipse.jgit.diff.Edit) Text(com.google.gerrit.server.patch.Text) Term(com.googlecode.prolog_cafe.lang.Term) SymbolTerm(com.googlecode.prolog_cafe.lang.SymbolTerm) VariableTerm(com.googlecode.prolog_cafe.lang.VariableTerm) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Repository(org.eclipse.jgit.lib.Repository) PatchList(com.google.gerrit.server.patch.PatchList) ObjectReader(org.eclipse.jgit.lib.ObjectReader) RevTree(org.eclipse.jgit.revwalk.RevTree) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 17 with ObjectReader

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

the class Revert method revert.

private Change.Id revert(BatchUpdate.Factory updateFactory, ChangeControl ctl, String message) throws OrmException, IOException, RestApiException, UpdateException {
    Change.Id changeIdToRevert = ctl.getChange().getId();
    PatchSet.Id patchSetId = ctl.getChange().currentPatchSetId();
    PatchSet patch = psUtil.get(db.get(), ctl.getNotes(), patchSetId);
    if (patch == null) {
        throw new ResourceNotFoundException(changeIdToRevert.toString());
    }
    Project.NameKey project = ctl.getProject().getNameKey();
    CurrentUser user = ctl.getUser();
    try (Repository git = repoManager.openRepository(project);
        ObjectInserter oi = git.newObjectInserter();
        ObjectReader reader = oi.newReader();
        RevWalk revWalk = new RevWalk(reader)) {
        RevCommit commitToRevert = revWalk.parseCommit(ObjectId.fromString(patch.getRevision().get()));
        if (commitToRevert.getParentCount() == 0) {
            throw new ResourceConflictException("Cannot revert initial commit");
        }
        Timestamp now = TimeUtil.nowTs();
        PersonIdent committerIdent = new PersonIdent(serverIdent, now);
        PersonIdent authorIdent = user.asIdentifiedUser().newCommitterIdent(now, committerIdent.getTimeZone());
        RevCommit parentToCommitToRevert = commitToRevert.getParent(0);
        revWalk.parseHeaders(parentToCommitToRevert);
        CommitBuilder revertCommitBuilder = new CommitBuilder();
        revertCommitBuilder.addParentId(commitToRevert);
        revertCommitBuilder.setTreeId(parentToCommitToRevert.getTree());
        revertCommitBuilder.setAuthor(authorIdent);
        revertCommitBuilder.setCommitter(authorIdent);
        Change changeToRevert = ctl.getChange();
        if (message == null) {
            message = MessageFormat.format(ChangeMessages.get().revertChangeDefaultMessage, changeToRevert.getSubject(), patch.getRevision().get());
        }
        ObjectId computedChangeId = ChangeIdUtil.computeChangeId(parentToCommitToRevert.getTree(), commitToRevert, authorIdent, committerIdent, message);
        revertCommitBuilder.setMessage(ChangeIdUtil.insertId(message, computedChangeId, true));
        Change.Id changeId = new Change.Id(seq.nextChangeId());
        ObjectId id = oi.insert(revertCommitBuilder);
        RevCommit revertCommit = revWalk.parseCommit(id);
        ChangeInserter ins = changeInserterFactory.create(changeId, revertCommit, ctl.getChange().getDest().get()).setTopic(changeToRevert.getTopic());
        ins.setMessage("Uploaded patch set 1.");
        Set<Account.Id> reviewers = new HashSet<>();
        reviewers.add(changeToRevert.getOwner());
        reviewers.addAll(approvalsUtil.getReviewers(db.get(), ctl.getNotes()).all());
        reviewers.remove(user.getAccountId());
        ins.setReviewers(reviewers);
        try (BatchUpdate bu = updateFactory.create(db.get(), project, user, now)) {
            bu.setRepository(git, revWalk, oi);
            bu.insertChange(ins);
            bu.addOp(changeId, new NotifyOp(ctl.getChange(), ins));
            bu.addOp(changeToRevert.getId(), new PostRevertedMessageOp(computedChangeId));
            bu.execute();
        }
        return changeId;
    } catch (RepositoryNotFoundException e) {
        throw new ResourceNotFoundException(changeIdToRevert.toString(), e);
    }
}
Also used : CurrentUser(com.google.gerrit.server.CurrentUser) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) Timestamp(java.sql.Timestamp) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) ObjectReader(org.eclipse.jgit.lib.ObjectReader) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) RevCommit(org.eclipse.jgit.revwalk.RevCommit) HashSet(java.util.HashSet) ObjectId(org.eclipse.jgit.lib.ObjectId) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) Change(com.google.gerrit.reviewdb.client.Change) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Project(com.google.gerrit.reviewdb.client.Project) Repository(org.eclipse.jgit.lib.Repository) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) PersonIdent(org.eclipse.jgit.lib.PersonIdent) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) ObjectId(org.eclipse.jgit.lib.ObjectId)

Example 18 with ObjectReader

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

the class UnfusedNoteDbBatchUpdate method executeChangeOps.

private Map<Change.Id, ChangeResult> executeChangeOps(boolean dryrun) throws Exception {
    logDebug("Executing change ops");
    Map<Change.Id, ChangeResult> result = Maps.newLinkedHashMapWithExpectedSize(ops.keySet().size());
    initRepository();
    Repository repo = repoView.getRepository();
    // update as in executeUpdateRepo.
    try (ObjectInserter ins = repo.newObjectInserter();
        ObjectReader reader = ins.newReader();
        RevWalk rw = new RevWalk(reader);
        NoteDbUpdateManager updateManager = updateManagerFactory.create(project).setChangeRepo(repo, rw, ins, new ChainedReceiveCommands(repo))) {
        if (user.isIdentifiedUser()) {
            updateManager.setRefLogIdent(user.asIdentifiedUser().newRefLogIdent(when, tz));
        }
        for (Map.Entry<Change.Id, Collection<BatchUpdateOp>> e : ops.asMap().entrySet()) {
            Change.Id id = e.getKey();
            ChangeContextImpl ctx = newChangeContext(id);
            boolean dirty = false;
            logDebug("Applying {} ops for change {}", e.getValue().size(), id);
            for (BatchUpdateOp op : e.getValue()) {
                dirty |= op.updateChange(ctx);
            }
            if (!dirty) {
                logDebug("No ops reported dirty, short-circuiting");
                result.put(id, ChangeResult.SKIPPED);
                continue;
            }
            for (ChangeUpdate u : ctx.updates.values()) {
                updateManager.add(u);
            }
            if (ctx.deleted) {
                logDebug("Change {} was deleted", id);
                updateManager.deleteChange(id);
                result.put(id, ChangeResult.DELETED);
            } else {
                result.put(id, ChangeResult.UPSERTED);
            }
        }
        if (!dryrun) {
            logDebug("Executing NoteDb updates");
            updateManager.execute();
        }
    }
    return result;
}
Also used : NoteDbUpdateManager(com.google.gerrit.server.notedb.NoteDbUpdateManager) Change(com.google.gerrit.reviewdb.client.Change) RevWalk(org.eclipse.jgit.revwalk.RevWalk) ChangeUpdate(com.google.gerrit.server.notedb.ChangeUpdate) Repository(org.eclipse.jgit.lib.Repository) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) Collection(java.util.Collection) ObjectReader(org.eclipse.jgit.lib.ObjectReader) RequestId(com.google.gerrit.server.util.RequestId) Map(java.util.Map) TreeMap(java.util.TreeMap)

Example 19 with ObjectReader

use of org.eclipse.jgit.lib.ObjectReader in project searchcode-server by boyter.

the class IndexGitHistoryJob method getRevisionChanges.

public void getRevisionChanges(Repository localRepository, Git git, GitChangeSet oldRevison, GitChangeSet newRevision) throws IOException, GitAPIException {
    ObjectId oldHead = localRepository.resolve(oldRevison.getRevision() + "^{tree}");
    ObjectId newHead = localRepository.resolve(newRevision.getRevision() + "^{tree}");
    ObjectReader reader = localRepository.newObjectReader();
    CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
    oldTreeIter.reset(reader, oldHead);
    CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
    newTreeIter.reset(reader, newHead);
    List<DiffEntry> entries = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();
    GitService gs = new GitService();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    for (DiffEntry entry : entries) {
        if ("DELETE".equals(entry.getChangeType().name())) {
            System.out.println("DEL " + entry.getOldPath());
            String contents = gs.fetchFileRevision(localRepository.getWorkTree().toString() + "/.git", oldRevison.getRevision(), entry.getOldPath());
            CodeIndexDocument cd = new CodeIndexDocument(entry.getNewPath(), "thumbor", entry.getOldPath(), entry.getOldPath(), entry.getOldPath(), "md5hash", "Java", contents.split("\\r?\\n").length, contents, "", oldRevison.getAuthor());
            cd.setRevision(oldRevison.getRevision());
            cd.setYearMonthDay(sdf.format(oldRevison.getExpiry()));
            cd.setYearMonth(cd.getYearMonthDay().substring(0, 6));
            cd.setYear(cd.getYearMonthDay().substring(0, 4));
            cd.setMessage(oldRevison.getMessage());
            cd.setDeleted("TRUE");
            Singleton.getCodeIndexer().indexTimeDocument(cd);
        } else {
            System.out.println("ADD " + entry.getNewPath());
            String contents = gs.fetchFileRevision(localRepository.getWorkTree().toString() + "/.git", newRevision.getRevision(), entry.getNewPath());
            CodeIndexDocument cd = new CodeIndexDocument(entry.getNewPath(), "thumbor", entry.getNewPath(), entry.getNewPath(), entry.getNewPath(), "md5hash", "Java", contents.split("\\r?\\n").length, contents, "", newRevision.getAuthor());
            cd.setRevision(newRevision.getRevision());
            cd.setYearMonthDay(sdf.format(oldRevison.getExpiry()));
            cd.setYearMonth(cd.getYearMonthDay().substring(0, 6));
            cd.setYear(cd.getYearMonthDay().substring(0, 4));
            cd.setMessage(newRevision.getMessage());
            cd.setDeleted("FALSE");
            Singleton.getCodeIndexer().indexTimeDocument(cd);
        }
    }
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) CodeIndexDocument(com.searchcode.app.dto.CodeIndexDocument) GitService(com.searchcode.app.service.GitService) ObjectReader(org.eclipse.jgit.lib.ObjectReader) SimpleDateFormat(java.text.SimpleDateFormat) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 20 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)

Aggregations

ObjectReader (org.eclipse.jgit.lib.ObjectReader)41 RevWalk (org.eclipse.jgit.revwalk.RevWalk)29 ObjectId (org.eclipse.jgit.lib.ObjectId)21 RevCommit (org.eclipse.jgit.revwalk.RevCommit)21 Repository (org.eclipse.jgit.lib.Repository)17 ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)16 IOException (java.io.IOException)11 Change (com.google.gerrit.reviewdb.client.Change)10 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)10 RevTree (org.eclipse.jgit.revwalk.RevTree)10 DiffEntry (org.eclipse.jgit.diff.DiffEntry)7 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)6 ObjectLoader (org.eclipse.jgit.lib.ObjectLoader)6 CanonicalTreeParser (org.eclipse.jgit.treewalk.CanonicalTreeParser)6 TreeWalk (org.eclipse.jgit.treewalk.TreeWalk)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