Example usage for org.eclipse.jgit.api.errors WrongRepositoryStateException WrongRepositoryStateException

List of usage examples for org.eclipse.jgit.api.errors WrongRepositoryStateException WrongRepositoryStateException

Introduction

In this page you can find the example usage for org.eclipse.jgit.api.errors WrongRepositoryStateException WrongRepositoryStateException.

Prototype

public WrongRepositoryStateException(String message) 

Source Link

Document

Constructor for WrongRepositoryStateException.

Usage

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 ww.  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:org.commonwl.view.workflow.WorkflowControllerTest.java

License:Apache License

/**
 * Endpoint for main form submission/*from  w  w w  .  j av  a 2 s. co  m*/
 */
@Test
public void newWorkflowFromGithubURL() throws Exception {

    // Validator pass or fail
    WorkflowFormValidator mockValidator = Mockito.mock(WorkflowFormValidator.class);
    when(mockValidator.validateAndParse(anyObject(), anyObject())).thenReturn(null)
            .thenReturn(new GitDetails("https://github.com/owner/repoName.git", "branch", "path/within"))
            .thenReturn(new GitDetails("https://github.com/owner/repoName.git", "branch", "path/workflow.cwl"));

    // The eventual accepted valid workflow
    Workflow mockWorkflow = Mockito.mock(Workflow.class);
    when(mockWorkflow.getRetrievedFrom())
            .thenReturn(new GitDetails("https://github.com/owner/repoName.git", "branch", "path/workflow.cwl"));
    QueuedWorkflow mockQueuedWorkflow = Mockito.mock(QueuedWorkflow.class);
    when(mockQueuedWorkflow.getTempRepresentation()).thenReturn(mockWorkflow);

    // Mock workflow service returning valid workflow
    WorkflowService mockWorkflowService = Mockito.mock(WorkflowService.class);
    when(mockWorkflowService.createQueuedWorkflow(anyObject())).thenThrow(new WorkflowNotFoundException())
            .thenThrow(new WrongRepositoryStateException("Some Error"))
            .thenThrow(new TransportException("No SSH Key")).thenThrow(new IOException())
            .thenReturn(mockQueuedWorkflow);

    // Mock controller/MVC
    WorkflowController workflowController = new WorkflowController(mockValidator, mockWorkflowService,
            Mockito.mock(GraphVizService.class));
    MockMvc mockMvc = MockMvcBuilders.standaloneSetup(workflowController).build();

    // Error in validation, go to index to show error
    mockMvc.perform(post("/workflows").param("url", "invalidurl")).andExpect(status().isOk())
            .andExpect(view().name("index"));

    // Valid directory URL redirect
    mockMvc.perform(
            post("/workflows").param("url", "https://github.com/owner/repoName/blob/branch/path/within"))
            .andExpect(status().isFound())
            .andExpect(redirectedUrl("/workflows/github.com/owner/repoName/blob/branch/path/within"));

    // Invalid workflow URL, go to index to show error
    mockMvc.perform(post("/workflows").param("url",
            "https://github.com/owner/repoName/blob/branch/path/nonexistant.cwl")).andExpect(status().isOk())
            .andExpect(view().name("index")).andExpect(model().attributeHasFieldErrors("workflowForm", "url"));

    // Git API error
    mockMvc.perform(post("/workflows").param("url",
            "https://github.com/owner/repoName/blob/branch/path/cantbecloned.cwl")).andExpect(status().isOk())
            .andExpect(view().name("index")).andExpect(model().attributeHasFieldErrors("workflowForm", "url"));

    // Unsupported SSH URL
    mockMvc.perform(
            post("/workflows").param("url", "ssh://github.com/owner/repoName/blob/branch/path/workflow.cwl"))
            .andExpect(status().isOk()).andExpect(view().name("index"))
            .andExpect(model().attributeHasFieldErrors("workflowForm", "url"));

    // Unexpected error
    mockMvc.perform(
            post("/workflows").param("url", "ssh://github.com/owner/repoName/blob/branch/path/unexpected.cwl"))
            .andExpect(status().isOk()).andExpect(view().name("index"))
            .andExpect(model().attributeHasFieldErrors("workflowForm", "url"));

    // Valid workflow URL redirect
    mockMvc.perform(
            post("/workflows").param("url", "https://github.com/owner/repoName/blob/branch/path/workflow.cwl"))
            .andExpect(status().isFound())
            .andExpect(redirectedUrl("/workflows/github.com/owner/repoName/blob/branch/path/workflow.cwl"));

}

