Example usage for org.eclipse.jgit.lib Repository newObjectInserter

List of usage examples for org.eclipse.jgit.lib Repository newObjectInserter

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository newObjectInserter.

Prototype

@NonNull
public ObjectInserter newObjectInserter() 

Source Link

Document

Create a new inserter to create objects in #getObjectDatabase() .

Usage

From source file:com.google.gerrit.acceptance.rest.account.ExternalIdIT.java

License:Apache License

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);/*from   w w  w.ja  v  a 2 s. c  o  m*/

        ExternalIdsUpdate.commit(repo, rw, ins, rev, noteMap, "Add external ID", admin.getIdent(),
                admin.getIdent());
        return noteId.getName();
    }
}

From source file:com.google.gerrit.pgm.init.AllProjectsConfig.java

License:Apache License

private void save(PersonIdent ident, String msg) throws IOException {
    File path = getPath();/*from   w w w . ja  v a 2s  .co  m*/
    if (path == null) {
        throw new IOException("All-Projects does not exist.");
    }

    Repository repo = new FileRepository(path);
    try {
        inserter = repo.newObjectInserter();
        reader = repo.newObjectReader();
        try {
            RevWalk rw = new RevWalk(reader);
            try {
                RevTree srcTree = revision != null ? rw.parseTree(revision) : null;
                newTree = readTree(srcTree);
                saveConfig(ProjectConfig.PROJECT_CONFIG, cfg);
                ObjectId res = newTree.writeTree(inserter);
                if (res.equals(srcTree)) {
                    // If there are no changes to the content, don't create the commit.
                    return;
                }

                CommitBuilder commit = new CommitBuilder();
                commit.setAuthor(ident);
                commit.setCommitter(ident);
                commit.setMessage(msg);
                commit.setTreeId(res);
                if (revision != null) {
                    commit.addParentId(revision);
                }
                ObjectId newRevision = inserter.insert(commit);
                updateRef(repo, ident, newRevision, "commit: " + msg);
                revision = newRevision;
            } finally {
                rw.release();
            }
        } finally {
            if (inserter != null) {
                inserter.release();
                inserter = null;
            }
            if (reader != null) {
                reader.release();
                reader = null;
            }
        }
    } finally {
        repo.close();
    }
}

From source file:com.google.gerrit.server.change.CreateChange.java

License:Apache License

private static RevCommit newCommit(Repository git, RevWalk rw, PersonIdent authorIdent, RevCommit mergeTip,
        String commitMessage) throws IOException {
    RevCommit emptyCommit;/*from ww w .j a  v a2 s.com*/
    try (ObjectInserter oi = git.newObjectInserter()) {
        CommitBuilder commit = new CommitBuilder();
        commit.setTreeId(mergeTip.getTree().getId());
        commit.setParentId(mergeTip);
        commit.setAuthor(authorIdent);
        commit.setCommitter(authorIdent);
        commit.setMessage(commitMessage);
        emptyCommit = rw.parseCommit(insert(oi, commit));
    }
    return emptyCommit;
}

From source file:com.google.gerrit.server.change.RebaseChange.java

License:Apache License

/**
 * Rebase the change of the given patch set.
 * <p>//  ww  w . j a  va2s . c o  m
 * If the patch set has no dependency to an open change, then the change is
 * rebased on the tip of the destination branch.
 * <p>
 * If the patch set depends on an open change, it is rebased on the latest
 * patch set of this change.
 * <p>
 * The rebased commit is added as new patch set to the change.
 * <p>
 * E-mail notification and triggering of hooks happens for the creation of the
 * new patch set.
 *
 * @param git the repository.
 * @param rw the RevWalk.
 * @param rsrc revision to rebase.
 * @param newBaseRev the commit that should be the new base.
 * @throws NoSuchChangeException if the change to which the patch set belongs
 *     does not exist or is not visible to the user.
 * @throws EmailException if sending the e-mail to notify about the new patch
 *     set fails.
 * @throws OrmException if accessing the database fails.
 * @throws IOException if accessing the repository fails.
 * @throws InvalidChangeOperationException if rebase is not possible or not
 *     allowed.
 */
