Search in sources :

Example 11 with ObjectReader

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

the class CommentsIT method assertMetaBranchCommitsAfterRewriting.

/**
   * All the commits, which contain the target comment before, should still contain the comment with
   * the updated message. All the other metas of the commits should be exactly the same.
   */
private void assertMetaBranchCommitsAfterRewriting(List<RevCommit> beforeDelete, Change.Id changeId, String targetCommentUuid, String expectedMessage) throws Exception {
    List<RevCommit> afterDelete = getCommits(changeId);
    assertThat(afterDelete).hasSize(beforeDelete.size());
    try (Repository repo = repoManager.openRepository(project);
        ObjectReader reader = repo.newObjectReader()) {
        for (int i = 0; i < beforeDelete.size(); i++) {
            RevCommit commitBefore = beforeDelete.get(i);
            RevCommit commitAfter = afterDelete.get(i);
            Map<String, com.google.gerrit.reviewdb.client.Comment> commentMapBefore = DeleteCommentRewriter.getPublishedComments(noteUtil, changeId, reader, NoteMap.read(reader, commitBefore));
            Map<String, com.google.gerrit.reviewdb.client.Comment> commentMapAfter = DeleteCommentRewriter.getPublishedComments(noteUtil, changeId, reader, NoteMap.read(reader, commitAfter));
            if (commentMapBefore.containsKey(targetCommentUuid)) {
                assertThat(commentMapAfter).containsKey(targetCommentUuid);
                com.google.gerrit.reviewdb.client.Comment comment = commentMapAfter.get(targetCommentUuid);
                assertThat(comment.message).isEqualTo(expectedMessage);
                comment.message = commentMapBefore.get(targetCommentUuid).message;
                commentMapAfter.put(targetCommentUuid, comment);
                assertThat(commentMapAfter).isEqualTo(commentMapBefore);
            } else {
                assertThat(commentMapAfter).doesNotContainKey(targetCommentUuid);
            }
            // Other metas should be exactly the same.
            assertThat(commitAfter.getFullMessage()).isEqualTo(commitBefore.getFullMessage());
            assertThat(commitAfter.getCommitterIdent()).isEqualTo(commitBefore.getCommitterIdent());
            assertThat(commitAfter.getAuthorIdent()).isEqualTo(commitBefore.getAuthorIdent());
            assertThat(commitAfter.getEncoding()).isEqualTo(commitBefore.getEncoding());
            assertThat(commitAfter.getEncodingName()).isEqualTo(commitBefore.getEncodingName());
        }
    }
}
Also used : Comment(com.google.gerrit.extensions.client.Comment) IdString(com.google.gerrit.extensions.restapi.IdString) Repository(org.eclipse.jgit.lib.Repository) ObjectReader(org.eclipse.jgit.lib.ObjectReader) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 12 with ObjectReader

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

the class PublicKeyStoreTest method saveAppendsToExistingList.

@Test
public void saveAppendsToExistingList() throws Exception {
    TestKey key1 = validKeyWithoutExpiration();
    TestKey key2 = validKeyWithExpiration();
    tr.branch(REFS_GPG_KEYS).commit().add(keyObjectId(key1.getKeyId()).name(), key2.getPublicKeyArmored()).create();
    store.add(key1.getPublicKeyRing());
    assertEquals(RefUpdate.Result.FAST_FORWARD, store.save(newCommitBuilder()));
    assertKeys(key1.getKeyId(), key1, key2);
    try (ObjectReader reader = tr.getRepository().newObjectReader();
        RevWalk rw = new RevWalk(reader)) {
        NoteMap notes = NoteMap.read(reader, tr.getRevWalk().parseCommit(tr.getRepository().exactRef(REFS_GPG_KEYS).getObjectId()));
        String contents = new String(reader.open(notes.get(keyObjectId(key1.getKeyId()))).getBytes(), UTF_8);
        String header = "-----BEGIN PGP PUBLIC KEY BLOCK-----";
        int i1 = contents.indexOf(header);
        assertTrue(i1 >= 0);
        int i2 = contents.indexOf(header, i1 + header.length());
        assertTrue(i2 >= 0);
    }
}
Also used : TestKey(com.google.gerrit.gpg.testutil.TestKey) ObjectReader(org.eclipse.jgit.lib.ObjectReader) NoteMap(org.eclipse.jgit.notes.NoteMap) PublicKeyStore.keyToString(com.google.gerrit.gpg.PublicKeyStore.keyToString) PublicKeyStore.keyIdToString(com.google.gerrit.gpg.PublicKeyStore.keyIdToString) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Test(org.junit.Test)

