Search in sources :

Example 6 with NoteMap

use of org.eclipse.jgit.notes.NoteMap in project gerrit by GerritCodeReview.

the class GroupNameNotes method updateAllGroups.

/**
 * Replaces the map of name/UUID pairs with a new version which matches exactly the passed {@code
 * GroupReference}s.
 *
 * <p>All old entries are discarded and replaced by the new ones.
 *
 * <p>This operation also works if the previous map has invalid entries or can't be read anymore.
 *
 * <p><strong>Note: </strong>This method doesn't flush the {@code ObjectInserter}. It doesn't
 * execute the {@code BatchRefUpdate} either.
 *
 * @param repository the repository which holds the commits of the notes
 * @param inserter an {@code ObjectInserter} for that repository
 * @param bru a {@code BatchRefUpdate} to which this method adds commands
 * @param groupReferences all {@code GroupReference}s (name/UUID pairs) which should be contained
 *     in the map of name/UUID pairs
 * @param ident the {@code PersonIdent} which is used as author and committer for commits
 * @throws IOException if the repository can't be accessed for some reason
 */
public static void updateAllGroups(Repository repository, ObjectInserter inserter, BatchRefUpdate bru, Collection<GroupReference> groupReferences, PersonIdent ident) throws IOException {
    // Not strictly necessary for iteration; throws IAE if it encounters duplicates, which is nice.
    ImmutableBiMap<AccountGroup.UUID, String> biMap = toBiMap(groupReferences);
    try (ObjectReader reader = inserter.newReader();
        RevWalk rw = new RevWalk(reader)) {
        // Always start from an empty map, discarding old notes.
        NoteMap noteMap = NoteMap.newEmptyMap();
        Ref ref = repository.exactRef(RefNames.REFS_GROUPNAMES);
        RevCommit oldCommit = ref != null ? rw.parseCommit(ref.getObjectId()) : null;
        for (Map.Entry<AccountGroup.UUID, String> e : biMap.entrySet()) {
            AccountGroup.NameKey nameKey = AccountGroup.nameKey(e.getValue());
            ObjectId noteKey = getNoteKey(nameKey);
            noteMap.set(noteKey, getAsNoteData(e.getKey(), nameKey), inserter);
        }
        ObjectId newTreeId = noteMap.writeTree(inserter);
        if (oldCommit != null && newTreeId.equals(oldCommit.getTree())) {
            return;
        }
        CommitBuilder cb = new CommitBuilder();
        if (oldCommit != null) {
            cb.addParentId(oldCommit);
        }
        cb.setTreeId(newTreeId);
        cb.setAuthor(ident);
        cb.setCommitter(ident);
        int n = groupReferences.size();
        cb.setMessage("Store " + n + " group name" + (n != 1 ? "s" : ""));
        ObjectId newId = inserter.insert(cb).copy();
        ObjectId oldId = ObjectIds.copyOrZero(oldCommit);
        bru.addCommand(new ReceiveCommand(oldId, newId, RefNames.REFS_GROUPNAMES));
    }
}
Also used : ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand) ObjectId(org.eclipse.jgit.lib.ObjectId) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) NoteMap(org.eclipse.jgit.notes.NoteMap) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Ref(org.eclipse.jgit.lib.Ref) AccountGroup(com.google.gerrit.entities.AccountGroup) ObjectReader(org.eclipse.jgit.lib.ObjectReader) ImmutableBiMap(com.google.common.collect.ImmutableBiMap) Map(java.util.Map) NoteMap(org.eclipse.jgit.notes.NoteMap) ImmutableBiMap.toImmutableBiMap(com.google.common.collect.ImmutableBiMap.toImmutableBiMap) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 7 with NoteMap

use of org.eclipse.jgit.notes.NoteMap in project gerrit by GerritCodeReview.

the class NotesBranchUtil method commitNewNotes.

