Example usage for org.eclipse.jgit.lib Repository getRepositoryState

List of usage examples for org.eclipse.jgit.lib Repository getRepositoryState

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository getRepositoryState.

Prototype

@NonNull
public RepositoryState getRepositoryState() 

Source Link

Document

Get the repository state

Usage

From source file:org.eclipse.egit.ui.internal.merge.GitMergeEditorInput.java

License:Open Source License

@Override
protected Object prepareInput(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    final Set<IFile> files = new HashSet<IFile>();
    List<IContainer> folders = new ArrayList<IContainer>();
    Set<IProject> projects = new HashSet<IProject>();

    // collect all projects and sort the selected
    // resources into files and folders; skip
    // ignored resources
    for (IResource res : resources) {
        projects.add(res.getProject());//ww  w. j a  va 2s .  co m
        if (Team.isIgnoredHint(res))
            continue;
        if (res.getType() == IResource.FILE)
            files.add((IFile) res);
        else
            folders.add((IContainer) res);
    }

    if (monitor.isCanceled())
        throw new InterruptedException();

    // make sure all resources belong to the same repository
    Repository repo = null;
    for (IProject project : projects) {
        RepositoryMapping map = RepositoryMapping.getMapping(project);
        if (repo != null && repo != map.getRepository())
            throw new InvocationTargetException(
                    new IllegalStateException(UIText.AbstractHistoryCommanndHandler_NoUniqueRepository));
        repo = map.getRepository();
    }

    if (repo == null)
        throw new InvocationTargetException(
                new IllegalStateException(UIText.AbstractHistoryCommanndHandler_NoUniqueRepository));

    if (monitor.isCanceled())
        throw new InterruptedException();

    // collect all file children of the selected folders
    IResourceVisitor fileCollector = new IResourceVisitor() {
        public boolean visit(IResource resource) throws CoreException {
            if (Team.isIgnoredHint(resource))
                return false;
            if (resource.getType() == IResource.FILE) {
                files.add((IFile) resource);
            }
            return true;
        }
    };

    for (IContainer cont : folders) {
        try {
            cont.accept(fileCollector);
        } catch (CoreException e) {
            // ignore here
        }
    }

    if (monitor.isCanceled())
        throw new InterruptedException();

    // our root node
    this.compareResult = new DiffNode(Differencer.CONFLICTING);

    final RevWalk rw = new RevWalk(repo);

    // get the "right" side (MERGE_HEAD for merge, ORIG_HEAD for rebase)
    final RevCommit rightCommit;
    try {
        String target;
        if (repo.getRepositoryState().equals(RepositoryState.MERGING))
            target = Constants.MERGE_HEAD;
        else if (repo.getRepositoryState().equals(RepositoryState.REBASING_INTERACTIVE))
            target = readFile(repo.getDirectory(),
                    RebaseCommand.REBASE_MERGE + File.separatorChar + RebaseCommand.STOPPED_SHA);
        else
            target = Constants.ORIG_HEAD;
        ObjectId mergeHead = repo.resolve(target);
        if (mergeHead == null)
            throw new IOException(NLS.bind(UIText.ValidationUtils_CanNotResolveRefMessage, target));
        rightCommit = rw.parseCommit(mergeHead);
    } catch (IOException e) {
        throw new InvocationTargetException(e);
    }

    // we need the HEAD, also to determine the common
    // ancestor
    final RevCommit headCommit;
    try {
        ObjectId head = repo.resolve(Constants.HEAD);
        if (head == null)
            throw new IOException(NLS.bind(UIText.ValidationUtils_CanNotResolveRefMessage, Constants.HEAD));
        headCommit = rw.parseCommit(head);
    } catch (IOException e) {
        throw new InvocationTargetException(e);
    }

    final String fullBranch;
    try {
        fullBranch = repo.getFullBranch();
    } catch (IOException e) {
        throw new InvocationTargetException(e);
    }

    // try to obtain the common ancestor
    List<RevCommit> startPoints = new ArrayList<RevCommit>();
    rw.setRevFilter(RevFilter.MERGE_BASE);
    startPoints.add(rightCommit);
    startPoints.add(headCommit);
    RevCommit ancestorCommit;
    try {
        rw.markStart(startPoints);
        ancestorCommit = rw.next();
    } catch (Exception e) {
        ancestorCommit = null;
    }

    if (monitor.isCanceled())
        throw new InterruptedException();

    // set the labels
    CompareConfiguration config = getCompareConfiguration();
    config.setRightLabel(NLS.bind(LABELPATTERN, rightCommit.getShortMessage(), rightCommit.name()));

    if (!useWorkspace)
        config.setLeftLabel(NLS.bind(LABELPATTERN, headCommit.getShortMessage(), headCommit.name()));
    else
        config.setLeftLabel(UIText.GitMergeEditorInput_WorkspaceHeader);

    if (ancestorCommit != null)
        config.setAncestorLabel(
                NLS.bind(LABELPATTERN, ancestorCommit.getShortMessage(), ancestorCommit.name()));

    // set title and icon
    setTitle(NLS.bind(UIText.GitMergeEditorInput_MergeEditorTitle,
            new Object[] { Activator.getDefault().getRepositoryUtil().getRepositoryName(repo),
                    rightCommit.getShortMessage(), fullBranch }));

    // now we calculate the nodes containing the compare information
    try {
        for (IFile file : files) {
            if (monitor.isCanceled())
                throw new InterruptedException();

            monitor.setTaskName(file.getFullPath().toString());

            RepositoryMapping map = RepositoryMapping.getMapping(file);
            String gitPath = map.getRepoRelativePath(file);
            if (gitPath == null)
                continue;

            // ignore everything in .git
            if (gitPath.startsWith(Constants.DOT_GIT))
                continue;

            fileToDiffNode(file, gitPath, map, this.compareResult, rightCommit, headCommit, ancestorCommit, rw,
                    monitor);
        }
    } catch (IOException e) {
        throw new InvocationTargetException(e);
    }
    return compareResult;
}

