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:org.eclipse.egit.ui.common.LocalRepositoryTestCase.java

License:Open Source License

protected static File createRemoteRepository(File repositoryDir) throws Exception {
    FileRepository myRepository = lookupRepository(repositoryDir);
    File gitDir = new File(testDirectory, REPO2);
    Repository myRemoteRepository = new FileRepository(gitDir);
    myRemoteRepository.create();//w  w  w  .  j a  va2 s  .  c o  m
    // double-check that this is bare
    assertTrue(myRemoteRepository.isBare());

    createStableBranch(myRepository);

    // now we configure a pure push destination
    myRepository.getConfig().setString("remote", "push", "pushurl",
            "file:///" + myRemoteRepository.getDirectory().getPath());
    myRepository.getConfig().setString("remote", "push", "push", "+refs/heads/*:refs/heads/*");

    // and a pure fetch destination
    myRepository.getConfig().setString("remote", "fetch", "url",
            "file:///" + myRemoteRepository.getDirectory().getPath());
    myRepository.getConfig().setString("remote", "fetch", "fetch", "+refs/heads/*:refs/heads/*");

    // a destination with both fetch and push urls and specs
    myRepository.getConfig().setString("remote", "both", "pushurl",
            "file:///" + myRemoteRepository.getDirectory().getPath());
    myRepository.getConfig().setString("remote", "both", "push", "+refs/heads/*:refs/heads/*");
    myRepository.getConfig().setString("remote", "both", "url",
            "file:///" + myRemoteRepository.getDirectory().getPath());
    myRepository.getConfig().setString("remote", "both", "fetch", "+refs/heads/*:refs/heads/*");

    // a destination with only a fetch url and push and fetch specs
    myRepository.getConfig().setString("remote", "mixed", "push", "+refs/heads/*:refs/heads/*");
    myRepository.getConfig().setString("remote", "mixed", "url",
            "file:///" + myRemoteRepository.getDirectory().getPath());
    myRepository.getConfig().setString("remote", "mixed", "fetch", "+refs/heads/*:refs/heads/*");

    myRepository.getConfig().save();
    // and push
    PushConfiguredRemoteAction pa = new PushConfiguredRemoteAction(myRepository, "push");

    pa.run(null, false);

    try {
        // delete the stable branch again
        RefUpdate op = myRepository.updateRef("refs/heads/stable");
        op.setRefLogMessage("branch deleted", //$NON-NLS-1$
                false);
        // we set the force update in order
        // to avoid having this rejected
        // due to minor issues
        op.setForceUpdate(true);
        op.delete();
    } catch (IOException ioe) {
        throw new InvocationTargetException(ioe);
    }
    return myRemoteRepository.getDirectory();
}

From source file:org.eclipse.egit.ui.common.LocalRepositoryTestCase.java

License:Open Source License

protected static void createStableBranch(Repository myRepository) throws IOException {
    // let's create a stable branch temporarily so
    // that we push two branches to remote
    String newRefName = "refs/heads/stable";
    RefUpdate updateRef = myRepository.updateRef(newRefName);
    Ref sourceBranch = myRepository.getRef("refs/heads/master");
    ObjectId startAt = sourceBranch.getObjectId();
    String startBranch = Repository.shortenRefName(sourceBranch.getName());
    updateRef.setNewObjectId(startAt);/*from w  w  w  .  j  av  a 2 s  . c  o m*/
    updateRef.setRefLogMessage("branch: Created from " + startBranch, false); //$NON-NLS-1$
    updateRef.update();
}

From source file:org.eclipse.egit.ui.view.repositories.GitRepositoriesViewTagHandlingTest.java

License:Open Source License

@Before
public void before() throws Exception {
    repository = lookupRepository(repositoryFile);
    for (String ref : repository.getTags().keySet()) {
        RefUpdate op = repository.updateRef(ref, true);
        op.setRefLogMessage("tag deleted", //$NON-NLS-1$
                false);//from  www . j  a va 2 s  . c  o m
        // we set the force update in order
        // to avoid having this rejected
        // due to minor issues
        op.setForceUpdate(true);
        op.delete();
    }
    revWalk = new RevWalk(repository);
}

