Example usage for org.eclipse.jgit.lib RefUpdate setRefLogMessage

List of usage examples for org.eclipse.jgit.lib RefUpdate setRefLogMessage

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib RefUpdate setRefLogMessage.

Prototype

public void setRefLogMessage(String msg, boolean appendStatus) 

Source Link

Document

Set the message to include in the reflog.

Usage

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

License:Apache License

/**
 * Open a batch of updates to the same metadata ref.
 * <p>//w w w .  j  a v  a 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());
            }
        }
    };
}

From source file:com.google.gerrit.server.notedb.ChangeDelete.java

License:Apache License

public void delete() throws OrmException, IOException {
    plcUtil.deleteAllDraftsFromAllUsers(notes.getChangeId());

    RefUpdate ru = repo.updateRef(notes.getRefName());
    ru.setExpectedOldObjectId(notes.load().getRevision());
    ru.setNewObjectId(ObjectId.zeroId());
    ru.setForceUpdate(true);//from w ww. j  a  v a2 s  .co  m
    ru.setRefLogMessage("Delete change from NoteDb", false);
    RefUpdate.Result result = ru.delete();
    switch (result) {
    case FAST_FORWARD:
    case FORCED:
    case NO_CHANGE:
        break;

    case IO_FAILURE:
    case LOCK_FAILURE:
    case NEW:
    case NOT_ATTEMPTED:
    case REJECTED:
    case REJECTED_CURRENT_BRANCH:
    case RENAMED:
    default:
        throw new IOException(String.format("Failed to delete change ref %s at %s: %s", notes.getRefName(),
                notes.getRevision(), result));
    }
}

From source file:com.google.gerrit.server.project.CreateBranch.java

License:Apache License

@Override
public BranchInfo apply(ProjectResource rsrc, Input input)
        throws BadRequestException, AuthException, ResourceConflictException, IOException {
    if (input == null) {
        input = new Input();
    }//from www  .  j  av a  2s  .c o  m
    if (input.ref != null && !ref.equals(input.ref)) {
        throw new BadRequestException("ref must match URL");
    }
    if (input.revision == null) {
        input.revision = Constants.HEAD;
    }
    while (ref.startsWith("/")) {
        ref = ref.substring(1);
    }
    ref = RefNames.fullName(ref);
    if (!Repository.isValidRefName(ref)) {
        throw new BadRequestException("invalid branch name \"" + ref + "\"");
    }
    if (MagicBranch.isMagicBranch(ref)) {
        throw new BadRequestException(
                "not allowed to create branches under \"" + MagicBranch.getMagicRefNamePrefix(ref) + "\"");
    }

    final Branch.NameKey name = new Branch.NameKey(rsrc.getNameKey(), ref);
    final RefControl refControl = rsrc.getControl().controlForRef(name);
    try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) {
        final ObjectId revid = parseBaseRevision(repo, rsrc.getNameKey(), input.revision);
        final RevWalk rw = verifyConnected(repo, revid);
        RevObject object = rw.parseAny(revid);

        if (ref.startsWith(Constants.R_HEADS)) {
            // Ensure that what we start the branch from is a commit. If we
            // were given a tag, deference to the commit instead.
            //
            try {
                object = rw.parseCommit(object);
            } catch (IncorrectObjectTypeException notCommit) {
                throw new BadRequestException("\"" + input.revision + "\" not a commit");
            }
        }

        rw.reset();
        if (!refControl.canCreate(db.get(), rw, object)) {
            throw new AuthException("Cannot create \"" + ref + "\"");
        }

        try {
            final RefUpdate u = repo.updateRef(ref);
            u.setExpectedOldObjectId(ObjectId.zeroId());
            u.setNewObjectId(object.copy());
            u.setRefLogIdent(identifiedUser.get().newRefLogIdent());
            u.setRefLogMessage("created via REST from " + input.revision, false);
            final RefUpdate.Result result = u.update(rw);
            switch (result) {
            case FAST_FORWARD:
            case NEW:
            case NO_CHANGE:
                referenceUpdated.fire(name.getParentKey(), u, ReceiveCommand.Type.CREATE);
                hooks.doRefUpdatedHook(name, u, identifiedUser.get().getAccount());
                break;
            case LOCK_FAILURE:
                if (repo.getRefDatabase().exactRef(ref) != null) {
                    throw new ResourceConflictException("branch \"" + ref + "\" already exists");
                }
                String refPrefix = getRefPrefix(ref);
                while (!Constants.R_HEADS.equals(refPrefix)) {
                    if (repo.getRefDatabase().exactRef(refPrefix) != null) {
                        throw new ResourceConflictException("Cannot create branch \"" + ref
                                + "\" since it conflicts with branch \"" + refPrefix + "\".");
                    }
                    refPrefix = getRefPrefix(refPrefix);
                }
                //$FALL-THROUGH$
            default: {
                throw new IOException(result.name());
            }
            }

            BranchInfo info = new BranchInfo();
            info.ref = ref;
            info.revision = revid.getName();
            info.canDelete = refControl.canDelete() ? true : null;
            return info;
        } catch (IOException err) {
            log.error("Cannot create branch \"" + name + "\"", err);
            throw err;
        }
    } catch (InvalidRevisionException e) {
        throw new BadRequestException("invalid revision \"" + input.revision + "\"");
    }
}

From source file:com.google.gerrit.server.schema.Schema_146.java

License:Apache License

private void rewriteUserBranch(Repository repo, RevWalk rw, ObjectInserter oi, ObjectId emptyTree, Ref ref,
        Account account) throws IOException {
    ObjectId current = createInitialEmptyCommit(oi, emptyTree, account.getRegisteredOn());

    rw.reset();//  w  ww  .  java  2 s. c  o m
    rw.sort(RevSort.TOPO);
    rw.sort(RevSort.REVERSE, true);
    rw.markStart(rw.parseCommit(ref.getObjectId()));

    RevCommit c;
    while ((c = rw.next()) != null) {
        if (isInitialEmptyCommit(emptyTree, c)) {
            return;
        }

        CommitBuilder cb = new CommitBuilder();
        cb.setParentId(current);
        cb.setTreeId(c.getTree());
        cb.setAuthor(c.getAuthorIdent());
        cb.setCommitter(c.getCommitterIdent());
        cb.setMessage(c.getFullMessage());
        cb.setEncoding(c.getEncoding());
        current = oi.insert(cb);
    }

    oi.flush();

    RefUpdate ru = repo.updateRef(ref.getName());
    ru.setExpectedOldObjectId(ref.getObjectId());
    ru.setNewObjectId(current);
    ru.setForceUpdate(true);
    ru.setRefLogIdent(serverIdent);
    ru.setRefLogMessage(getClass().getSimpleName(), true);
    Result result = ru.update();
    if (result != Result.FORCED) {
        throw new IOException(String.format("Failed to update ref %s: %s", ref.getName(), result.name()));
    }
}

From source file:com.google.gerrit.server.StarredChangesUtil.java

License:Apache License

public void unstar(Account.Id accountId, Project.NameKey project, Change.Id changeId) throws OrmException {
    try (Repository repo = repoManager.openRepository(allUsers); RevWalk rw = new RevWalk(repo)) {
        RefUpdate u = repo.updateRef(RefNames.refsStarredChanges(changeId, accountId));
        u.setForceUpdate(true);//from ww  w .j  a  va  2s.  c o  m
        u.setRefLogIdent(serverIdent);
        u.setRefLogMessage("Unstar change " + changeId.get(), true);
        RefUpdate.Result result = u.delete();
        switch (result) {
        case FORCED:
            indexer.index(dbProvider.get(), project, changeId);
            return;
        case FAST_FORWARD:
        case IO_FAILURE:
        case LOCK_FAILURE:
        case NEW:
        case NOT_ATTEMPTED:
        case NO_CHANGE:
        case REJECTED:
        case REJECTED_CURRENT_BRANCH:
        case RENAMED:
        default:
            throw new OrmException(String.format("Unstar change %d for account %d failed: %s", changeId.get(),
                    accountId.get(), result.name()));
        }
    } catch (IOException e) {
        throw new OrmException(
                String.format("Unstar change %d for account %d failed", changeId.get(), accountId.get()), e);
    }
}

From source file:com.google.gerrit.server.StarredChangesUtil.java

License:Apache License

private void updateLabels(Repository repo, String refName, ObjectId oldObjectId, SortedSet<String> labels)
        throws IOException, OrmException {
    try (RevWalk rw = new RevWalk(repo)) {
        RefUpdate u = repo.updateRef(refName);
        u.setExpectedOldObjectId(oldObjectId);
        u.setForceUpdate(true);//www.j av a2s . co m
        u.setNewObjectId(writeLabels(repo, labels));
        u.setRefLogIdent(serverIdent);
        u.setRefLogMessage("Update star labels", true);
        RefUpdate.Result result = u.update(rw);
        switch (result) {
        case NEW:
        case FORCED:
        case NO_CHANGE:
        case FAST_FORWARD:
            return;
        case IO_FAILURE:
        case LOCK_FAILURE:
        case NOT_ATTEMPTED:
        case REJECTED:
        case REJECTED_CURRENT_BRANCH:
        case RENAMED:
            throw new OrmException(
                    String.format("Update star labels on ref %s failed: %s", refName, result.name()));
        }
    }
}

From source file:com.googlesource.gerrit.plugins.refprotection.BackupRef.java

License:Open Source License

public void createBackup(RefUpdatedEvent event, ProjectResource project) {
    String refName = event.getRefName();

    try (Repository git = repoManager.openRepository(project.getNameKey())) {
        String backupRef = get(project, refName);

        // No-op if the backup branch name is same as the original
        if (backupRef.equals(refName)) {
            return;
        }/*  w w w. ja v  a  2 s.  c  om*/

        try (RevWalk revWalk = new RevWalk(git)) {
            RefUpdateAttribute refUpdate = event.refUpdate.get();
            if (cfg.getFromGerritConfig(pluginName).getBoolean("createTag", false)) {
                TagBuilder tag = new TagBuilder();
                AccountAttribute submitter = event.submitter.get();
                tag.setTagger(new PersonIdent(submitter.name, submitter.email));
                tag.setObjectId(revWalk.parseCommit(ObjectId.fromString(refUpdate.oldRev)));
                String update = "Non-fast-forward update to";
                if (refUpdate.newRev.equals(ObjectId.zeroId().getName())) {
                    update = "Deleted";
                }
                String type = "branch";
                String fullMessage = "";
                if (refUpdate.refName.startsWith(R_TAGS)) {
                    type = "tag";
                    try {
                        RevTag origTag = revWalk.parseTag(ObjectId.fromString(refUpdate.oldRev));
                        SimpleDateFormat format = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy ZZZZ");
                        PersonIdent taggerIdent = origTag.getTaggerIdent();
                        String tagger = String.format("Tagger: %s <%s>\nDate:   %s", taggerIdent.getName(),
                                taggerIdent.getEmailAddress(), format.format(taggerIdent.getWhen()));
                        fullMessage = "\n\nOriginal tag:\n" + tagger + "\n\n" + origTag.getFullMessage();
                    } catch (MissingObjectException e) {
                        log.warn("Original tag does not exist", e);
                    } catch (IncorrectObjectTypeException e) {
                        log.warn("Original tag was not a tag", e);
                    } catch (IOException e) {
                        log.warn("Unable to read original tag details", e);
                    }
                }
                tag.setMessage(update + " " + type + " " + refUpdate.refName + fullMessage);
                tag.setTag(backupRef);

                ObjectInserter inserter = git.newObjectInserter();
                ObjectId tagId = inserter.insert(tag);
                inserter.flush();
                RefUpdate tagRef = git.updateRef(tag.getTag());
                tagRef.setNewObjectId(tagId);
                tagRef.setRefLogMessage("tagged deleted branch/tag " + tag.getTag(), false);
                tagRef.setForceUpdate(false);
                Result result = tagRef.update();
                switch (result) {
                case NEW:
                case FORCED:
                    log.debug("Successfully created backup tag");
                    break;

                case LOCK_FAILURE:
                    log.error("Failed to lock repository while creating backup tag");
                    break;

                case REJECTED:
                    log.error("Tag already exists while creating backup tag");
                    break;

                default:
                    log.error("Unknown error while creating backup tag");
                }
            } else {
                BranchInput input = new BranchInput();
                input.ref = backupRef;
                // We need to parse the commit to ensure if it's a tag, we get the
                // commit the tag points to!
                input.revision = ObjectId
                        .toString(revWalk.parseCommit(ObjectId.fromString(refUpdate.oldRev)).getId());

                try {
                    createBranchFactory.create(backupRef).apply(project, input);
                } catch (BadRequestException | AuthException | ResourceConflictException | IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    } catch (RepositoryNotFoundException e) {
        log.error("Repository does not exist", e);
    } catch (IOException e) {
        log.error("Could not open repository", e);
    }
}

From source file:com.mangosolutions.rcloud.rawgist.repository.git.BareCommitCommand.java

/**
 * Executes the {@code commit} command with all the options and parameters
 * collected by the setter methods of this class. Each instance of this
 * class should only be used for one invocation of the command (means: one
 * call to {@link #call()})//  w  w w.  j a  va2  s  .  c  om
 *
 * @return a {@link RevCommit} object representing the successful commit.
 * @throws NoHeadException
 *             when called on a git repo without a HEAD reference
 * @throws NoMessageException
 *             when called without specifying a commit message
 * @throws UnmergedPathsException
 *             when the current index contained unmerged paths (conflicts)
 * @throws ConcurrentRefUpdateException
 *             when HEAD or branch ref is updated concurrently by someone
 *             else
 * @throws WrongRepositoryStateException
 *             when repository is not in the right state for committing
 * @throws AbortedByHookException
 *             if there are either pre-commit or commit-msg hooks present in
 *             the repository and one of them rejects the commit.
 */
public RevCommit call() throws GitAPIException, NoHeadException, NoMessageException, UnmergedPathsException,
        ConcurrentRefUpdateException, WrongRepositoryStateException, AbortedByHookException {
    checkCallable();
    Collections.sort(only);

    try (RevWalk rw = new RevWalk(repo)) {
        RepositoryState state = repo.getRepositoryState();

        if (!noVerify) {
            Hooks.preCommit(repo, hookOutRedirect).call();
        }

        processOptions(state, rw);

        if (all && !repo.isBare()) {
            try (Git git = new Git(repo)) {
                git.add().addFilepattern(".") //$NON-NLS-1$
                        .setUpdate(true).call();
            } catch (NoFilepatternException e) {
                // should really not happen
                throw new JGitInternalException(e.getMessage(), e);
            }
        }

        Ref head = repo.findRef(Constants.HEAD);
        if (head == null) {
            throw new NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
        }

        // determine the current HEAD and the commit it is referring to
        ObjectId headId = repo.resolve(Constants.HEAD + "^{commit}"); //$NON-NLS-1$
        if (headId == null && amend)
            throw new WrongRepositoryStateException(JGitText.get().commitAmendOnInitialNotPossible);

        if (headId != null) {
            if (amend) {
                RevCommit previousCommit = rw.parseCommit(headId);
                for (RevCommit p : previousCommit.getParents())
                    parents.add(p.getId());
                if (author == null)
                    author = previousCommit.getAuthorIdent();
            } else {
                parents.add(0, headId);
            }
        }
        if (!noVerify) {
            message = Hooks.commitMsg(repo, hookOutRedirect).setCommitMessage(message).call();
        }

        // lock the index
        //         DirCache index = repo.lockDirCache();
        index.lock();
        try (ObjectInserter odi = repo.newObjectInserter()) {
            if (!only.isEmpty())
                index = createTemporaryIndex(headId, index, rw);

            // Write the index as tree to the object database. This may
            // fail for example when the index contains unmerged paths
            // (unresolved conflicts)
            ObjectId indexTreeId = index.writeTree(odi);

            if (insertChangeId)
                insertChangeId(indexTreeId);

            // Check for empty commits
            if (headId != null && !allowEmpty.booleanValue()) {
                RevCommit headCommit = rw.parseCommit(headId);
                headCommit.getTree();
                if (indexTreeId.equals(headCommit.getTree())) {
                    return null;
                }
            }

            // Create a Commit object, populate it and write it
            CommitBuilder commit = new CommitBuilder();
            commit.setCommitter(committer);
            commit.setAuthor(author);
            commit.setMessage(message);

            commit.setParentIds(parents);
            commit.setTreeId(indexTreeId);
            ObjectId commitId = odi.insert(commit);
            odi.flush();

            RevCommit revCommit = rw.parseCommit(commitId);
            RefUpdate ru = repo.updateRef(Constants.HEAD);
            ru.setNewObjectId(commitId);
            if (reflogComment != null) {
                ru.setRefLogMessage(reflogComment, false);
            } else {
                String prefix = amend ? "commit (amend): " //$NON-NLS-1$
                        : parents.size() == 0 ? "commit (initial): " //$NON-NLS-1$
                                : "commit: "; //$NON-NLS-1$
                ru.setRefLogMessage(prefix + revCommit.getShortMessage(), false);
            }
            if (headId != null) {
                ru.setExpectedOldObjectId(headId);
            } else {
                ru.setExpectedOldObjectId(ObjectId.zeroId());
            }
            Result rc = ru.forceUpdate();
            switch (rc) {
            case NEW:
            case FORCED:
            case FAST_FORWARD: {
                setCallable(false);
                if (state == RepositoryState.MERGING_RESOLVED || isMergeDuringRebase(state)) {
                    // Commit was successful. Now delete the files
                    // used for merge commits
                    repo.writeMergeCommitMsg(null);
                    repo.writeMergeHeads(null);
                } else if (state == RepositoryState.CHERRY_PICKING_RESOLVED) {
                    repo.writeMergeCommitMsg(null);
                    repo.writeCherryPickHead(null);
                } else if (state == RepositoryState.REVERTING_RESOLVED) {
                    repo.writeMergeCommitMsg(null);
                    repo.writeRevertHead(null);
                }
                return revCommit;
            }
            case REJECTED:
            case LOCK_FAILURE:
                throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
            default:
                throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed,
                        Constants.HEAD, commitId.toString(), rc));
            }
        } finally {
            index.unlock();
        }
    } catch (UnmergedPathException e) {
        throw new UnmergedPathsException(e);
    } catch (IOException e) {
        throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfCommitCommand, e);
    }
}