/**
 * Create a new commit in the {@code notesBranch} by creating not yet existing notes from the
 * {@code notes} map. The notes from the {@code notes} map which already exist in the note-tree of
 * the tip of the {@code notesBranch} will not be updated.
 *
 * <p>Does not retry in the case of lock failure; callers may use {@link
 * com.google.gerrit.server.update.RetryHelper}.
 *
 * @param notes map of notes
 * @param notesBranch notes branch to update
 * @param commitAuthor author of the commit in the notes branch
 * @param commitMessage for the commit in the notes branch
 * @return map with those notes from the {@code notes} that were newly created
 * @throws LockFailureException if committing the notes failed due to a lock failure on the notes
 *     branch
 * @throws IOException if committing the notes failed for any other reason
 */
public final NoteMap commitNewNotes(NoteMap notes, String notesBranch, PersonIdent commitAuthor, String commitMessage) throws IOException {
    this.overwrite = false;
    commitNotes(notes, notesBranch, commitAuthor, commitMessage);
    NoteMap newlyCreated = NoteMap.newEmptyMap();
    for (Note n : notes) {
        if (base == null || !base.contains(n)) {
            newlyCreated.set(n, n.getData());
        }
    }
    return newlyCreated;
}
Also used : Note(org.eclipse.jgit.notes.Note) NoteMap(org.eclipse.jgit.notes.NoteMap)

Example 8 with NoteMap

use of org.eclipse.jgit.notes.NoteMap in project gerrit by GerritCodeReview.

the class DeleteCommentRewriter method rewriteCommitHistory.

@Override
public ObjectId rewriteCommitHistory(RevWalk revWalk, ObjectInserter inserter, ObjectId currTip) throws IOException, ConfigInvalidException {
    checkArgument(!currTip.equals(ObjectId.zeroId()));
    // Walk from the first commit of the branch.
    revWalk.reset();
    revWalk.markStart(revWalk.parseCommit(currTip));
    revWalk.sort(RevSort.REVERSE);
    ObjectReader reader = revWalk.getObjectReader();
    // The first commit will not be rewritten.
    RevCommit newTipCommit = revWalk.next();
    Map<String, HumanComment> parentComments = getPublishedComments(noteUtil, reader, NoteMap.read(reader, newTipCommit));
    boolean rewrite = false;
    RevCommit originalCommit;
    while ((originalCommit = revWalk.next()) != null) {
        NoteMap noteMap = NoteMap.read(reader, originalCommit);
        Map<String, HumanComment> currComments = getPublishedComments(noteUtil, reader, noteMap);
        if (!rewrite && currComments.containsKey(uuid)) {
            rewrite = true;
        }
        if (!rewrite) {
            parentComments = currComments;
            newTipCommit = originalCommit;
            continue;
        }
        List<HumanComment> putInComments = getPutInComments(parentComments, currComments);
        List<HumanComment> deletedComments = getDeletedComments(parentComments, currComments);
        newTipCommit = revWalk.parseCommit(rewriteCommit(originalCommit, newTipCommit, inserter, reader, putInComments, deletedComments));
        parentComments = currComments;
    }
    return newTipCommit;
}
Also used : ObjectReader(org.eclipse.jgit.lib.ObjectReader) NoteMap(org.eclipse.jgit.notes.NoteMap) HumanComment(com.google.gerrit.entities.HumanComment) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 9 with NoteMap

use of org.eclipse.jgit.notes.NoteMap in project gerrit by GerritCodeReview.

the class ExternalIdsConsistencyChecker method check.