From source file:org.eclipse.egit.ui.view.repositories.GitRepositoriesViewTestBase.java

License:Open Source License

protected static File createRemoteRepository(File repositoryDir) throws Exception {
    Repository myRepository = org.eclipse.egit.core.Activator.getDefault().getRepositoryCache()
            .lookupRepository(repositoryDir);
    File gitDir = new File(getTestDirectory(), REPO2);
    Repository myRemoteRepository = lookupRepository(gitDir);
    myRemoteRepository.create();/*from   w ww  .j a v a 2  s  . c  o m*/

    createStableBranch(myRepository);

    // now we configure the push destination
    myRepository.getConfig().setString("remote", "push", "pushurl",
            "file:///" + myRemoteRepository.getDirectory().getPath());
    myRepository.getConfig().setString("remote", "push", "push", "+refs/heads/*:refs/heads/*");
    // TODO Bug: for some reason, this seems to be required
    myRepository.getConfig().setString(ConfigConstants.CONFIG_CORE_SECTION, null,
            ConfigConstants.CONFIG_KEY_REPO_FORMAT_VERSION, "0");

    myRepository.getConfig().save();
    // and push
    PushConfiguredRemoteAction pa = new PushConfiguredRemoteAction(myRepository, "push");

    pa.run(null, false);
    TestUtil.joinJobs(JobFamilies.PUSH);
    try {
        // delete the stable branch again
        RefUpdate op = myRepository.updateRef("refs/heads/stable");
        op.setRefLogMessage("branch deleted", //$NON-NLS-1$
                false);
        // we set the force update in order
        // to avoid having this rejected
        // due to minor issues
        op.setForceUpdate(true);
        op.delete();
    } catch (IOException ioe) {
        throw new InvocationTargetException(ioe);
    }
    return myRemoteRepository.getDirectory();
}

From source file:org.eclipse.emf.compare.diagram.papyrus.tests.egit.fixture.GitTestRepository.java

License:Open Source License

/**
 * Creates a new branch./*  ww w.j a  v  a  2  s .c om*/
 * 
 * @param refName
 *            Starting point for the new branch.
 * @param newRefName
 *            Name of the new branch.
 */
public void createBranch(String refName, String newRefName) throws IOException {
    RefUpdate updateRef;
    updateRef = repository.updateRef(newRefName);
    Ref startRef = repository.getRef(refName);
    ObjectId startAt = repository.resolve(refName);
    String startBranch;
    if (startRef != null) {
        startBranch = refName;
    } else {
        startBranch = startAt.name();
    }
    startBranch = Repository.shortenRefName(startBranch);
    updateRef.setNewObjectId(startAt);
    updateRef.setRefLogMessage("branch: Created from " + startBranch, false);
    updateRef.update();
}

From source file:org.jfrog.bamboo.release.scm.git.ResetCommand.java

License:Eclipse Distribution License

/**
 * Executes the {@code Reset} command. Each instance of this class should only be used for one invocation of the
 * command. Don't call this method twice on an instance.
 *
 * @return the Ref after reset/* w w w  .j  a  va2  s.com*/
 */
