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

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

Introduction

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

Prototype


public File getDirectory() 

Source Link

Document

Get local metadata directory

Usage

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

License:Open Source License

/**
 * Enable the command if all of the following conditions are fulfilled: <li>
 * All selected nodes belong to the same repository <li>All selected nodes
 * are of type FileNode or FolderNode or WorkingTreeNode <li>Each node does
 * not represent a file / folder in the git directory
 *
 * @param evaluationContext/*  www  . j  a  v  a 2s . c  om*/
 */
protected void enableWorkingDirCommand(Object evaluationContext) {
    if (!(evaluationContext instanceof IEvaluationContext)) {
        setBaseEnabled(false);
        return;
    }
    IEvaluationContext context = (IEvaluationContext) evaluationContext;
    Object selection = context.getVariable(ISources.ACTIVE_CURRENT_SELECTION_NAME);
    if (!(selection instanceof TreeSelection)) {
        setBaseEnabled(false);
        return;
    }
    Repository repository = null;
    TreeSelection treeSelection = (TreeSelection) selection;
    for (Iterator iterator = treeSelection.iterator(); iterator.hasNext();) {
        Object object = iterator.next();
        if (!(object instanceof RepositoryTreeNode)) {
            setBaseEnabled(false);
            return;
        }
        Repository nodeRepository = ((RepositoryTreeNode) object).getRepository();
        if (repository == null)
            repository = nodeRepository;
        else if (repository != nodeRepository) {
            setBaseEnabled(false);
            return;
        }
        if (!(object instanceof WorkingDirNode)) {
            String path;
            if (object instanceof FolderNode)
                path = ((FolderNode) object).getObject().getAbsolutePath();
            else if (object instanceof FileNode)
                path = ((FileNode) object).getObject().getAbsolutePath();
            else {
                setBaseEnabled(false);
                return;
            }
            if (path.startsWith(repository.getDirectory().getAbsolutePath())) {
                setBaseEnabled(false);
                return;
            }
        }
    }

    setBaseEnabled(true);
}

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

License:Open Source License

public Object execute(ExecutionEvent event) throws ExecutionException {
    final RepositoryTreeNode node = getSelectedNodes(event).get(0);
    final String refName = getRefName(node);
    if (refName == null)
        return null;

    String secondRefName = Constants.HEAD;
    if (getSelectedNodes(event).size() == 2) {
        secondRefName = getRefName(getSelectedNodes(event).get(1));
        if (secondRefName == null)
            return null;
    }// ww w  . ja v  a2  s  . com

    final String secondRefNameParam = secondRefName;

    final boolean includeLocal = getSelectedNodes(event).size() == 1;

    final Repository repo = node.getRepository();
    Job job = new Job(NLS.bind(UIText.SelectSynchronizeResourceDialog_selectProject, repo.getDirectory())) {

        @Override
        protected IStatus run(IProgressMonitor monitor) {
            GitSynchronizeData data;
            try {
                data = new GitSynchronizeData(repo, secondRefNameParam, refName, includeLocal);

                Set<IProject> projects = data.getProjects();
                IResource[] resources = projects.toArray(new IResource[projects.size()]);

                GitModelSynchronize.launch(data, resources);
            } catch (IOException e) {
                Activator.logError(e.getMessage(), e);
            }

            return Status.OK_STATUS;
        }
    };
    job.setUser(true);
    job.schedule();

    return null;
}

From source file:org.eclipse.egit.ui.internal.search.CommitSearchQuery.java

License:Open Source License

/**
 * @see org.eclipse.search.ui.ISearchQuery#run(org.eclipse.core.runtime.IProgressMonitor)
 */// w w w. j av a 2s  .  co m
