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:com.google.gerrit.acceptance.git.ForcePushIT.java

License:Apache License

@Test
public void forcePushNotAllowed() throws Exception {
    ObjectId initial = repo().getRef(HEAD).getLeaf().getObjectId();
    PushOneCommit push1 = pushFactory.create(db, admin.getIdent(), testRepo, "change1", "a.txt", "content");
    PushOneCommit.Result r1 = push1.to("refs/heads/master");
    r1.assertOkStatus();/*w  w w.j a  v a 2s . co m*/

    // Reset HEAD to initial so the new change is a non-fast forward
    RefUpdate ru = repo().updateRef(HEAD);
    ru.setNewObjectId(initial);
    assertThat(ru.forceUpdate()).isEqualTo(RefUpdate.Result.FORCED);

    PushOneCommit push2 = pushFactory.create(db, admin.getIdent(), testRepo, "change2", "b.txt", "content");
    push2.setForce(true);
    PushOneCommit.Result r2 = push2.to("refs/heads/master");
    r2.assertErrorStatus("non-fast forward");
}

From source file:com.google.gerrit.acceptance.git.ForcePushIT.java

License:Apache License

@Test
public void forcePushAllowed() throws Exception {
    ObjectId initial = repo().getRef(HEAD).getLeaf().getObjectId();
    grant(Permission.PUSH, project, "refs/*", true);
    PushOneCommit push1 = pushFactory.create(db, admin.getIdent(), testRepo, "change1", "a.txt", "content");
    PushOneCommit.Result r1 = push1.to("refs/heads/master");
    r1.assertOkStatus();/* ww w.  j a  va 2 s  .c om*/

    // Reset HEAD to initial so the new change is a non-fast forward
    RefUpdate ru = repo().updateRef(HEAD);
    ru.setNewObjectId(initial);
    assertThat(ru.forceUpdate()).isEqualTo(RefUpdate.Result.FORCED);

    PushOneCommit push2 = pushFactory.create(db, admin.getIdent(), testRepo, "change2", "b.txt", "content");
    push2.setForce(true);
    PushOneCommit.Result r2 = push2.to("refs/heads/master");
    r2.assertOkStatus();
}

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

License:Apache License

private void update(RevCommit rev) throws Exception {
    RefUpdate u = db.updateRef(RefNames.REFS_CONFIG);
    u.disableRefLog();/*from w ww.  j a va2  s  .  c  om*/
    u.setNewObjectId(rev);
    Result result = u.forceUpdate();
    assert_().withFailureMessage("Cannot update ref for test: " + result).that(result)
            .isAnyOf(Result.FAST_FORWARD, Result.FORCED, Result.NEW, Result.NO_CHANGE);
}

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

License:Apache License