private List<ConsistencyProblemInfo> check(ExternalIdNotes extIdNotes) throws IOException {
    List<ConsistencyProblemInfo> problems = new ArrayList<>();
    ListMultimap<String, ExternalId> emails = MultimapBuilder.hashKeys().arrayListValues().build();
    try (RevWalk rw = new RevWalk(extIdNotes.getRepository())) {
        NoteMap noteMap = extIdNotes.getNoteMap();
        for (Note note : noteMap) {
            byte[] raw = ExternalIdNotes.readNoteData(rw, note.getData());
            try {
                ExternalId extId = externalIdFactory.parse(note.getName(), raw, note.getData());
                problems.addAll(validateExternalId(extId));
                if (extId.email() != null) {
                    String email = extId.email();
                    if (emails.get(email).stream().noneMatch(e -> e.accountId().get() == extId.accountId().get())) {
                        emails.put(email, extId);
                    }
                }
            } catch (ConfigInvalidException e) {
                addError(String.format(e.getMessage()), problems);
            }
        }
    }
    emails.asMap().entrySet().stream().filter(e -> e.getValue().size() > 1).forEach(e -> addError(String.format("Email '%s' is not unique, it's used by the following external IDs: %s", e.getKey(), e.getValue().stream().map(k -> "'" + k.key().get() + "'").sorted().collect(joining(", "))), problems));
    return problems;
}
Also used : AllUsersName(com.google.gerrit.server.config.AllUsersName) AccountCache(com.google.gerrit.server.account.AccountCache) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) OutgoingEmailValidator(com.google.gerrit.server.mail.send.OutgoingEmailValidator) Note(org.eclipse.jgit.notes.Note) ListMultimap(com.google.common.collect.ListMultimap) MultimapBuilder(com.google.common.collect.MultimapBuilder) Inject(com.google.inject.Inject) IOException(java.io.IOException) Collectors.joining(java.util.stream.Collectors.joining) ArrayList(java.util.ArrayList) ObjectId(org.eclipse.jgit.lib.ObjectId) RevWalk(org.eclipse.jgit.revwalk.RevWalk) List(java.util.List) GitRepositoryManager(com.google.gerrit.server.git.GitRepositoryManager) SCHEME_USERNAME(com.google.gerrit.server.account.externalids.ExternalId.SCHEME_USERNAME) ConsistencyProblemInfo(com.google.gerrit.extensions.api.config.ConsistencyCheckInfo.ConsistencyProblemInfo) HashedPassword(com.google.gerrit.server.account.HashedPassword) Repository(org.eclipse.jgit.lib.Repository) NoteMap(org.eclipse.jgit.notes.NoteMap) Singleton(com.google.inject.Singleton) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) Note(org.eclipse.jgit.notes.Note) ArrayList(java.util.ArrayList) ConsistencyProblemInfo(com.google.gerrit.extensions.api.config.ConsistencyCheckInfo.ConsistencyProblemInfo) NoteMap(org.eclipse.jgit.notes.NoteMap) RevWalk(org.eclipse.jgit.revwalk.RevWalk)

Example 10 with NoteMap

use of org.eclipse.jgit.notes.NoteMap 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.testing.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)

Aggregations

NoteMap (org.eclipse.jgit.notes.NoteMap)29 ObjectId (org.eclipse.jgit.lib.ObjectId)23 RevWalk (org.eclipse.jgit.revwalk.RevWalk)15 ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)11 Repository (org.eclipse.jgit.lib.Repository)9 Note (org.eclipse.jgit.notes.Note)9 IOException (java.io.IOException)8 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)7 ObjectReader (org.eclipse.jgit.lib.ObjectReader)6 RevCommit (org.eclipse.jgit.revwalk.RevCommit)6 Ref (org.eclipse.jgit.lib.Ref)5 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)4 ConsistencyProblemInfo (com.google.gerrit.extensions.api.config.ConsistencyCheckInfo.ConsistencyProblemInfo)3 AllUsersName (com.google.gerrit.server.config.AllUsersName)3 Inject (com.google.inject.Inject)3 Singleton (com.google.inject.Singleton)3 ListMultimap (com.google.common.collect.ListMultimap)2 MultimapBuilder (com.google.common.collect.MultimapBuilder)2 AccountGroup (com.google.gerrit.entities.AccountGroup)2 GroupReference (com.google.gerrit.entities.GroupReference)2