public IStatus run(IProgressMonitor monitor) throws OperationCanceledException {
    this.result.removeAll();

    Pattern pattern = PatternUtils.createPattern(this.settings.getTextPattern(),
            this.settings.isCaseSensitive(), this.settings.isRegExSearch());
    List<String> paths = settings.getRepositories();
    try {
        for (String path : paths) {
            if (monitor.isCanceled())
                throw new OperationCanceledException();

            Repository repo = getRepository(path);
            if (repo == null)
                continue;

            monitor.setTaskName(MessageFormat.format(UIText.CommitSearchQuery_TaskSearchCommits,
                    repo.getDirectory().getParentFile().getName()));
            walkRepository(repo, pattern, monitor);
        }
    } catch (IOException e) {
        org.eclipse.egit.ui.Activator.handleError("Error searching commits", e, true); //$NON-NLS-1$
    }
    return Status.OK_STATUS;
}

From source file:org.eclipse.egit.ui.internal.selection.RepositorySourceProvider.java

License:Open Source License

@Override
public Map getCurrentState() {
    @SuppressWarnings("resource")
    Repository repository = repositoryRef == null ? null : repositoryRef.get();
    if (repository == null) {
        return Collections.singletonMap(REPOSITORY_PROPERTY, ""); //$NON-NLS-1$
    }/*  www  . j a v  a  2 s.  c o  m*/
    return Collections.singletonMap(REPOSITORY_PROPERTY, repository.getDirectory().getAbsolutePath());
}

From source file:org.eclipse.egit.ui.internal.selection.RepositorySourceProvider.java

License:Open Source License

@Override
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
    Repository newRepository;
    if (selection == null) {
        newRepository = null;/*from w w w  . j  a v  a2s .  c  om*/
    } else {
        newRepository = SelectionUtils.getRepository(SelectionUtils.getStructuredSelection(selection));
    }
    @SuppressWarnings("resource")
    Repository currentRepository = repositoryRef == null ? null : repositoryRef.get();
    if (currentRepository == null && repositoryRef != null) {
        repositoryRef = null;
        if (newRepository == null) {
            // Last evaluation was non-null, but that repo has since gone.
            fireSourceChanged(ISources.ACTIVE_WORKBENCH_WINDOW, REPOSITORY_PROPERTY, ""); //$NON-NLS-1$
            return;
        }
    }
    if (currentRepository != newRepository) {
        if (newRepository != null) {
            repositoryRef = new WeakReference<>(newRepository);
            fireSourceChanged(ISources.ACTIVE_WORKBENCH_WINDOW, REPOSITORY_PROPERTY,
                    newRepository.getDirectory().getAbsolutePath());
        } else {
            repositoryRef = null;
            fireSourceChanged(ISources.ACTIVE_WORKBENCH_WINDOW, REPOSITORY_PROPERTY, ""); //$NON-NLS-1$
        }
    }
}

From source file:org.eclipse.egit.ui.internal.sharing.RepoComboLabelProvider.java

License:Open Source License

public String getText(Object element) {
    Repository repo = (Repository) element;
    String repoName = util.getRepositoryName(repo);
    return NLS.bind("{0} - {1}", repoName, repo.getDirectory().getPath()); //$NON-NLS-1$
}

From source file:org.eclipse.egit.ui.internal.sharing.SharingWizard.java

License:Open Source License