From source file:com.microsoft.gittf.core.util.StashUtil.java

License:Open Source License

/**
 * Creates a stash/* w  ww .j a v a  2 s . c  om*/
 * 
 * @param repository
 *        the git repository
 * @param repositoryInserter
 *        the repository inserter object to use
 * @param rootBaseTree
 *        the tree id for the base commit of the stash
 * @param rootStashTree
 *        the tree id for the commit of the stash
 * @param rootIndexTree
 *        the tree id for the index commit of the stash
 * @param baseParentId
 *        the parent of the base tree commit
 * @param ownerDisplayName
 *        the owner display name of the stash
 * @param ownerName
 *        the owner name of the stash
 * @param stashComment
 *        the comment used to for the stash
 * @param stashName
 *        the stash name
 * @return
 * @throws IOException
 */
public static final ObjectId create(final Repository repository, final ObjectInserter repositoryInserter,
        final ObjectId rootBaseTree, final ObjectId rootStashTree, final ObjectId rootIndexTree,
        final ObjectId baseParentId, final String ownerDisplayName, final String ownerName,
        final String stashComment, final String stashName) throws IOException {
    Check.notNull(repository, "repository"); //$NON-NLS-1$
    Check.notNull(repositoryInserter, "repositoryInserter"); //$NON-NLS-1$
    Check.notNull(rootBaseTree, "rootBaseTree"); //$NON-NLS-1$
    Check.notNull(rootStashTree, "rootStashTree"); //$NON-NLS-1$
    Check.notNull(rootIndexTree, "rootIndexTree"); //$NON-NLS-1$

    /* identifies the head and the branch we are creating the stash for */
    Ref headReference = repository.getRef(Constants.HEAD);
    RevCommit headCommit = new RevWalk(repository).parseCommit(headReference.getObjectId());
    String currentBranchName = Repository.shortenRefName(headReference.getTarget().getName());

    PersonIdent author = new PersonIdent(ownerDisplayName, ownerName);

    /* create the base commit */
    CommitBuilder commitBuilder = new CommitBuilder();
    commitBuilder.setTreeId(rootBaseTree);
    if (baseParentId != null) {
        commitBuilder.setParentId(baseParentId);
    }
    commitBuilder.setMessage(stashComment);
    commitBuilder.setAuthor(author);
    commitBuilder.setCommitter(author);

    ObjectId baseCommit = repositoryInserter.insert(commitBuilder);

    /* create the index commit */
    commitBuilder.setTreeId(rootIndexTree);
    commitBuilder.setParentId(baseCommit);
    commitBuilder.setMessage(MessageFormat.format(STASH_INDEX_COMMENT, currentBranchName,
            headCommit.abbreviate(7).name(), stashName));
    commitBuilder.setAuthor(author);
    commitBuilder.setCommitter(author);

    ObjectId indexCommit = repositoryInserter.insert(commitBuilder);

    /* create the stash commit */
    commitBuilder.setTreeId(rootStashTree);
    commitBuilder.setParentId(baseCommit);
    commitBuilder.addParentId(indexCommit);

    String stashRefLogComment = MessageFormat.format(STASH_COMMENT, currentBranchName,
            headCommit.abbreviate(7).name(), stashName);
    commitBuilder.setMessage(stashRefLogComment);

    ObjectId stashCommit = repositoryInserter.insert(commitBuilder);

    repositoryInserter.flush();

    /* Update the stash reference and ref log */
    RefUpdate stashReferenceUpdate = repository.updateRef(Constants.R_STASH);
    stashReferenceUpdate.setNewObjectId(stashCommit);
    stashReferenceUpdate.setRefLogIdent(author);
    stashReferenceUpdate.setRefLogMessage(stashRefLogComment, false);

    Ref currentStashRef = repository.getRef(Constants.R_STASH);
    if (currentStashRef != null) {
        stashReferenceUpdate.setExpectedOldObjectId(currentStashRef.getObjectId());
    } else {
        stashReferenceUpdate.setExpectedOldObjectId(ObjectId.zeroId());
    }

    stashReferenceUpdate.forceUpdate();

    return stashCommit;
}