public void rebase(Repository git, RevWalk rw, RevisionResource rsrc, String newBaseRev)
        throws NoSuchChangeException, EmailException, OrmException, IOException, ResourceConflictException,
        InvalidChangeOperationException {
    Change change = rsrc.getChange();
    PatchSet patchSet = rsrc.getPatchSet();
    IdentifiedUser uploader = (IdentifiedUser) rsrc.getControl().getCurrentUser();

    try (ObjectInserter inserter = git.newObjectInserter()) {
        String baseRev = newBaseRev;
        if (baseRev == null) {
            baseRev = findBaseRevision(patchSet, change.getDest(), git, rw);
        }

        ObjectId baseObjectId = git.resolve(baseRev);
        if (baseObjectId == null) {
            throw new InvalidChangeOperationException("Cannot rebase: Failed to resolve baseRev: " + baseRev);
        }

        RevCommit baseCommit = rw.parseCommit(baseObjectId);
        PersonIdent committerIdent = uploader.newCommitterIdent(TimeUtil.nowTs(), serverTimeZone);

        rebase(git, rw, inserter, change, patchSet.getId(), uploader, baseCommit,
                mergeUtilFactory.create(rsrc.getControl().getProjectControl().getProjectState(), true),
                committerIdent, true, ValidatePolicy.GERRIT);
    } catch (MergeConflictException e) {
        throw new ResourceConflictException(e.getMessage());
    }
}

From source file:com.google.gerrit.server.changedetail.RebaseChange.java

License:Apache License

/**
 * Rebases the change of the given patch set.
 *
 * It is verified that the current user is allowed to do the rebase.
 *
 * If the patch set has no dependency to an open change, then the change is
 * rebased on the tip of the destination branch.
 *
 * If the patch set depends on an open change, it is rebased on the latest
 * patch set of this change./*from  ww  w  .j a  v a  2  s .  c  o  m*/
 *
 * The rebased commit is added as new patch set to the change.
 *
 * E-mail notification and triggering of hooks happens for the creation of the
 * new patch set.
 *
 * @param change the change to perform the rebase for
 * @param patchSetId the id of the patch set
 * @param uploader the user that creates the rebased patch set
 * @param newBaseRev the commit that should be the new base
 * @throws NoSuchChangeException thrown if the change to which the patch set
 *         belongs does not exist or is not visible to the user
 * @throws EmailException thrown if sending the e-mail to notify about the new
 *         patch set fails
 * @throws OrmException thrown in case accessing the database fails
 * @throws IOException thrown if rebase is not possible or not needed
 * @throws InvalidChangeOperationException thrown if rebase is not allowed
 */
public void rebase(Change change, PatchSet.Id patchSetId, final IdentifiedUser uploader,
        final String newBaseRev) throws NoSuchChangeException, EmailException, OrmException, IOException,
        InvalidChangeOperationException {
    final Change.Id changeId = patchSetId.getParentKey();
    final ChangeControl changeControl = changeControlFactory.validateFor(change, uploader);
    if (!changeControl.canRebase()) {
        throw new InvalidChangeOperationException(
                "Cannot rebase: New patch sets are not allowed to be added to change: " + changeId.toString());
    }
    Repository git = null;
    RevWalk rw = null;
    ObjectInserter inserter = null;
    try {
        git = gitManager.openRepository(change.getProject());
        rw = new RevWalk(git);
        inserter = git.newObjectInserter();

        String baseRev = newBaseRev;
        if (baseRev == null) {
            baseRev = findBaseRevision(patchSetId, db.get(), change.getDest(), git, null, null, null);
        }
        ObjectId baseObjectId = git.resolve(baseRev);
        if (baseObjectId == null) {
            throw new InvalidChangeOperationException("Cannot rebase: Failed to resolve baseRev: " + baseRev);
        }
        final RevCommit baseCommit = rw.parseCommit(baseObjectId);

        PersonIdent committerIdent = uploader.newCommitterIdent(TimeUtil.nowTs(), serverTimeZone);

        rebase(git, rw, inserter, patchSetId, change, uploader, baseCommit,
                mergeUtilFactory.create(changeControl.getProjectControl().getProjectState(), true),
                committerIdent, true, ValidatePolicy.GERRIT);
    } catch (MergeConflictException e) {
        throw new IOException(e.getMessage());
    } finally {
        if (inserter != null) {
            inserter.release();
        }
        if (rw != null) {
            rw.release();
        }
        if (git != null) {
            git.close();
        }
    }
}