From source file:org.commonwl.view.workflow.WorkflowControllerTest.java

License:Apache License

/**
 * Displaying workflows/* w w  w  . j ava 2  s . c  om*/
 */
@Test
public void directWorkflowURL() throws Exception {

    Workflow mockWorkflow = Mockito.mock(Workflow.class);
    QueuedWorkflow mockQueuedWorkflow = Mockito.mock(QueuedWorkflow.class);
    when(mockQueuedWorkflow.getWorkflowList()).thenReturn(null);

    // Mock service
    WorkflowService mockWorkflowService = Mockito.mock(WorkflowService.class);
    when(mockWorkflowService.getWorkflow(Matchers.<GitDetails>anyObject())).thenReturn(mockWorkflow)
            .thenReturn(null);
    when(mockWorkflowService.createQueuedWorkflow(anyObject())).thenReturn(mockQueuedWorkflow)
            .thenThrow(new WorkflowNotFoundException())
            .thenThrow(new WrongRepositoryStateException("Some Error"))
            .thenThrow(new TransportException("No SSH Key")).thenThrow(new IOException());
    List<WorkflowOverview> listOfTwoOverviews = new ArrayList<>();
    listOfTwoOverviews.add(new WorkflowOverview("/workflow1.cwl", "label", "doc"));
    listOfTwoOverviews.add(new WorkflowOverview("/workflow2.cwl", "label2", "doc2"));
    when(mockWorkflowService.getWorkflowsFromDirectory(anyObject())).thenReturn(listOfTwoOverviews)
            .thenReturn(Collections.singletonList(new WorkflowOverview("/workflow1.cwl", "label", "doc")));

    // Mock controller/MVC
    WorkflowController workflowController = new WorkflowController(Mockito.mock(WorkflowFormValidator.class),
            mockWorkflowService, Mockito.mock(GraphVizService.class));
    MockMvc mockMvc = MockMvcBuilders.standaloneSetup(workflowController).build();

    // Workflow already exists in the database
    mockMvc.perform(get("/workflows/github.com/owner/reponame/tree/branch/path/within/workflow.cwl"))
            .andExpect(status().isOk()).andExpect(view().name("workflow"))
            .andExpect(model().attribute("workflow", is(mockWorkflow)));

    // Workflow needs to be created, loading page
    mockMvc.perform(get("/workflows/github.com/owner/reponame/tree/branch/path/within/workflow.cwl"))
            .andExpect(status().isOk()).andExpect(view().name("loading"))
            .andExpect(model().attribute("queued", is(mockQueuedWorkflow)));

    // Directory URL, select between
    mockMvc.perform(get("/workflows/github.com/owner/reponame/tree/branch/path/within"))
            .andExpect(status().isOk()).andExpect(view().name("selectworkflow"))
            .andExpect(model().attributeExists("gitDetails"))
            .andExpect(model().attributeExists("workflowOverviews"));

    // Directory URL with only one workflow redirects
    mockMvc.perform(get("/workflows/github.com/owner/reponame/tree/branch/path/within"))
            .andExpect(status().isFound()).andExpect(redirectedUrl(
                    "/workflows/github.com/owner/reponame/blob/branch/path/within/workflow1.cwl"));

    // Workflow not found
    mockMvc.perform(get("/workflows/github.com/owner/reponame/tree/branch/path/within/nonexistant.cwl"))
            .andExpect(status().isFound()).andExpect(MockMvcResultMatchers.flash().attributeExists("errors"));

    // Git API error
    mockMvc.perform(get("/workflows/github.com/owner/reponame/tree/branch/path/within/cantbecloned.cwl"))
            .andExpect(status().isFound()).andExpect(MockMvcResultMatchers.flash().attributeExists("errors"));

    // Submodules with SSH Url
    mockMvc.perform(get("/workflows/github.com/owner/reponame/tree/branch/path/within/submodulewithssh.cwl"))
            .andExpect(status().isFound()).andExpect(MockMvcResultMatchers.flash().attributeExists("errors"));

    // Unexpected error
    mockMvc.perform(get("/workflows/github.com/owner/reponame/tree/branch/path/within/badworkflow.cwl"))
            .andExpect(status().isFound()).andExpect(MockMvcResultMatchers.flash().attributeExists("errors"));
}

From source file:org.eclipse.orion.server.git.jobs.StashApplyCommand.java

License:Eclipse Distribution License