From source file:com.smartitengineering.version.impl.jgit.JGitImpl.java

License:Open Source License

protected void performCommit(final Commit newCommit, final Tree head) throws IOException {
    ObjectId[] parentIds;//from   w  w  w .  j  a v a2s.  c om
    ObjectId currentHeadId = getWriteRepository().resolve(Constants.HEAD);
    if (currentHeadId != null) {
        parentIds = new ObjectId[] { currentHeadId };
    } else {
        parentIds = new ObjectId[0];
    }
    org.eclipse.jgit.lib.Commit commit = new org.eclipse.jgit.lib.Commit(getWriteRepository(), parentIds);
    commit.setTree(head);
    commit.setTreeId(head.getId());
    PersonIdent person = new PersonIdent(newCommit.getAuthor().getName(), newCommit.getAuthor().getEmail());
    commit.setAuthor(person);
    commit.setCommitter(person);
    commit.setMessage(newCommit.getCommitMessage());
    ObjectId newCommitId = getObjectWriter().writeCommit(commit);
    if (newCommit instanceof MutableCommit) {
        MutableCommit mutableCommit = (MutableCommit) newCommit;
        mutableCommit.setCommitId(ObjectId.toString(newCommitId));
        mutableCommit.setCommitTime(commit.getCommitter().getWhen());
        commit.setCommitId(newCommitId);
        if (commit.getParentIds().length > 0) {
            mutableCommit.setParentCommitId(ObjectId.toString(commit.getParentIds()[0]));
        } else {
            mutableCommit.setParentCommitId(ObjectId.toString(ObjectId.zeroId()));
        }
    } else {
        throw new IllegalArgumentException("SPI not implemented by API!");
    }
    RefUpdate refUpdate = getWriteRepository().updateRef(Constants.HEAD);
    refUpdate.setNewObjectId(commit.getCommitId());
    refUpdate.setRefLogMessage(commit.getMessage(), false);
    refUpdate.forceUpdate();
}