From source file:org.eclipse.egit.ui.internal.preferences.GitProjectPropertyPage.java

License:Open Source License

private void fillValues(Repository repository) throws IOException {
    gitDir.setText(repository.getDirectory().getAbsolutePath());
    branch.setText(repository.getBranch());
    workDir.setText(repository.getWorkTree().getAbsolutePath());

    state.setText(repository.getRepositoryState().getDescription());

    final ObjectId objectId = repository.resolve(repository.getFullBranch());
    if (objectId == null) {
        if (repository.getAllRefs().size() == 0)
            id.setText(UIText.GitProjectPropertyPage_ValueEmptyRepository);
        else/*w  w w. j  a  v a  2  s  . c o m*/
            id.setText(UIText.GitProjectPropertyPage_ValueUnbornBranch);
    } else
        id.setText(objectId.name());
}

From source file:org.eclipse.egit.ui.internal.rebase.RebaseHelper.java

License:Open Source License

/**
 * Shared implementation to be called from an implementation of
 * {@link org.eclipse.core.commands.AbstractHandler#execute(org.eclipse.core.commands.ExecutionEvent)}
 * <p>//w ww  .j  a v a2  s.  c  om
 * Perform a rebase operation, moving the commits from the branch tip <code>commit</code> onto the
 * currently checked out branch. The actual operation is deferred to a {@link RebaseOperation} executed
 * as a {@link Job}.
 * <p>
 * @param repository
 * @param jobname
 * @param ref
 */
public static void runRebaseJob(final Repository repository, String jobname, Ref ref) {
    final RebaseOperation rebase = new RebaseOperation(repository, ref);
    Job job = new Job(jobname) {
        @Override
        protected IStatus run(IProgressMonitor monitor) {
            try {
                rebase.execute(monitor);
            } catch (final CoreException e) {
                if (!repository.getRepositoryState().equals(RepositoryState.SAFE)) {
                    try {
                        new RebaseOperation(repository, Operation.ABORT).execute(monitor);
                    } catch (CoreException e1) {
                        return createMultiStatus(e, e1);
                    }
                }
                return e.getStatus();
            }
            return Status.OK_STATUS;
        }
    };
    job.setUser(true);
    job.setRule(rebase.getSchedulingRule());
    job.addJobChangeListener(new JobChangeAdapter() {
        @Override
        public void done(IJobChangeEvent cevent) {
            IStatus result = cevent.getJob().getResult();
            if (result.getSeverity() == IStatus.CANCEL) {
                Display.getDefault().asyncExec(new Runnable() {
                    public void run() {
                        // don't use getShell(event) here since
                        // the active shell has changed since the
                        // execution has been triggered.
                        Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
                        MessageDialog.openInformation(shell, UIText.RebaseCurrentRefCommand_RebaseCanceledTitle,
                                UIText.RebaseCurrentRefCommand_RebaseCanceledMessage);
                    }
                });
            } else if (result.isOK()) {
                RebaseResultDialog.show(rebase.getResult(), repository);
            }
        }
    });
    job.schedule();
}