/**
 * Apply the changes in a stashed commit to the working directory and index
 *
 * @return id of stashed commit that was applied TODO: Does anyone depend on this, or could we make it more like Merge/CherryPick/Revert?
 * @throws GitAPIException//from  w w  w .ja va  2s  .  c  o m
 * @throws WrongRepositoryStateException
 * @throws NoHeadException
 * @throws StashApplyFailureException
 */
@Override
public ObjectId call()
        throws GitAPIException, WrongRepositoryStateException, NoHeadException, StashApplyFailureException {
    checkCallable();

    if (!ignoreRepositoryState && repo.getRepositoryState() != RepositoryState.SAFE)
        throw new WrongRepositoryStateException(
                MessageFormat.format(JGitText.get().stashApplyOnUnsafeRepository, repo.getRepositoryState()));

    ObjectReader reader = repo.newObjectReader();
    try {
        RevWalk revWalk = new RevWalk(reader);

        ObjectId headCommit = repo.resolve(Constants.HEAD);
        if (headCommit == null)
            throw new NoHeadException(JGitText.get().stashApplyWithoutHead);

        final ObjectId stashId = getStashId();
        RevCommit stashCommit = revWalk.parseCommit(stashId);
        if (stashCommit.getParentCount() < 2 || stashCommit.getParentCount() > 3)
            throw new JGitInternalException(
                    MessageFormat.format(JGitText.get().stashCommitIncorrectNumberOfParents, stashId.name(),
                            Integer.valueOf(stashCommit.getParentCount())));

        ObjectId headTree = repo.resolve(Constants.HEAD + "^{tree}"); //$NON-NLS-1$
        ObjectId stashIndexCommit = revWalk.parseCommit(stashCommit.getParent(1));
        ObjectId stashHeadCommit = stashCommit.getParent(0);
        ObjectId untrackedCommit = null;
        if (applyUntracked && stashCommit.getParentCount() == 3)
            untrackedCommit = revWalk.parseCommit(stashCommit.getParent(2));

        ResolveMerger merger = (ResolveMerger) strategy.newMerger(repo);
        merger.setCommitNames(new String[] { "stashed HEAD", "HEAD", "stash" });
        merger.setBase(stashHeadCommit);
        merger.setWorkingTreeIterator(new FileTreeIterator(repo));
        if (merger.merge(headCommit, stashCommit)) {
            DirCache dc = repo.lockDirCache();
            DirCacheCheckout dco = new DirCacheCheckout(repo, headTree, dc, merger.getResultTreeId());
            dco.setFailOnConflict(true);
            dco.checkout(); // Ignoring failed deletes....
            if (applyIndex) {
                ResolveMerger ixMerger = (ResolveMerger) strategy.newMerger(repo, true);
                ixMerger.setCommitNames(new String[] { "stashed HEAD", "HEAD", "stashed index" });
                ixMerger.setBase(stashHeadCommit);
                boolean ok = ixMerger.merge(headCommit, stashIndexCommit);
                if (ok) {
                    resetIndex(revWalk.parseTree(ixMerger.getResultTreeId()));
                } else {
                    throw new StashApplyFailureException(JGitText.get().stashApplyConflict);
                }
            }

            if (untrackedCommit != null) {
                ResolveMerger untrackedMerger = (ResolveMerger) strategy.newMerger(repo, true);
                untrackedMerger.setCommitNames(new String[] { "stashed HEAD", "HEAD", "untracked files" }); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                untrackedMerger.setBase(stashHeadCommit);
                boolean ok = untrackedMerger.merge(stashHeadCommit, untrackedCommit);
                if (ok)
                    try {
                        RevTree untrackedTree = revWalk.parseTree(untrackedMerger.getResultTreeId());
                        resetUntracked(untrackedTree);
                    } catch (CheckoutConflictException e) {
                        throw new StashApplyFailureException(JGitText.get().stashApplyConflict);
                    }
                else
                    throw new StashApplyFailureException(JGitText.get().stashApplyConflict);
            }
        } else {
            throw new StashApplyFailureException(JGitText.get().stashApplyConflict);
        }
        return stashId;

    } catch (JGitInternalException e) {
        throw e;
    } catch (IOException e) {
        throw new JGitInternalException(JGitText.get().stashApplyFailed, e);
    } finally {
        reader.release();
    }
}

From source file:org.flowerplatform.web.git.operation.internal.PullCommand.java

License:Open Source License

/**
 * Executes the {@code Pull} command with all the options and parameters
 * collected by the setter methods (e.g.
 * {@link #setProgressMonitor(ProgressMonitor)}) of this class. 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 result of the pull/*  w  ww. j a v  a 2s .  co  m*/
 * @throws WrongRepositoryStateException
 * @throws InvalidConfigurationException
 * @throws DetachedHeadException
 * @throws InvalidRemoteException
 * @throws CanceledException
 * @throws RefNotFoundException
 * @throws NoHeadException
 * @throws org.eclipse.jgit.api.errors.TransportException
 * @throws GitAPIException
 */