public boolean performFinish() {
    if (!existingPage.getInternalMode()) {
        try {// w ww .  j a  v a  2 s .c  o m
            final Map<IProject, File> projectsToMove = existingPage.getProjects(true);
            final Repository selectedRepository = existingPage.getSelectedRepsoitory();
            getContainer().run(false, false, new IRunnableWithProgress() {
                public void run(IProgressMonitor monitor)
                        throws InvocationTargetException, InterruptedException {
                    for (Map.Entry<IProject, File> entry : projectsToMove.entrySet()) {

                        IPath targetLocation = new Path(entry.getValue().getPath());
                        IPath currentLocation = entry.getKey().getLocation();
                        if (!targetLocation.equals(currentLocation)) {
                            MoveProjectOperation op = new MoveProjectOperation(entry.getKey(),
                                    entry.getValue().toURI(), UIText.SharingWizard_MoveProjectActionLabel);
                            try {
                                IStatus result = op.execute(monitor, null);
                                if (!result.isOK())
                                    throw new RuntimeException();
                            } catch (ExecutionException e) {
                                if (e.getCause() != null)
                                    throw new InvocationTargetException(e.getCause());
                                throw new InvocationTargetException(e);
                            }
                        }
                        try {
                            new ConnectProviderOperation(entry.getKey(), selectedRepository.getDirectory())
                                    .execute(monitor);
                        } catch (CoreException e) {
                            throw new InvocationTargetException(e);
                        }
                    }
                }
            });
        } catch (InvocationTargetException e) {
            Activator.handleError(UIText.SharingWizard_failed, e.getCause(), true);
            return false;
        } catch (InterruptedException e) {
            // ignore for the moment
        }
        return true;
    } else {
        final ConnectProviderOperation op = new ConnectProviderOperation(existingPage.getProjects(true));
        try {
            getContainer().run(true, false, new IRunnableWithProgress() {
                public void run(final IProgressMonitor monitor) throws InvocationTargetException {
                    try {
                        op.execute(monitor);
                        PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
                            public void run() {
                                Set<File> filesToAdd = new HashSet<File>();
                                // collect all files first
                                for (Entry<IProject, File> entry : existingPage.getProjects(true).entrySet())
                                    filesToAdd.add(entry.getValue());
                                // add the files to the repository
                                // view
                                for (File file : filesToAdd)
                                    Activator.getDefault().getRepositoryUtil().addConfiguredRepository(file);
                            }
                        });
                    } catch (CoreException ce) {
                        throw new InvocationTargetException(ce);
                    }
                }
            });
            return true;
        } catch (Throwable e) {
            if (e instanceof InvocationTargetException) {
                e = e.getCause();
            }
            if (e instanceof CoreException) {
                IStatus status = ((CoreException) e).getStatus();
                e = status.getException();
            }
            Activator.handleError(UIText.SharingWizard_failed, e, true);
            return false;
        }
    }
}

From source file:org.eclipse.egit.ui.RepositoryUtil.java

License:Open Source License

/**
 * Tries to map a commit to a symbolic reference.
 * <p>/*from  www . j av  a 2  s  .c o m*/
 * This value will be cached for the given commit ID unless refresh is
 * specified. The return value will be the full name, e.g.
 * "refs/remotes/someBranch", "refs/tags/v.1.0"
 * <p>
 * Since this mapping is not unique, the following precedence rules are
 * used:
 * <ul>
 * <li>Tags take precedence over branches</li>
 * <li>Local branches take preference over remote branches</li>
 * <li>Newer references take precedence over older ones where time stamps
 * are available</li>
 * <li>If there are still ambiguities, the reference name with the highest
 * lexicographic value will be returned</li>
 * </ul>
 *
 * @param repository
 *            the {@link Repository}
 * @param commitId
 *            a commit
 * @param refresh
 *            if true, the cache will be invalidated
 * @return the symbolic reference, or <code>null</code> if no such reference
 *         can be found
 */