From source file:org.eclipse.egit.ui.internal.rebase.RebaseInteractiveView.java

License:Open Source License

private static String getRepositoryName(Repository repository) {
    String repoName = Activator.getDefault().getRepositoryUtil().getRepositoryName(repository);
    RepositoryState state = repository.getRepositoryState();
    if (state != RepositoryState.SAFE)
        return repoName + '|' + state.getDescription();
    else/* ww w  . ja v  a 2s. c  o  m*/
        return repoName;
}

From source file:org.eclipse.egit.ui.internal.repository.RepositoriesViewLabelProvider.java

License:Open Source License

public StyledString getStyledText(Object element) {
    if (!(element instanceof RepositoryTreeNode))
        return null;

    RepositoryTreeNode node = (RepositoryTreeNode) element;

    try {//from  ww  w  .j  a  v a  2  s.com
        switch (node.getType()) {
        case REPO:
            Repository repository = (Repository) node.getObject();
            File directory = repository.getDirectory();
            StyledString string = new StyledString(directory.getParentFile().getName());
            string.append(" - " + directory.getAbsolutePath(), StyledString.QUALIFIER_STYLER); //$NON-NLS-1$
            String branch = repository.getBranch();
            if (repository.getRepositoryState() != RepositoryState.SAFE)
                branch += " - " + repository.getRepositoryState().getDescription(); //$NON-NLS-1$
            string.append(" [" + branch + "]", StyledString.DECORATIONS_STYLER); //$NON-NLS-1$//$NON-NLS-2$
            return string;
        case ADDITIONALREF:
            Ref ref = (Ref) node.getObject();
            // shorten the name
            StyledString refName = new StyledString(Repository.shortenRefName(ref.getName()));
            if (ref.isSymbolic()) {
                refName.append(" - ", StyledString.QUALIFIER_STYLER); //$NON-NLS-1$
                refName.append(ref.getLeaf().getName(), StyledString.QUALIFIER_STYLER);
                refName.append(" - ", StyledString.QUALIFIER_STYLER); //$NON-NLS-1$
                refName.append(ObjectId.toString(ref.getLeaf().getObjectId()), StyledString.QUALIFIER_STYLER);
            } else {
                refName.append(" - ", StyledString.QUALIFIER_STYLER); //$NON-NLS-1$
                refName.append(ObjectId.toString(ref.getObjectId()), StyledString.QUALIFIER_STYLER);

            }
            return refName;
        case WORKINGDIR:
            StyledString dirString = new StyledString(UIText.RepositoriesView_WorkingDir_treenode);
            dirString.append(" - ", StyledString.QUALIFIER_STYLER); //$NON-NLS-1$
            if (node.getRepository().isBare()) {
                dirString.append(UIText.RepositoriesViewLabelProvider_BareRepositoryMessage,
                        StyledString.QUALIFIER_STYLER);
            } else {
                dirString.append(node.getRepository().getWorkTree().getAbsolutePath(),
                        StyledString.QUALIFIER_STYLER);
            }
            return dirString;
        case PUSH:
            // fall through
        case FETCH:
            // fall through
        case FILE:
            // fall through
        case FOLDER:
            // fall through
        case BRANCHES:
            // fall through
        case LOCAL:
            // fall through
        case REMOTETRACKING:
            // fall through
        case BRANCHHIERARCHY:
            // fall through
        case TAGS:
            // fall through;
        case ADDITIONALREFS:
            // fall through
        case REMOTES:
            // fall through
        case REMOTE:
            // fall through
        case ERROR:
            // fall through
        case REF:
            // fall through
        case TAG: {
            String label = getSimpleText(node);
            if (label != null)
                return new StyledString(label);
        }

        }
    } catch (IOException e) {
        Activator.logError(e.getMessage(), e);
    }

    return null;

}

From source file:org.eclipse.egit.ui.internal.repository.tree.command.CreateTagCommand.java

License:Open Source License

