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

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

Introduction

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

Prototype

public Result forceUpdate() throws IOException 

Source Link

Document

Force the ref to take the new value.

Usage

From source file:org.moxie.utils.JGitUtils.java

License:Apache License

public static void updateGhPages(File repositoryFolder, File sourceFolder, boolean obliterate) {
    String ghpages = "refs/heads/gh-pages";
    try {/*from  www .  j ava2s.c  o m*/
        File gitDir = FileKey.resolve(repositoryFolder, FS.DETECTED);
        Repository repository = new FileRepository(gitDir);

        ObjectId objectId = repository.resolve(ghpages);
        if (objectId == null) {
            JGitUtils.createOrphanBranch(repository, "gh-pages", null);
        }

        System.out.println("Updating gh-pages branch...");
        ObjectId headId = repository.resolve(ghpages + "^{commit}");
        ObjectInserter odi = repository.newObjectInserter();
        try {
            // Create the in-memory index of the new/updated issue.
            DirCache index = createIndex(repository, headId, sourceFolder, obliterate);
            ObjectId indexTreeId = index.writeTree(odi);

            // Create a commit object
            PersonIdent author = new PersonIdent("Moxie", "moxie@localhost");
            CommitBuilder commit = new CommitBuilder();
            commit.setAuthor(author);
            commit.setCommitter(author);
            commit.setEncoding(Constants.CHARACTER_ENCODING);
            commit.setMessage("updated pages");
            commit.setParentId(headId);
            commit.setTreeId(indexTreeId);

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

            RevWalk revWalk = new RevWalk(repository);
            try {
                RevCommit revCommit = revWalk.parseCommit(commitId);
                RefUpdate ru = repository.updateRef(ghpages);
                ru.setNewObjectId(commitId);
                ru.setExpectedOldObjectId(headId);
                ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
                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,
                            ghpages, commitId.toString(), rc));
                }
            } finally {
                revWalk.release();
            }
        } finally {
            odi.release();
        }
        System.out.println("gh-pages updated.");
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:org.nbgit.ui.clone.CloneAction.java

License:Open Source License

public static void doCheckout(Repository repo, Ref branch, OutputLogger logger) throws IOException {

    final GitIndex index = new GitIndex(repo);
    final Commit mapCommit = repo.mapCommit(branch.getObjectId());
    final Tree tree = mapCommit.getTree();
    final RefUpdate u;
    final WorkDirCheckout co;

    u = repo.updateRef(Constants.HEAD);/*www .  j a v  a  2  s . c om*/
    u.setNewObjectId(mapCommit.getCommitId());
    u.forceUpdate();

    // checking out files
    co = new WorkDirCheckout(repo, repo.getWorkDir(), index, tree);
    co.checkout();
    // writing index
    index.write();
}

From source file:org.openengsb.connector.git.internal.GitServiceImpl.java

License:Apache License

protected void doCheckout(FetchResult fetchResult) throws IOException {
    final Ref head = fetchResult.getAdvertisedRef(Constants.R_HEADS + watchBranch);
    final RevWalk rw = new RevWalk(repository);
    final RevCommit mapCommit;
    try {/*from   ww w  .j av  a 2 s . c o  m*/
        LOGGER.debug("Mapping received reference to respective commit.");
        mapCommit = rw.parseCommit(head.getObjectId());
    } finally {
        rw.release();
    }

    final RefUpdate u;

    boolean detached = !head.getName().startsWith(Constants.R_HEADS);
    LOGGER.debug("Updating HEAD reference to revision [{}]", mapCommit.getId().name());
    u = repository.updateRef(Constants.HEAD, detached);
    u.setNewObjectId(mapCommit.getId());
    u.forceUpdate();

    DirCacheCheckout dirCacheCheckout = new DirCacheCheckout(repository, null, repository.lockDirCache(),
            mapCommit.getTree());
    dirCacheCheckout.setFailOnConflict(true);
    boolean checkoutResult = dirCacheCheckout.checkout();
    LOGGER.debug("Checked out new repository revision to working directory");
    if (!checkoutResult) {
        throw new IOException("Internal error occured on checking out files");
    }
}

From source file:org.uberfire.java.nio.fs.jgit.util.commands.SimpleRefUpdateCommand.java

License:Apache License

private void forceUpdate(final RefUpdate ru, final ObjectId id)
        throws java.io.IOException, ConcurrentRefUpdateException {
    final RefUpdate.Result rc = ru.forceUpdate();
    switch (rc) {
    case NEW://from  w  w w . j  a va 2 s .  c om
    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, id.toString(), rc));
    }
}

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

License:Apache License

public static boolean commit(final Git git, final String branchName, final CommitInfo commitInfo,
        final boolean amend, final ObjectId _originId, final CommitContent content) {
    boolean hadEffecitiveCommit = true;
    final PersonIdent author = buildPersonIdent(git, commitInfo.getName(), commitInfo.getEmail(),
            commitInfo.getTimeZone(), commitInfo.getWhen());

    try {//from w  w  w. 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 ObjectId originId;
            if (_originId == null) {
                originId = git.getRepository().resolve(branchName + "^{commit}");
            } else {
                originId = _originId;
            }

            final DirCache index;
            if (content instanceof DefaultCommitContent) {
                index = createTemporaryIndex(git, originId, (DefaultCommitContent) content);
            } else if (content instanceof MoveCommitContent) {
                index = createTemporaryIndex(git, originId, (MoveCommitContent) content);
            } else if (content instanceof CopyCommitContent) {
                index = createTemporaryIndex(git, originId, (CopyCommitContent) content);
            } else if (content instanceof RevertCommitContent) {
                index = createTemporaryIndex(git, originId);
            } else {
                index = null;
            }

            if (index != null) {
                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(commitInfo.getMessage());
                //headId can be null if the repository has no commit yet
                if (headId != null) {
                    if (amend) {
                        final List<ObjectId> parents = new LinkedList<ObjectId>();
                        final RevCommit previousCommit = new RevWalk(git.getRepository()).parseCommit(headId);
                        final RevCommit[] p = previousCommit.getParents();
                        for (final RevCommit revCommit : p) {
                            parents.add(0, revCommit.getId());
                        }
                        commit.setParentIds(parents);
                    } else {
                        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();
                }
            } else {
                hadEffecitiveCommit = false;
            }
        } finally {
            odi.release();
        }
    } catch (final Throwable t) {
        throw new RuntimeException(t);
    }
    return hadEffecitiveCommit;
}