private ObjectId writeBlob(String sequenceName, String value) {
    String refName = RefNames.REFS_SEQUENCES + sequenceName;
    try (Repository repo = repoManager.openRepository(project); ObjectInserter ins = repo.newObjectInserter()) {
        ObjectId newId = ins.insert(OBJ_BLOB, value.getBytes(UTF_8));
        ins.flush();/*from www.ja v a  2 s.c  o  m*/
        RefUpdate ru = repo.updateRef(refName);
        ru.setNewObjectId(newId);
        assertThat(ru.forceUpdate()).isAnyOf(RefUpdate.Result.NEW, RefUpdate.Result.FORCED);
        return newId;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.google.gerrit.server.patch.AutoMerger.java

License:Apache License

private RevCommit commit(Repository repo, RevWalk rw, ObjectInserter ins, String refName, ObjectId tree,
        RevCommit merge) throws IOException {
    rw.parseHeaders(merge);//www  .  j av  a  2s.co m
    // For maximum stability, choose a single ident using the committer time of
    // the input commit, using the server name and timezone.
    PersonIdent ident = new PersonIdent(gerritIdent, merge.getCommitterIdent().getWhen(),
            gerritIdent.getTimeZone());
    CommitBuilder cb = new CommitBuilder();
    cb.setAuthor(ident);
    cb.setCommitter(ident);
    cb.setTreeId(tree);
    cb.setMessage("Auto-merge of " + merge.name() + '\n');
    for (RevCommit p : merge.getParents()) {
        cb.addParentId(p);
    }
    ObjectId commitId;
    commitId = ins.insert(cb);
    if (save) {
        ins.flush();

        RefUpdate ru = repo.updateRef(refName);
        ru.setNewObjectId(commitId);
        ru.disableRefLog();
        ru.forceUpdate();
    }
    return rw.parseCommit(commitId);
}

From source file:com.google.gerrit.server.patch.PatchListLoader.java

License:Apache License

public static RevTree automerge(Repository repo, RevWalk rw, RevCommit b, ThreeWayMergeStrategy mergeStrategy,
        boolean save) throws IOException {
    String hash = b.name();/*w  w w. j ava 2  s.  co m*/
    String refName = RefNames.REFS_CACHE_AUTOMERGE + hash.substring(0, 2) + "/" + hash.substring(2);
    Ref ref = repo.getRefDatabase().exactRef(refName);
    if (ref != null && ref.getObjectId() != null) {
        return rw.parseTree(ref.getObjectId());
    }

    ResolveMerger m = (ResolveMerger) mergeStrategy.newMerger(repo, true);
    try (ObjectInserter ins = repo.newObjectInserter()) {
        DirCache dc = DirCache.newInCore();
        m.setDirCache(dc);
        m.setObjectInserter(new ObjectInserter.Filter() {
            @Override
            protected ObjectInserter delegate() {
                return ins;
            }

            @Override
            public void flush() {
            }

            @Override
            public void close() {
            }
        });

        boolean couldMerge;
        try {
            couldMerge = m.merge(b.getParents());
        } catch (IOException e) {
            // It is not safe to continue further down in this method as throwing
            // an exception most likely means that the merge tree was not created
            // and m.getMergeResults() is empty. This would mean that all paths are
            // unmerged and Gerrit UI would show all paths in the patch list.
            log.warn("Error attempting automerge " + refName, e);
            return null;
        }

        ObjectId treeId;
        if (couldMerge) {
            treeId = m.getResultTreeId();

        } else {
            RevCommit ours = b.getParent(0);
            RevCommit theirs = b.getParent(1);
            rw.parseBody(ours);
            rw.parseBody(theirs);
            String oursMsg = ours.getShortMessage();
            String theirsMsg = theirs.getShortMessage();

            String oursName = String.format("HEAD   (%s %s)", ours.abbreviate(6).name(),
                    oursMsg.substring(0, Math.min(oursMsg.length(), 60)));
            String theirsName = String.format("BRANCH (%s %s)", theirs.abbreviate(6).name(),
                    theirsMsg.substring(0, Math.min(theirsMsg.length(), 60)));

            MergeFormatter fmt = new MergeFormatter();
            Map<String, MergeResult<? extends Sequence>> r = m.getMergeResults();
            Map<String, ObjectId> resolved = new HashMap<>();
            for (Map.Entry<String, MergeResult<? extends Sequence>> entry : r.entrySet()) {
                MergeResult<? extends Sequence> p = entry.getValue();
                try (TemporaryBuffer buf = new TemporaryBuffer.LocalFile(null, 10 * 1024 * 1024)) {
                    fmt.formatMerge(buf, p, "BASE", oursName, theirsName, "UTF-8");
                    buf.close();

                    try (InputStream in = buf.openInputStream()) {
                        resolved.put(entry.getKey(), ins.insert(Constants.OBJ_BLOB, buf.length(), in));
                    }
                }
            }

            DirCacheBuilder builder = dc.builder();
            int cnt = dc.getEntryCount();
            for (int i = 0; i < cnt;) {
                DirCacheEntry entry = dc.getEntry(i);
                if (entry.getStage() == 0) {
                    builder.add(entry);
                    i++;
                    continue;
                }

                int next = dc.nextEntry(i);
                String path = entry.getPathString();
                DirCacheEntry res = new DirCacheEntry(path);
                if (resolved.containsKey(path)) {
                    // For a file with content merge conflict that we produced a result
                    // above on, collapse the file down to a single stage 0 with just
                    // the blob content, and a randomly selected mode (the lowest stage,
                    // which should be the merge base, or ours).
                    res.setFileMode(entry.getFileMode());
                    res.setObjectId(resolved.get(path));

                } else if (next == i + 1) {
                    // If there is exactly one stage present, shouldn't be a conflict...
                    res.setFileMode(entry.getFileMode());
                    res.setObjectId(entry.getObjectId());

                } else if (next == i + 2) {
                    // Two stages suggests a delete/modify conflict. Pick the higher
                    // stage as the automatic result.
                    entry = dc.getEntry(i + 1);
                    res.setFileMode(entry.getFileMode());
                    res.setObjectId(entry.getObjectId());

                } else { // 3 stage conflict, no resolve above
                    // Punt on the 3-stage conflict and show the base, for now.
                    res.setFileMode(entry.getFileMode());
                    res.setObjectId(entry.getObjectId());
                }
                builder.add(res);
                i = next;
            }
            builder.finish();
            treeId = dc.writeTree(ins);
        }
        ins.flush();

        if (save) {
            RefUpdate update = repo.updateRef(refName);
            update.setNewObjectId(treeId);
            update.disableRefLog();
            update.forceUpdate();
        }

        return rw.lookupTree(treeId);
    }
}

From source file:com.google.gerrit.server.tools.hooks.CommitMsgHookTest.java

License:Apache License

private void setHEAD() throws Exception {
    try (ObjectInserter oi = repository.newObjectInserter()) {
        final CommitBuilder commit = new CommitBuilder();
        commit.setTreeId(oi.insert(Constants.OBJ_TREE, new byte[] {}));
        commit.setAuthor(author);/*from w  w  w  .  ja v a 2 s  .c  om*/
        commit.setCommitter(committer);
        commit.setMessage("test\n");
        ObjectId commitId = oi.insert(commit);

        final RefUpdate ref = repository.updateRef(Constants.HEAD);
        ref.setNewObjectId(commitId);
        Result result = ref.forceUpdate();
        assert_().withFailureMessage(Constants.HEAD + " did not change: " + ref.getResult()).that(result)
                .isAnyOf(Result.FAST_FORWARD, Result.FORCED, Result.NEW, Result.NO_CHANGE);
    }
}

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()})//from   w w w .j a v a 2 s . c  o  m
 *
 * @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//from   w ww  .j a va2 s  .  c  o m
 * 
 * @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.mooregreatsoftware.gitprocess.lib.Branch.java

License:Apache License

/**
 * Write a "control" reference to remember the current OID of the branch.
 *
 * @return the error message, or null if it went well
 *//*from w  w  w. j  a v a 2 s  .c  o  m*/

@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
public @Nullable String recordLastSyncedAgainst() {
    LOG.debug("Writing sync control file");
    final Try<RefUpdate.Result> refUpdateRes = Try.of(() -> {
        final RefUpdate refUpdate = gitLib.jgit().getRepository().updateRef("gitProcess/" + shortName());
        refUpdate.setNewObjectId(objectId());
        return refUpdate.forceUpdate();
    });
    return refUpdateRes.isFailure() ? refUpdateRes.getCause().toString() : null;
}