@SuppressWarnings("restriction")
public PullResult call() throws GitAPIException, WrongRepositoryStateException, InvalidConfigurationException,
        DetachedHeadException, InvalidRemoteException, CanceledException, RefNotFoundException, NoHeadException,
        org.eclipse.jgit.api.errors.TransportException {
    checkCallable();

    monitor.beginTask(JGitText.get().pullTaskName, 2);

    Object[] data = GitPlugin.getInstance().getUtils().getFetchPushUpstreamDataRefSpecAndRemote(repo);

    String fullBranch = (String) data[0];
    String branchName = fullBranch.substring(Constants.R_HEADS.length());

    if (!repo.getRepositoryState().equals(RepositoryState.SAFE))
        throw new WrongRepositoryStateException(MessageFormat.format(JGitText.get().cannotPullOnARepoWithState,
                repo.getRepositoryState().name()));

    // get the configured remote for the currently checked out branch
    // stored in configuration key branch.<branch name>.remote
    Config repoConfig = repo.getConfig();
    String remote = repoConfig.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
            ConfigConstants.CONFIG_KEY_REMOTE);
    if (remote == null)
        // fall back to default remote
        remote = Constants.DEFAULT_REMOTE_NAME;

    // get the name of the branch in the remote repository
    // stored in configuration key branch.<branch name>.merge
    String remoteBranchName = (String) data[1];

    // determines whether rebase should be used after fetching
    boolean doRebase = (boolean) data[3];

    final boolean isRemote = !remote.equals("."); //$NON-NLS-1$
    String remoteUri;
    FetchResult fetchRes;
    if (isRemote) {
        remoteUri = (String) data[2];

        if (monitor.isCancelled())
            throw new CanceledException(
                    MessageFormat.format(JGitText.get().operationCanceled, JGitText.get().pullTaskName));

        RefSpec refSpec = new RefSpec();
        refSpec = refSpec.setForceUpdate(true);
        refSpec = refSpec.setSourceDestination(remoteBranchName, fullBranch);

        FetchCommand fetch = new Git(repo).fetch().setRemote(remote).setRefSpecs(refSpec);

        fetch.setProgressMonitor(monitor);
        configure(fetch);

        fetchRes = fetch.call();
    } else {
        // we can skip the fetch altogether
        remoteUri = "local repository";
        fetchRes = null;
    }

    monitor.update(1);

    if (monitor.isCancelled())
        throw new CanceledException(
                MessageFormat.format(JGitText.get().operationCanceled, JGitText.get().pullTaskName));

    // we check the updates to see which of the updated branches
    // corresponds
    // to the remote branch name
    AnyObjectId commitToMerge;
    if (isRemote) {
        Ref r = null;
        if (fetchRes != null) {
            r = fetchRes.getAdvertisedRef(remoteBranchName);
            if (r == null)
                r = fetchRes.getAdvertisedRef(Constants.R_HEADS + remoteBranchName);
        }
        if (r == null)
            throw new JGitInternalException(
                    MessageFormat.format(JGitText.get().couldNotGetAdvertisedRef, remoteBranchName));
        else
            commitToMerge = r.getObjectId();
    } else {
        try {
            commitToMerge = repo.resolve(remoteBranchName);
            if (commitToMerge == null)
                throw new RefNotFoundException(
                        MessageFormat.format(JGitText.get().refNotResolved, remoteBranchName));
        } catch (IOException e) {
            throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfPullCommand, e);
        }
    }

    String upstreamName = "branch \'" + Repository.shortenRefName(remoteBranchName) + "\' of " + remoteUri;

    PullResult result;
    if (doRebase) {
        RebaseCommand rebase = new Git(repo).rebase();
        RebaseResult rebaseRes = rebase.setUpstream(commitToMerge).setUpstreamName(upstreamName)
                .setProgressMonitor(monitor).setOperation(Operation.BEGIN).call();
        result = new PullResult(fetchRes, remote, rebaseRes);
    } else {
        MergeCommand merge = new Git(repo).merge();
        merge.include(upstreamName, commitToMerge);
        MergeResult mergeRes = merge.call();
        monitor.update(1);
        result = new PullResult(fetchRes, remote, mergeRes);
    }
    monitor.endTask();
    return result;
}