Search in sources :

Example 36 with ObjectInserter

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

the class ExternalIdIT method insertExternalIdWithoutAccountId.

private String insertExternalIdWithoutAccountId(Repository repo, RevWalk rw, String externalId) throws IOException {
    ObjectId rev = ExternalIdReader.readRevision(repo);
    NoteMap noteMap = ExternalIdReader.readNoteMap(rw, rev);
    ExternalId extId = ExternalId.create(ExternalId.Key.parse(externalId), admin.id);
    try (ObjectInserter ins = repo.newObjectInserter()) {
        ObjectId noteId = extId.key().sha1();
        Config c = new Config();
        extId.writeToConfig(c);
        c.unset("externalId", extId.key().get(), "accountId");
        byte[] raw = c.toText().getBytes(UTF_8);
        ObjectId dataBlob = ins.insert(OBJ_BLOB, raw);
        noteMap.set(noteId, dataBlob);
        ExternalIdsUpdate.commit(repo, rw, ins, rev, noteMap, "Add external ID", admin.getIdent(), admin.getIdent());
        return noteId.getName();
    }
}
Also used : ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) ObjectId(org.eclipse.jgit.lib.ObjectId) Config(org.eclipse.jgit.lib.Config) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) NoteMap(org.eclipse.jgit.notes.NoteMap)

Example 37 with ObjectInserter

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

the class ExternalIdIT method insertExternalIdWithEmptyNote.

private String insertExternalIdWithEmptyNote(Repository repo, RevWalk rw, String externalId) throws IOException {
    ObjectId rev = ExternalIdReader.readRevision(repo);
    NoteMap noteMap = ExternalIdReader.readNoteMap(rw, rev);
    try (ObjectInserter ins = repo.newObjectInserter()) {
        ObjectId noteId = ExternalId.Key.parse(externalId).sha1();
        byte[] raw = "".getBytes(UTF_8);
        ObjectId dataBlob = ins.insert(OBJ_BLOB, raw);
        noteMap.set(noteId, dataBlob);
        ExternalIdsUpdate.commit(repo, rw, ins, rev, noteMap, "Add external ID", admin.getIdent(), admin.getIdent());
        return noteId.getName();
    }
}
Also used : ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) ObjectId(org.eclipse.jgit.lib.ObjectId) NoteMap(org.eclipse.jgit.notes.NoteMap)

Example 38 with ObjectInserter

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

the class PublicKeyStore method save.

/**
   * Save pending keys to the store.
   *
   * <p>One commit is created and the ref updated. The pending list is cleared if and only if the
   * ref update succeeds, which allows for easy retries in case of lock failure.
   *
   * @param cb commit builder with at least author and identity populated; tree and parent are
   *     ignored.
   * @return result of the ref update.
   */
public RefUpdate.Result save(CommitBuilder cb) throws PGPException, IOException {
    if (toAdd.isEmpty() && toRemove.isEmpty()) {
        return RefUpdate.Result.NO_CHANGE;
    }
    if (reader == null) {
        load();
    }
    if (notes == null) {
        notes = NoteMap.newEmptyMap();
    }
    ObjectId newTip;
    try (ObjectInserter ins = repo.newObjectInserter()) {
        for (PGPPublicKeyRing keyRing : toAdd.values()) {
            saveToNotes(ins, keyRing);
        }
        for (Fingerprint fp : toRemove) {
            deleteFromNotes(ins, fp);
        }
        cb.setTreeId(notes.writeTree(ins));
        if (cb.getTreeId().equals(tip != null ? tip.getTree() : EMPTY_TREE)) {
            return RefUpdate.Result.NO_CHANGE;
        }
        if (tip != null) {
            cb.setParentId(tip);
        }
        if (cb.getMessage() == null) {
            int n = toAdd.size() + toRemove.size();
            cb.setMessage(String.format("Update %d public key%s", n, n != 1 ? "s" : ""));
        }
        newTip = ins.insert(cb);
        ins.flush();
    }
    RefUpdate ru = repo.updateRef(PublicKeyStore.REFS_GPG_KEYS);
    ru.setExpectedOldObjectId(tip);
    ru.setNewObjectId(newTip);
    ru.setRefLogIdent(cb.getCommitter());
    ru.setRefLogMessage("Store public keys", true);
    RefUpdate.Result result = ru.update();
    reset();
    switch(result) {
        case FAST_FORWARD:
        case NEW:
        case NO_CHANGE:
            toAdd.clear();
            toRemove.clear();
            break;
        case FORCED:
        case IO_FAILURE:
        case LOCK_FAILURE:
        case NOT_ATTEMPTED:
        case REJECTED:
        case REJECTED_CURRENT_BRANCH:
        case RENAMED:
        default:
            break;
    }
    return result;
}
Also used : PGPPublicKeyRing(org.bouncycastle.openpgp.PGPPublicKeyRing) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) ObjectId(org.eclipse.jgit.lib.ObjectId) RefUpdate(org.eclipse.jgit.lib.RefUpdate)