Example 13 with ObjectReader

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

the class CherryPickChange method cherryPick.

public Change.Id cherryPick(BatchUpdate.Factory batchUpdateFactory, @Nullable Change.Id sourceChangeId, @Nullable PatchSet.Id sourcePatchId, @Nullable Branch.NameKey sourceBranch, @Nullable String sourceChangeTopic, Project.NameKey project, ObjectId sourceCommit, CherryPickInput input, String targetRef, RefControl targetRefControl) throws OrmException, IOException, InvalidChangeOperationException, IntegrationException, UpdateException, RestApiException {
    if (Strings.isNullOrEmpty(targetRef)) {
        throw new InvalidChangeOperationException("Cherry Pick: Destination branch cannot be null or empty");
    }
    String destinationBranch = RefNames.shortName(targetRef);
    IdentifiedUser identifiedUser = user.get();
    try (Repository git = gitManager.openRepository(project);
        // before patch sets are updated.
        ObjectInserter oi = git.newObjectInserter();
        ObjectReader reader = oi.newReader();
        CodeReviewRevWalk revWalk = CodeReviewCommit.newRevWalk(reader)) {
        Ref destRef = git.getRefDatabase().exactRef(targetRef);
        if (destRef == null) {
            throw new InvalidChangeOperationException(String.format("Branch %s does not exist.", destinationBranch));
        }
        CodeReviewCommit mergeTip = revWalk.parseCommit(destRef.getObjectId());
        CodeReviewCommit commitToCherryPick = revWalk.parseCommit(sourceCommit);
        if (input.parent <= 0 || input.parent > commitToCherryPick.getParentCount()) {
            throw new InvalidChangeOperationException(String.format("Cherry Pick: Parent %s does not exist. Please specify a parent in" + " range [1, %s].", input.parent, commitToCherryPick.getParentCount()));
        }
        Timestamp now = TimeUtil.nowTs();
        PersonIdent committerIdent = identifiedUser.newCommitterIdent(now, serverTimeZone);
        final ObjectId computedChangeId = ChangeIdUtil.computeChangeId(commitToCherryPick.getTree(), mergeTip, commitToCherryPick.getAuthorIdent(), committerIdent, input.message);
        String commitMessage = ChangeIdUtil.insertId(input.message, computedChangeId).trim() + '\n';
        CodeReviewCommit cherryPickCommit;
        try {
            ProjectState projectState = targetRefControl.getProjectControl().getProjectState();
            cherryPickCommit = mergeUtilFactory.create(projectState).createCherryPickFromCommit(oi, git.getConfig(), mergeTip, commitToCherryPick, committerIdent, commitMessage, revWalk, input.parent - 1, false);
            Change.Key changeKey;
            final List<String> idList = cherryPickCommit.getFooterLines(FooterConstants.CHANGE_ID);
            if (!idList.isEmpty()) {
                final String idStr = idList.get(idList.size() - 1).trim();
                changeKey = new Change.Key(idStr);
            } else {
                changeKey = new Change.Key("I" + computedChangeId.name());
            }
            Branch.NameKey newDest = new Branch.NameKey(project, destRef.getName());
            List<ChangeData> destChanges = queryProvider.get().setLimit(2).byBranchKey(newDest, changeKey);
            if (destChanges.size() > 1) {
                throw new InvalidChangeOperationException("Several changes with key " + changeKey + " reside on the same branch. " + "Cannot create a new patch set.");
            }
            try (BatchUpdate bu = batchUpdateFactory.create(db.get(), project, identifiedUser, now)) {
                bu.setRepository(git, revWalk, oi);
                Change.Id result;
                if (destChanges.size() == 1) {
                    // The change key exists on the destination branch. The cherry pick
                    // will be added as a new patch set.
                    ChangeControl destCtl = targetRefControl.getProjectControl().controlFor(destChanges.get(0).notes());
                    result = insertPatchSet(bu, git, destCtl, cherryPickCommit, input);
                } else {
                    // Change key not found on destination branch. We can create a new
                    // change.
                    String newTopic = null;
                    if (!Strings.isNullOrEmpty(sourceChangeTopic)) {
                        newTopic = sourceChangeTopic + "-" + newDest.getShortName();
                    }
                    result = createNewChange(bu, cherryPickCommit, targetRefControl.getRefName(), newTopic, sourceBranch, sourceCommit, input);
                    if (sourceChangeId != null && sourcePatchId != null) {
                        bu.addOp(sourceChangeId, new AddMessageToSourceChangeOp(changeMessagesUtil, sourcePatchId, destinationBranch, cherryPickCommit));
                    }
                }
                bu.execute();
                return result;
            }
        } catch (MergeIdenticalTreeException | MergeConflictException e) {
            throw new IntegrationException("Cherry pick failed: " + e.getMessage());
        }
    }
}
Also used : InvalidChangeOperationException(com.google.gerrit.server.project.InvalidChangeOperationException) Timestamp(java.sql.Timestamp) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) MergeConflictException(com.google.gerrit.extensions.restapi.MergeConflictException) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) Branch(com.google.gerrit.reviewdb.client.Branch) ChangeControl(com.google.gerrit.server.project.ChangeControl) ObjectReader(org.eclipse.jgit.lib.ObjectReader) IntegrationException(com.google.gerrit.server.git.IntegrationException) ObjectId(org.eclipse.jgit.lib.ObjectId) CodeReviewRevWalk(com.google.gerrit.server.git.CodeReviewCommit.CodeReviewRevWalk) Change(com.google.gerrit.reviewdb.client.Change) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) CodeReviewCommit(com.google.gerrit.server.git.CodeReviewCommit) ChangeData(com.google.gerrit.server.query.change.ChangeData) MergeIdenticalTreeException(com.google.gerrit.server.git.MergeIdenticalTreeException) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) PersonIdent(org.eclipse.jgit.lib.PersonIdent) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) ProjectState(com.google.gerrit.server.project.ProjectState)