From source file:com.google.gerrit.server.edit.tree.TreeCreator.java

License:Apache License

private static ObjectId writeAndGetId(Repository repository, DirCache tree) throws IOException {
    try (ObjectInserter objectInserter = repository.newObjectInserter()) {
        ObjectId treeId = tree.writeTree(objectInserter);
        objectInserter.flush();/*from ww w .j a va2  s .  c  om*/
        return treeId;
    }
}

From source file:com.google.gerrit.server.git.CreateCodeReviewNotes.java

License:Apache License

@Inject
CreateCodeReviewNotes(@GerritPersonIdent final PersonIdent gerritIdent, final AccountCache accountCache,
        final ApprovalTypes approvalTypes, @Nullable @CanonicalWebUrl final String canonicalWebUrl,
        @Assisted ReviewDb reviewDb, @Assisted final Repository db) {
    schema = reviewDb;/*from   ww  w .  j av a 2  s. c  om*/
    this.author = gerritIdent;
    this.gerritIdent = gerritIdent;
    this.accountCache = accountCache;
    this.approvalTypes = approvalTypes;
    this.canonicalWebUrl = canonicalWebUrl;
    this.db = db;

    revWalk = new RevWalk(db);
    inserter = db.newObjectInserter();
    reader = db.newObjectReader();
}

From source file:com.google.gerrit.server.git.MergeUtil.java

License:Apache License

public static ObjectInserter createDryRunInserter(Repository db) {
    final ObjectInserter delegate = db.newObjectInserter();
    return new ObjectInserter.Filter() {
        @Override/*w  w w  .  ja va 2s .c  o  m*/
        protected ObjectInserter delegate() {
            return delegate;
        }

        @Override
        public PackParser newPackParser(InputStream in) throws IOException {
            throw new UnsupportedOperationException();
        }

        @Override
        public void flush() throws IOException {
            // Do nothing.
        }
    };
}

From source file:com.google.gerrit.server.git.SubmoduleOpTest.java

License:Apache License

/**
 * It creates and adds a regular file to git index of a repository.
 *
 * @param fileName The file name.// w  w w. j  a v  a 2 s.  co m
 * @param content File content.
 * @param repository The Repository instance.
 * @throws IOException If an I/O exception occurs.
 */
private void addRegularFileToIndex(final String fileName, final String content, final Repository repository)
        throws IOException {
    final ObjectInserter oi = repository.newObjectInserter();
    AnyObjectId objectId = oi.insert(Constants.OBJ_BLOB, Constants.encode(content));
    oi.flush();
    addEntryToIndex(fileName, FileMode.REGULAR_FILE, objectId, repository);
}

From source file:com.google.gerrit.server.git.VersionedMetaData.java

License:Apache License

/**
 * Open a batch of updates to the same metadata ref.
 * <p>/*from w  w w.j ava 2s.  c o  m*/
 * 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;
            }

            // Reuse tree from parent commit unless there are contents in newTree or
            // there is no tree for a parent commit.
            ObjectId res = newTree.getEntryCount() != 0 || srcTree == null ? newTree.writeTree(inserter)
                    : srcTree.copy();
            if (res.equals(srcTree) && !update.allowEmpty() && (commit.getTreeId() == null)) {
                // If there are no changes to the content, don't create the commit.
                return;
            }

            // If changes are made to the DirCache and those changes are written as
            // a commit and then the tree ID is set for the CommitBuilder, then
            // those previous DirCache changes will be ignored and the commit's
            // tree will be replaced with the ID in the CommitBuilder. The same is
            // true if you explicitly set tree ID in a commit and then make changes
            // to the DirCache; that tree ID will be ignored and replaced by that of
            // 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;
            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;
            default:
                throw new IOException(
                        "Cannot update " + ru.getName() + " in " + db.getDirectory() + ": " + ru.getResult());
            }
        }
    };
}