Example 39 with ObjectInserter

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

the class ExternalIdsUpdate method updateNoteMap.

private RefsMetaExternalIdsUpdate updateNoteMap(MyConsumer<OpenRepo> update) throws IOException, ConfigInvalidException, OrmException {
    try {
        return retryer.call(() -> {
            try (Repository repo = repoManager.openRepository(allUsersName);
                ObjectInserter ins = repo.newObjectInserter()) {
                ObjectId rev = readRevision(repo);
                afterReadRevision.run();
                try (RevWalk rw = new RevWalk(repo)) {
                    NoteMap noteMap = readNoteMap(rw, rev);
                    update.accept(OpenRepo.create(repo, rw, ins, noteMap));
                    return commit(repo, rw, ins, rev, noteMap);
                }
            }
        });
    } catch (ExecutionException | RetryException e) {
        if (e.getCause() != null) {
            Throwables.throwIfInstanceOf(e.getCause(), IOException.class);
            Throwables.throwIfInstanceOf(e.getCause(), ConfigInvalidException.class);
            Throwables.throwIfInstanceOf(e.getCause(), OrmException.class);
        }
        throw new OrmException(e);
    }
}
Also used : Repository(org.eclipse.jgit.lib.Repository) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) ObjectId(org.eclipse.jgit.lib.ObjectId) OrmException(com.google.gwtorm.server.OrmException) NoteMap(org.eclipse.jgit.notes.NoteMap) ExternalIdReader.readNoteMap(com.google.gerrit.server.account.externalids.ExternalIdReader.readNoteMap) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) ExecutionException(java.util.concurrent.ExecutionException) RetryException(com.github.rholder.retry.RetryException)

Example 40 with ObjectInserter

use of org.eclipse.jgit.lib.ObjectInserter 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)

Aggregations

ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)58 ObjectId (org.eclipse.jgit.lib.ObjectId)40 RevWalk (org.eclipse.jgit.revwalk.RevWalk)32 Repository (org.eclipse.jgit.lib.Repository)26 IOException (java.io.IOException)19 RevCommit (org.eclipse.jgit.revwalk.RevCommit)17 ObjectReader (org.eclipse.jgit.lib.ObjectReader)16 Change (com.google.gerrit.reviewdb.client.Change)13 PersonIdent (org.eclipse.jgit.lib.PersonIdent)13 CommitBuilder (org.eclipse.jgit.lib.CommitBuilder)12 RefUpdate (org.eclipse.jgit.lib.RefUpdate)12 NoteMap (org.eclipse.jgit.notes.NoteMap)12 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)10 OrmException (com.google.gwtorm.server.OrmException)8 DirCache (org.eclipse.jgit.dircache.DirCache)8 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)7 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)6 Project (com.google.gerrit.reviewdb.client.Project)6 ChangeControl (com.google.gerrit.server.project.ChangeControl)6 DirCacheEntry (org.eclipse.jgit.dircache.DirCacheEntry)6