Example 14 with ObjectReader

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

the class CreateChange method applyImpl.

@Override
protected Response<ChangeInfo> applyImpl(BatchUpdate.Factory updateFactory, TopLevelResource parent, ChangeInput input) throws OrmException, IOException, InvalidChangeOperationException, RestApiException, UpdateException, PermissionBackendException {
    if (Strings.isNullOrEmpty(input.project)) {
        throw new BadRequestException("project must be non-empty");
    }
    if (Strings.isNullOrEmpty(input.branch)) {
        throw new BadRequestException("branch must be non-empty");
    }
    if (Strings.isNullOrEmpty(input.subject)) {
        throw new BadRequestException("commit message must be non-empty");
    }
    if (input.status != null) {
        if (input.status != ChangeStatus.NEW && input.status != ChangeStatus.DRAFT) {
            throw new BadRequestException("unsupported change status");
        }
        if (!allowDrafts && input.status == ChangeStatus.DRAFT) {
            throw new MethodNotAllowedException("draft workflow is disabled");
        }
    }
    String refName = RefNames.fullName(input.branch);
    ProjectResource rsrc = projectsCollection.parse(input.project);
    Capable r = rsrc.getControl().canPushToAtLeastOneRef();
    if (r != Capable.OK) {
        throw new AuthException(r.getMessage());
    }
    RefControl refControl = rsrc.getControl().controlForRef(refName);
    if (!refControl.canUpload() || !refControl.isVisible()) {
        throw new AuthException("cannot upload review");
    }
    Project.NameKey project = rsrc.getNameKey();
    try (Repository git = gitManager.openRepository(project);
        ObjectInserter oi = git.newObjectInserter();
        ObjectReader reader = oi.newReader();
        RevWalk rw = new RevWalk(reader)) {
        ObjectId parentCommit;
        List<String> groups;
        if (input.baseChange != null) {
            List<ChangeControl> ctls = changeFinder.find(input.baseChange, rsrc.getControl().getUser());
            if (ctls.size() != 1) {
                throw new UnprocessableEntityException("Base change not found: " + input.baseChange);
            }
            ChangeControl ctl = Iterables.getOnlyElement(ctls);
            if (!ctl.isVisible(db.get())) {
                throw new UnprocessableEntityException("Base change not found: " + input.baseChange);
            }
            PatchSet ps = psUtil.current(db.get(), ctl.getNotes());
            parentCommit = ObjectId.fromString(ps.getRevision().get());
            groups = ps.getGroups();
        } else {
            Ref destRef = git.getRefDatabase().exactRef(refName);
            if (destRef != null) {
                if (Boolean.TRUE.equals(input.newBranch)) {
                    throw new ResourceConflictException(String.format("Branch %s already exists.", refName));
                }
                parentCommit = destRef.getObjectId();
            } else {
                if (Boolean.TRUE.equals(input.newBranch)) {
                    parentCommit = null;
                } else {
                    throw new UnprocessableEntityException(String.format("Branch %s does not exist.", refName));
                }
            }
            groups = Collections.emptyList();
        }
        RevCommit mergeTip = parentCommit == null ? null : rw.parseCommit(parentCommit);
        Timestamp now = TimeUtil.nowTs();
        IdentifiedUser me = user.get().asIdentifiedUser();
        PersonIdent author = me.newCommitterIdent(now, serverTimeZone);
        AccountState account = accountCache.get(me.getAccountId());
        GeneralPreferencesInfo info = account.getAccount().getGeneralPreferencesInfo();
        ObjectId treeId = mergeTip == null ? emptyTreeId(oi) : mergeTip.getTree();
        ObjectId id = ChangeIdUtil.computeChangeId(treeId, mergeTip, author, author, input.subject);
        String commitMessage = ChangeIdUtil.insertId(input.subject, id);
        if (Boolean.TRUE.equals(info.signedOffBy)) {
            commitMessage += String.format("%s%s", SIGNED_OFF_BY_TAG, account.getAccount().getNameEmail(anonymousCowardName));
        }
        RevCommit c;
        if (input.merge != null) {
            // create a merge commit
            if (!(submitType.equals(SubmitType.MERGE_ALWAYS) || submitType.equals(SubmitType.MERGE_IF_NECESSARY))) {
                throw new BadRequestException("Submit type: " + submitType + " is not supported");
            }
            c = newMergeCommit(git, oi, rw, rsrc.getControl(), mergeTip, input.merge, author, commitMessage);
        } else {
            // create an empty commit
            c = newCommit(oi, rw, author, mergeTip, commitMessage);
        }
        Change.Id changeId = new Change.Id(seq.nextChangeId());
        ChangeInserter ins = changeInserterFactory.create(changeId, c, refName);
        ins.setMessage(String.format("Uploaded patch set %s.", ins.getPatchSetId().get()));
        String topic = input.topic;
        if (topic != null) {
            topic = Strings.emptyToNull(topic.trim());
        }
        ins.setTopic(topic);
        ins.setDraft(input.status == ChangeStatus.DRAFT);
        ins.setPrivate(input.isPrivate != null && input.isPrivate);
        ins.setWorkInProgress(input.workInProgress != null && input.workInProgress);
        ins.setGroups(groups);
        ins.setNotify(input.notify);
        ins.setAccountsToNotify(notifyUtil.resolveAccounts(input.notifyDetails));
        try (BatchUpdate bu = updateFactory.create(db.get(), project, me, now)) {
            bu.setRepository(git, rw, oi);
            bu.insertChange(ins);
            bu.execute();
        }
        ChangeJson json = jsonFactory.noOptions();
        return Response.created(json.format(ins.getChange()));
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(e.getMessage());
    }
}
Also used : RefControl(com.google.gerrit.server.project.RefControl) AuthException(com.google.gerrit.extensions.restapi.AuthException) Timestamp(java.sql.Timestamp) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) Capable(com.google.gerrit.common.data.Capable) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) ChangeControl(com.google.gerrit.server.project.ChangeControl) ObjectReader(org.eclipse.jgit.lib.ObjectReader) RevCommit(org.eclipse.jgit.revwalk.RevCommit) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) ObjectId(org.eclipse.jgit.lib.ObjectId) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) AccountState(com.google.gerrit.server.account.AccountState) Change(com.google.gerrit.reviewdb.client.Change) RevWalk(org.eclipse.jgit.revwalk.RevWalk) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) Project(com.google.gerrit.reviewdb.client.Project) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) PersonIdent(org.eclipse.jgit.lib.PersonIdent) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) GeneralPreferencesInfo(com.google.gerrit.extensions.client.GeneralPreferencesInfo) ProjectResource(com.google.gerrit.server.project.ProjectResource) ObjectId(org.eclipse.jgit.lib.ObjectId)

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

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