@Override
public Ref call() throws GitAPIException {
    checkCallable();

    Ref r;
    RevCommit commit;

    try {
        boolean merging = false;
        if (repo.getRepositoryState().equals(RepositoryState.MERGING)
                || repo.getRepositoryState().equals(RepositoryState.MERGING_RESOLVED)) {
            merging = true;
        }

        // resolve the ref to a commit
        final ObjectId commitId;
        try {
            commitId = repo.resolve(ref);
        } catch (IOException e) {
            throw new JGitInternalException(MessageFormat.format(JGitText.get().cannotRead, ref), e);
        }
        RevWalk rw = new RevWalk(repo);
        try {
            commit = rw.parseCommit(commitId);
        } catch (IOException e) {
            throw new JGitInternalException(
                    MessageFormat.format(JGitText.get().cannotReadCommit, commitId.toString()), e);
        } finally {
            rw.release();
        }

        // write the ref
        final RefUpdate ru = repo.updateRef(Constants.HEAD);
        ru.setNewObjectId(commitId);

        String refName = Repository.shortenRefName(ref);
        String message = "reset --" //$NON-NLS-1$
                + mode.toString().toLowerCase() + " " + refName; //$NON-NLS-1$
        ru.setRefLogMessage(message, false);
        if (ru.forceUpdate() == RefUpdate.Result.LOCK_FAILURE) {
            throw new JGitInternalException(MessageFormat.format(JGitText.get().cannotLock, ru.getName()));
        }

        switch (mode) {
        case HARD:
            checkoutIndex(commit);
            break;
        case MIXED:
            resetIndex(commit);
            break;
        case SOFT: // do nothing, only the ref was changed
            break;
        }

        if (mode != ResetType.SOFT && merging) {
            resetMerge();
        }

        setCallable(false);
        r = ru.getRef();
    } catch (IOException e) {
        throw new JGitInternalException("Error while executing reset command");
    }

    return r;
}

From source file:org.kie.commons.java.nio.fs.jgit.util.JGitUtil.java

License:Apache License