public Object execute(ExecutionEvent event) throws ExecutionException {
    RepositoryTreeNode node = getSelectedNodes(event).get(0);

    final Repository repo = node.getRepository();

    if (!repo.getRepositoryState().canCheckout()) {
        MessageDialog.openError(getShell(event), UIText.TagAction_cannotCheckout,
                NLS.bind(UIText.TagAction_repositoryState, repo.getRepositoryState().getDescription()));
        return null;
    }// w  w  w. ja v a 2 s  .c  om

    String currentBranchName;
    try {
        currentBranchName = repo.getBranch();
    } catch (IOException e) {
        Activator.handleError(e.getMessage(), e, true);
        // TODO correct message
        throw new ExecutionException(e.getMessage(), e);
    }

    CreateTagDialog dialog = new CreateTagDialog(getView(event).getSite().getShell(), currentBranchName, repo);

    if (dialog.open() != IDialogConstants.OK_ID)
        return null;

    final TagBuilder tag = new TagBuilder();
    PersonIdent personIdent = new PersonIdent(repo);
    String tagName = dialog.getTagName();

    tag.setTag(tagName);
    tag.setTagger(personIdent);
    tag.setMessage(dialog.getTagMessage());
    tag.setObjectId(getTagTarget(dialog.getTagCommit(), repo));

    String tagJobName = NLS.bind(UIText.TagAction_creating, tagName);
    final boolean shouldMoveTag = dialog.shouldOverWriteTag();

    Job tagJob = new Job(tagJobName) {
        protected IStatus run(IProgressMonitor monitor) {
            try {
                new TagOperation(repo, tag, shouldMoveTag).execute(monitor);
            } catch (CoreException e) {
                return Activator.createErrorStatus(UIText.TagAction_taggingFailed, e);
            } finally {
                GitLightweightDecorator.refresh();
            }

            return Status.OK_STATUS;
        }

        @Override
        public boolean belongsTo(Object family) {
            if (family.equals(JobFamilies.TAG))
                return true;
            return super.belongsTo(family);
        }
    };

    tagJob.setUser(true);
    tagJob.schedule();

    return null;
}

From source file:org.eclipse.egit.ui.internal.repository.tree.command.MergeCommand.java

License:Open Source License

private boolean canMerge(final Repository repository) {
    String message = null;//from  w  w w .ja v  a  2s .  c  o m
    Exception ex = null;
    try {
        Ref head = repository.getRef(Constants.HEAD);
        if (head == null || !head.isSymbolic())
            message = UIText.MergeAction_HeadIsNoBranch;
        else if (!repository.getRepositoryState().equals(RepositoryState.SAFE))
            message = NLS.bind(UIText.MergeAction_WrongRepositoryState, repository.getRepositoryState());
    } catch (IOException e) {
        message = e.getMessage();
        ex = e;
    }

    if (message != null) {
        Activator.handleError(UIText.MergeAction_CannotMerge, ex, true);
    }
    return (message == null);
}

From source file:org.eclipse.egit.ui.internal.repository.tree.RepositoriesViewPropertyTester.java

License:Open Source License