From source file:org.webcat.core.git.GitCloner.java

License:Open Source License

private void doCheckout(Repository repository, Ref branch) throws IOException {
    if (!Constants.HEAD.equals(branch.getName())) {
        RefUpdate refUpdate = repository.updateRef(Constants.HEAD);
        refUpdate.disableRefLog();//  w  w  w  . j ava  2s  . c o  m
        refUpdate.link(branch.getName());
    }

    RevCommit commit = parseCommit(repository, branch);
    RefUpdate refUpdate = repository.updateRef(Constants.HEAD);
    refUpdate.setNewObjectId(commit);
    refUpdate.forceUpdate();

    DirCache dirCache = repository.lockDirCache();
    DirCacheCheckout checkout = new DirCacheCheckout(repository, dirCache, commit.getTree());
    checkout.checkout();
}

From source file:util.ChkoutCmd.java

License:Eclipse Distribution License

/**
 * @throws RefAlreadyExistsException/*from   w ww .  j av  a2  s. c o  m*/
 *             when trying to create (without force) a branch with a name
 *             that already exists
 * @throws RefNotFoundException
 *             if the start point or branch can not be found
 * @throws InvalidRefNameException
 *             if the provided name is <code>null</code> or otherwise
 *             invalid
 * @throws CheckoutConflictException
 *             if the checkout results in a conflict
 * @return the newly created branch
 */
public Ref call() throws GitAPIException, RefAlreadyExistsException, RefNotFoundException,
        InvalidRefNameException, CheckoutConflictException {
    checkCallable();
    processOptions();
    try {
        if (checkoutAllPaths || !paths.isEmpty()) {
            checkoutPaths();
            status = new CheckoutResult(Status.OK, paths);
            setCallable(false);
            return null;
        }

        if (createBranch) {
            Git git = new Git(repo);
            CreateBranchCommand command = git.branchCreate();
            command.setName(name);
            command.setStartPoint(getStartPoint().name());
            if (upstreamMode != null)
                command.setUpstreamMode(upstreamMode);
            command.call();
        }

        Ref headRef = repo.getRef(Constants.HEAD);
        String shortHeadRef = getShortBranchName(headRef);
        String refLogMessage = "checkout: moving from " + shortHeadRef; //$NON-NLS-1$
        ObjectId branch = repo.resolve(name);
        if (branch == null)
            throw new RefNotFoundException(MessageFormat.format(JGitText.get().refNotResolved, name));

        RevWalk revWalk = new RevWalk(repo);
        AnyObjectId headId = headRef.getObjectId();
        RevCommit headCommit = headId == null ? null : revWalk.parseCommit(headId);
        RevCommit newCommit = revWalk.parseCommit(branch);
        RevTree headTree = headCommit == null ? null : headCommit.getTree();
        DirCacheCheckout dco;
        DirCache dc = repo.lockDirCache();
        try {
            dco = new DirCacheCheckout(repo, headTree, dc, newCommit.getTree());
            dco.setFailOnConflict(false);
            try {
                dco.checkout();
            } catch (org.eclipse.jgit.errors.CheckoutConflictException e) {
                status = new CheckoutResult(Status.CONFLICTS, dco.getConflicts());
                throw new CheckoutConflictException(dco.getConflicts(), e);
            }
        } finally {
            dc.unlock();
        }
        Ref ref = repo.getRef(name);
        if (ref != null && !ref.getName().startsWith(Constants.R_HEADS))
            ref = null;
        String toName = Repository.shortenRefName(name);
        RefUpdate refUpdate = repo.updateRef(Constants.HEAD, ref == null);
        refUpdate.setForceUpdate(force);
        refUpdate.setRefLogMessage(refLogMessage + " to " + toName, false); //$NON-NLS-1$
        Result updateResult;
        if (ref != null)
            updateResult = refUpdate.link(ref.getName());
        else {
            refUpdate.setNewObjectId(newCommit);
            updateResult = refUpdate.forceUpdate();
        }

        setCallable(false);

        boolean ok = false;
        switch (updateResult) {
        case NEW:
            ok = true;
            break;
        case NO_CHANGE:
        case FAST_FORWARD:
        case FORCED:
            ok = true;
            break;
        default:
            break;
        }

        if (!ok)
            throw new JGitInternalException(
                    MessageFormat.format(JGitText.get().checkoutUnexpectedResult, updateResult.name()));

        if (!dco.getToBeDeleted().isEmpty()) {
            status = new CheckoutResult(Status.NONDELETED, dco.getToBeDeleted());
        } else
            status = new CheckoutResult(new ArrayList<String>(dco.getUpdated().keySet()), dco.getRemoved());

        return ref;
    } catch (IOException ioe) {
        throw new JGitInternalException(ioe.getMessage(), ioe);
    } finally {
        if (status == null)
            status = CheckoutResult.ERROR_RESULT;
    }
}