public static void commit(final Git git, final String branchName, final String name, final String email,
        final String message, final TimeZone timeZone, final Date when, final Map<String, File> content) {

    final PersonIdent author = buildPersonIdent(git, name, email, timeZone, when);

    try {/*from w ww.ja va 2  s. com*/
        final ObjectInserter odi = git.getRepository().newObjectInserter();
        try {
            // Create the in-memory index of the new/updated issue.
            final ObjectId headId = git.getRepository().resolve(branchName + "^{commit}");
            final DirCache index = createTemporaryIndex(git, headId, content);
            final ObjectId indexTreeId = index.writeTree(odi);

            // Create a commit object
            final CommitBuilder commit = new CommitBuilder();
            commit.setAuthor(author);
            commit.setCommitter(author);
            commit.setEncoding(Constants.CHARACTER_ENCODING);
            commit.setMessage(message);
            //headId can be null if the repository has no commit yet
            if (headId != null) {
                commit.setParentId(headId);
            }
            commit.setTreeId(indexTreeId);

            // Insert the commit into the repository
            final ObjectId commitId = odi.insert(commit);
            odi.flush();

            final RevWalk revWalk = new RevWalk(git.getRepository());
            try {
                final RevCommit revCommit = revWalk.parseCommit(commitId);
                final RefUpdate ru = git.getRepository().updateRef("refs/heads/" + branchName);
                if (headId == null) {
                    ru.setExpectedOldObjectId(ObjectId.zeroId());
                } else {
                    ru.setExpectedOldObjectId(headId);
                }
                ru.setNewObjectId(commitId);
                ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
                final RefUpdate.Result rc = ru.forceUpdate();
                switch (rc) {
                case NEW:
                case FORCED:
                case FAST_FORWARD:
                    break;
                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 {
                revWalk.release();
            }
        } finally {
            odi.release();
        }
    } catch (final Throwable t) {
        throw new RuntimeException(t);
    }
}

From source file:org.kie.commons.java.nio.fs.jgit.util.JGitUtil.java

License:Apache License

public static MergeResult mergeBranches(final Git git, final String source, final String target)
        throws Exception {

    final Repository repo = git.getRepository();
    final MergeStrategy mergeStrategy = MergeStrategy.RESOLVE;
    final List<Ref> commits = new LinkedList<Ref>();
    final boolean squash = false;

    RevWalk revWalk = null;//from  ww  w  .  j a v  a 2 s.c om
    DirCacheCheckout dco = null;
    try {
        Ref head = repo.getRef(Constants.HEAD);
        if (head == null) {
            throw new NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
        }
        final StringBuilder refLogMessage = new StringBuilder("merge ");

        // Check for FAST_FORWARD, ALREADY_UP_TO_DATE
        revWalk = new RevWalk(repo);

        // we know for now there is only one commit
        Ref ref = commits.get(0);

        refLogMessage.append(ref.getName());

        // handle annotated tags
        ObjectId objectId = ref.getPeeledObjectId();
        if (objectId == null) {
            objectId = ref.getObjectId();
        }

        final RevCommit srcCommit = revWalk.lookupCommit(objectId);

        ObjectId headId = head.getObjectId();
        if (headId == null) {
            revWalk.parseHeaders(srcCommit);
            dco = new DirCacheCheckout(repo, repo.lockDirCache(), srcCommit.getTree());
            dco.setFailOnConflict(true);
            dco.checkout();
            RefUpdate refUpdate = repo.updateRef(head.getTarget().getName());
            refUpdate.setNewObjectId(objectId);
            refUpdate.setExpectedOldObjectId(null);
            refUpdate.setRefLogMessage("initial pull", false);
            if (refUpdate.update() != RefUpdate.Result.NEW) {
                throw new NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
            }

            return new MergeResult(srcCommit, srcCommit, new ObjectId[] { null, srcCommit },
                    MergeStatus.FAST_FORWARD, mergeStrategy, null, null);
        }

        final RevCommit headCommit = revWalk.lookupCommit(headId);

        if (revWalk.isMergedInto(srcCommit, headCommit)) {
            return new MergeResult(headCommit, srcCommit, new ObjectId[] { headCommit, srcCommit },
                    ALREADY_UP_TO_DATE, mergeStrategy, null, null);
        } else if (revWalk.isMergedInto(headCommit, srcCommit)) {
            // FAST_FORWARD detected: skip doing a real merge but only
            // update HEAD
            refLogMessage.append(": " + FAST_FORWARD);
            dco = new DirCacheCheckout(repo, headCommit.getTree(), repo.lockDirCache(), srcCommit.getTree());
            dco.setFailOnConflict(true);
            dco.checkout();
            String msg = null;
            ObjectId newHead, base = null;
            final MergeStatus mergeStatus;
            if (!squash) {
                updateHead(git, refLogMessage, srcCommit, headId);
                newHead = base = srcCommit;
                mergeStatus = FAST_FORWARD;
            } else {
                msg = JGitText.get().squashCommitNotUpdatingHEAD;
                newHead = base = headId;
                mergeStatus = FAST_FORWARD_SQUASHED;
                final List<RevCommit> squashedCommits = RevWalkUtils.find(revWalk, srcCommit, headCommit);
                final String squashMessage = new SquashMessageFormatter().format(squashedCommits, head);
                repo.writeSquashCommitMsg(squashMessage);
            }
            return new MergeResult(newHead, base, new ObjectId[] { headCommit, srcCommit }, mergeStatus,
                    mergeStrategy, null, msg);
        } else {
            String mergeMessage = "";
            if (!squash) {
                mergeMessage = new MergeMessageFormatter().format(commits, head);
                repo.writeMergeCommitMsg(mergeMessage);
                repo.writeMergeHeads(Arrays.asList(ref.getObjectId()));
            } else {
                final List<RevCommit> squashedCommits = RevWalkUtils.find(revWalk, srcCommit, headCommit);
                final String squashMessage = new SquashMessageFormatter().format(squashedCommits, head);
                repo.writeSquashCommitMsg(squashMessage);
            }
            boolean noProblems;
            final Merger merger = mergeStrategy.newMerger(repo);
            final Map<String, org.eclipse.jgit.merge.MergeResult<?>> lowLevelResults;
            final Map<String, ResolveMerger.MergeFailureReason> failingPaths;
            final List<String> unmergedPaths;

            if (merger instanceof ResolveMerger) {
                ResolveMerger resolveMerger = (ResolveMerger) merger;
                resolveMerger.setCommitNames(new String[] { "BASE", "HEAD", ref.getName() });
                resolveMerger.setWorkingTreeIterator(new FileTreeIterator(repo));
                noProblems = merger.merge(headCommit, srcCommit);
                lowLevelResults = resolveMerger.getMergeResults();
                failingPaths = resolveMerger.getFailingPaths();
                unmergedPaths = resolveMerger.getUnmergedPaths();
            } else {
                noProblems = merger.merge(headCommit, srcCommit);
                lowLevelResults = emptyMap();
                failingPaths = emptyMap();
                unmergedPaths = emptyList();
            }

            refLogMessage.append(": Merge made by ");
            refLogMessage.append(mergeStrategy.getName());
            refLogMessage.append('.');
            if (noProblems) {
                dco = new DirCacheCheckout(repo, headCommit.getTree(), repo.lockDirCache(),
                        merger.getResultTreeId());
                dco.setFailOnConflict(true);
                dco.checkout();

                String msg = null;
                RevCommit newHead = null;
                MergeStatus mergeStatus = null;
                if (!squash) {
                    newHead = new Git(repo).commit().setReflogComment(refLogMessage.toString()).call();
                    mergeStatus = MERGED;
                } else {
                    msg = JGitText.get().squashCommitNotUpdatingHEAD;
                    newHead = headCommit;
                    mergeStatus = MERGED_SQUASHED;
                }
                return new MergeResult(newHead.getId(), null,
                        new ObjectId[] { headCommit.getId(), srcCommit.getId() }, mergeStatus, mergeStrategy,
                        null, msg);
            } else {
                if (failingPaths != null && !failingPaths.isEmpty()) {
                    repo.writeMergeCommitMsg(null);
                    repo.writeMergeHeads(null);
                    return new MergeResult(null, merger.getBaseCommit(0, 1),
                            new ObjectId[] { headCommit.getId(), srcCommit.getId() }, FAILED, mergeStrategy,
                            lowLevelResults, failingPaths, null);
                } else {
                    final String mergeMessageWithConflicts = new MergeMessageFormatter()
                            .formatWithConflicts(mergeMessage, unmergedPaths);
                    repo.writeMergeCommitMsg(mergeMessageWithConflicts);
                    return new MergeResult(null, merger.getBaseCommit(0, 1),
                            new ObjectId[] { headCommit.getId(), srcCommit.getId() }, CONFLICTING,
                            mergeStrategy, lowLevelResults, null);
                }
            }
        }
    } catch (org.eclipse.jgit.errors.CheckoutConflictException e) {
        final List<String> conflicts = (dco == null) ? Collections.<String>emptyList() : dco.getConflicts();
        throw new CheckoutConflictException(conflicts, e);
    } catch (java.io.IOException e) {
        throw new JGitInternalException(
                MessageFormat.format(JGitText.get().exceptionCaughtDuringExecutionOfMergeCommand, e), e);
    } finally {
        if (revWalk != null) {
            revWalk.release();
        }
    }
}

From source file:org.kie.commons.java.nio.fs.jgit.util.JGitUtil.java

License:Apache License

private static void updateHead(final Git git, final StringBuilder refLogMessage, final ObjectId newHeadId,
        final ObjectId oldHeadID) throws java.io.IOException, ConcurrentRefUpdateException {
    RefUpdate refUpdate = git.getRepository().updateRef(Constants.HEAD);
    refUpdate.setNewObjectId(newHeadId);
    refUpdate.setRefLogMessage(refLogMessage.toString(), false);
    refUpdate.setExpectedOldObjectId(oldHeadID);
    RefUpdate.Result rc = refUpdate.update();
    switch (rc) {
    case NEW:/*  w  w w  .  j  a va2s  .c  om*/
    case FAST_FORWARD:
        return;
    case REJECTED:
    case LOCK_FAILURE:
        throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, refUpdate.getRef(), rc);
    default:
        throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, Constants.HEAD,
                newHeadId.toString(), rc));
    }
}

From source file:org.kuali.student.git.importer.FixImportRepo.java

License:Educational Community License

private static void updateRef(Repository repo, String branchName, String revision, AnyObjectId branchId)
        throws IOException {

    RefUpdate u = repo.updateRef(branchName, true);

    u.setForceUpdate(true);/*from  ww  w.  j  a  va  2  s . c  om*/

    String resultMessage = "resetting branch " + branchName + " to revision " + revision + " at "
            + branchId.name();

    u.setNewObjectId(branchId);

    u.setRefLogMessage(resultMessage, true);

    Result result = u.update();

    log.info(resultMessage + " result = " + result);

}