public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {

    if (!(receiver instanceof RepositoryTreeNode))
        return false;
    RepositoryTreeNode node = (RepositoryTreeNode) receiver;

    if (property.equals("isBare")) //$NON-NLS-1$
        return node.getRepository().isBare();

    if (property.equals("isSafe")) //$NON-NLS-1$
        return node.getRepository().getRepositoryState() == RepositoryState.SAFE;

    if (property.equals("isRefCheckedOut")) { //$NON-NLS-1$
        if (!(node.getObject() instanceof Ref))
            return false;
        Ref ref = (Ref) node.getObject();
        try {//from ww  w  . ja  v a2  s  .  com
            if (ref.getName().startsWith(Constants.R_REFS)) {
                return ref.getName().equals(node.getRepository().getFullBranch());
            } else if (ref.getName().equals(Constants.HEAD))
                return true;
            else {
                String leafname = ref.getLeaf().getName();
                if (leafname.startsWith(Constants.R_REFS)
                        && leafname.equals(node.getRepository().getFullBranch()))
                    return true;
                else
                    ref.getLeaf().getObjectId().equals(node.getRepository().resolve(Constants.HEAD));
            }
        } catch (IOException e) {
            return false;
        }
    }
    if (property.equals("isLocalBranch")) { //$NON-NLS-1$
        if (!(node.getObject() instanceof Ref))
            return false;
        Ref ref = (Ref) node.getObject();
        return ref.getName().startsWith(Constants.R_HEADS);
    }
    if (property.equals("fetchExists")) { //$NON-NLS-1$
        if (node instanceof RemoteNode) {
            String configName = ((RemoteNode) node).getObject();

            RemoteConfig rconfig;
            try {
                rconfig = new RemoteConfig(node.getRepository().getConfig(), configName);
            } catch (URISyntaxException e2) {
                return false;
            }
            // we need to have a fetch ref spec and a fetch URI
            return !rconfig.getFetchRefSpecs().isEmpty() && !rconfig.getURIs().isEmpty();
        }
    }
    if (property.equals("pushExists")) { //$NON-NLS-1$
        if (node instanceof RemoteNode) {
            String configName = ((RemoteNode) node).getObject();

            RemoteConfig rconfig;
            try {
                rconfig = new RemoteConfig(node.getRepository().getConfig(), configName);
            } catch (URISyntaxException e2) {
                return false;
            }
            // we need to have at least a push ref spec and any URI
            return !rconfig.getPushRefSpecs().isEmpty()
                    && (!rconfig.getPushURIs().isEmpty() || !rconfig.getURIs().isEmpty());
        }
    }
    if (property.equals("canMerge")) { //$NON-NLS-1$
        Repository rep = node.getRepository();
        if (rep.getRepositoryState() != RepositoryState.SAFE)
            return false;
        try {
            String branch = rep.getFullBranch();
            if (branch == null)
                return false; // fail gracefully...
            return branch.startsWith(Constants.R_HEADS);
        } catch (IOException e) {
            return false;
        }
    }

    if (property.equals("canAbortRebase")) //$NON-NLS-1$
        switch (node.getRepository().getRepositoryState()) {
        case REBASING_INTERACTIVE:
            return true;
        default:
            return false;
        }
    return false;
}

From source file:org.eclipse.egit.ui.internal.ResourcePropertyTester.java

License:Open Source License

/**
 * @param repository/*w w w.j  a v  a2 s .co m*/
 * @param property
 * @return true if the repository is in an appropriate state. See
 *         {@link ResourcePropertyTester}
 */
public static boolean testRepositoryState(Repository repository, String property) {
    if ("isShared".equals(property)) //$NON-NLS-1$
        return repository != null;
    if (repository != null) {
        // isSTATE checks repository state where STATE is the CamelCase version
        // of the RepositoryState enum values.
        RepositoryState state = repository.getRepositoryState();
        if (property.length() > 3 && property.startsWith("is")) { //$NON-NLS-1$
            // e.g. isCherryPickingResolved => CHERRY_PICKING_RESOLVED
            String lookFor = property.substring(2, 3)
                    + property.substring(3).replaceAll("([A-Z])", "_$1").toUpperCase(); //$NON-NLS-1$//$NON-NLS-2$
            if (state.toString().equals(lookFor))
                return true;
        }
        // invokes test methods of RepositoryState, canCommit etc
        try {
            Method method = RepositoryState.class.getMethod(property);
            if (method.getReturnType() == boolean.class) {
                Boolean ret = (Boolean) method.invoke(state);
                return ret.booleanValue();
            }
        } catch (Exception e) {
            // ignore
        }
    }
    return false;
}

From source file:org.eclipse.egit.ui.internal.staging.StagingView.java

License:Open Source License

private void reload(final Repository repository) {
    if (form.isDisposed())
        return;//from   ww  w .  jav a  2 s .c o  m
    if (repository == null) {
        asyncExec(new Runnable() {
            public void run() {
                clearRepository();
            }
        });
        return;
    }

    if (!isValidRepo(repository))
        return;

    final boolean repositoryChanged = currentRepository != repository;

    asyncExec(new Runnable() {
        public void run() {
            if (form.isDisposed())
                return;

            final IndexDiffData indexDiff = doReload(repository);

            boolean indexDiffAvailable = indexDiff != null;

            final StagingViewUpdate update = new StagingViewUpdate(currentRepository, indexDiff, null);
            unstagedTableViewer.setInput(update);
            stagedTableViewer.setInput(update);
            enableCommitWidgets(indexDiffAvailable);
            boolean commitEnabled = indexDiffAvailable && repository.getRepositoryState().canCommit();
            commitButton.setEnabled(commitEnabled);
            commitAndPushButton.setEnabled(commitEnabled);
            form.setText(StagingView.getRepositoryName(repository));
            updateCommitMessageComponent(repositoryChanged, indexDiffAvailable);
            updateSectionText();
        }
    });
}