public String mapCommitToRef(Repository repository, String commitId, boolean refresh) {

    synchronized (commitMappingCache) {

        if (!ObjectId.isId(commitId)) {
            return null;
        }

        Map<String, String> cacheEntry = commitMappingCache.get(repository.getDirectory().toString());
        if (!refresh && cacheEntry != null && cacheEntry.containsKey(commitId)) {
            // this may be null in fact
            return cacheEntry.get(commitId);
        }
        if (cacheEntry == null) {
            cacheEntry = new HashMap<String, String>();
            commitMappingCache.put(repository.getDirectory().getPath(), cacheEntry);
        } else {
            cacheEntry.clear();
        }

        Map<String, Date> tagMap = new HashMap<String, Date>();
        try {
            Map<String, Ref> tags = repository.getRefDatabase().getRefs(Constants.R_TAGS);
            for (Ref tagRef : tags.values()) {
                Tag tag = repository.mapTag(tagRef.getName());
                if (tag.getObjId().name().equals(commitId)) {
                    Date timestamp;
                    if (tag.getTagger() != null) {
                        timestamp = tag.getTagger().getWhen();
                    } else {
                        timestamp = null;
                    }
                    tagMap.put(tagRef.getName(), timestamp);
                }
            }
        } catch (IOException e) {
            // ignore here
        }

        String cacheValue = null;

        if (!tagMap.isEmpty()) {
            // we try to obtain the "latest" tag
            Date compareDate = new Date(0);
            for (Map.Entry<String, Date> tagEntry : tagMap.entrySet()) {
                if (tagEntry.getValue() != null && tagEntry.getValue().after(compareDate)) {
                    compareDate = tagEntry.getValue();
                    cacheValue = tagEntry.getKey();
                }
            }
            // if we don't have time stamps, we sort
            if (cacheValue == null) {
                String compareString = ""; //$NON-NLS-1$
                for (String tagName : tagMap.keySet()) {
                    if (tagName.compareTo(compareString) >= 0) {
                        cacheValue = tagName;
                        compareString = tagName;
                    }
                }
            }
        }

        if (cacheValue == null) {
            // we didnt't find a tag, so let's look for local branches
            Set<String> branchNames = new TreeSet<String>();
            // put this into a sorted set
            try {
                Map<String, Ref> remoteBranches = repository.getRefDatabase().getRefs(Constants.R_HEADS);
                for (Ref branch : remoteBranches.values()) {
                    if (branch.getObjectId().name().equals(commitId)) {
                        branchNames.add(branch.getName());
                    }
                }
            } catch (IOException e) {
                // ignore here
            }
            if (!branchNames.isEmpty()) {
                // get the last (sorted) entry
                cacheValue = branchNames.toArray(new String[branchNames.size()])[branchNames.size() - 1];
            }
        }

        if (cacheValue == null) {
            // last try: remote branches
            Set<String> branchNames = new TreeSet<String>();
            // put this into a sorted set
            try {
                Map<String, Ref> remoteBranches = repository.getRefDatabase().getRefs(Constants.R_REMOTES);
                for (Ref branch : remoteBranches.values()) {
                    if (branch.getObjectId().name().equals(commitId)) {
                        branchNames.add(branch.getName());
                    }
                }
                if (!branchNames.isEmpty()) {
                    // get the last (sorted) entry
                    cacheValue = branchNames.toArray(new String[branchNames.size()])[branchNames.size() - 1];
                }
            } catch (IOException e) {
                // ignore here
            }
        }
        cacheEntry.put(commitId, cacheValue);
        return cacheValue;
    }
}

From source file:org.eclipse.egit.ui.RepositoryUtil.java

License:Open Source License

/**
 * Return a cached UI "name" for a Repository
 * <p>/*from   ww w  .j  av  a 2  s  .co  m*/
 * This uses the name of the parent of the repository's directory.
 *
 * @param repository
 * @return the name
 */
public String getRepositoryName(Repository repository) {
    synchronized (repositoryNameCache) {
        File gitDir = repository.getDirectory();
        if (gitDir != null) {
            String name = repositoryNameCache.get(gitDir.getPath().toString());
            if (name != null) {
                return name;
            }
            name = gitDir.getParentFile().getName();
            repositoryNameCache.put(gitDir.getPath().toString(), name);
            return name;
        }
    }
    return ""; //$NON-NLS-1$
}

From source file:org.eclipse.egit.ui.search.CommitSearchQueryTest.java

License:Open Source License

private void validateResult(RevCommit expectedCommit, Repository expectedRepository, ISearchResult result) {
    assertNotNull(result);/*from ww  w . j  a  v a 2s . c om*/
    assertTrue(result instanceof CommitSearchResult);
    CommitSearchResult commitResult = (CommitSearchResult) result;
    assertEquals(1, commitResult.getMatchCount());
    Object[] elements = commitResult.getElements();
    assertNotNull(elements);
    assertEquals(1, elements.length);
    assertTrue(elements[0] instanceof RepositoryCommit);
    RepositoryCommit repoCommit = (RepositoryCommit) elements[0];
    assertEquals(expectedRepository.getDirectory(), repoCommit.getRepository().getDirectory());
    assertEquals(expectedCommit, repoCommit.getRevCommit());
}