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

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

Introduction

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

Prototype

@NonNull
public File getWorkTree() throws NoWorkTreeException 

Source Link

Document

Get the root directory of the working tree, where files are checked out for viewing and editing.

Usage

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

License:Open Source License

public Object execute(ExecutionEvent event) throws ExecutionException {
    List<FileNode> selectedNodes = getSelectedNodes(event);
    if (selectedNodes.isEmpty() || selectedNodes.get(0).getRepository() == null)
        return null;

    Repository repository = selectedNodes.get(0).getRepository();
    IPath workTreePath = new Path(repository.getWorkTree().getAbsolutePath());

    AddCommand addCommand = new Git(repository).add();

    Collection<IPath> paths = getSelectedFileAndFolderPaths(event);
    for (IPath path : paths) {
        String repoRelativepath;/*  www  . j av  a 2s  .c  o m*/
        if (path.equals(workTreePath))
            repoRelativepath = "."; //$NON-NLS-1$
        else
            repoRelativepath = path.removeFirstSegments(path.matchingFirstSegments(workTreePath))
                    .setDevice(null).toString();
        addCommand.addFilepattern(repoRelativepath);
    }
    try {
        addCommand.call();
    } catch (GitAPIException e) {
        Activator.logError(UIText.AddToIndexCommand_addingFilesFailed, e);
    }
    return null;
}

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

License:Open Source License

private List<File> getChangedFiles(RevCommit commit, Repository repo) {
    try {/*w ww  . jav a 2 s  .  co m*/
        List<File> files = new ArrayList<File>();
        try (TreeWalk tw = new TreeWalk(repo); final RevWalk walk = new RevWalk(repo)) {
            tw.setRecursive(true);
            FileDiff[] diffs = FileDiff.compute(repo, tw, commit, TreeFilter.ALL);
            if (diffs != null && diffs.length > 0) {
                String workDir = repo.getWorkTree().getAbsolutePath();
                for (FileDiff d : diffs) {
                    String path = d.getPath();
                    File f = new File(workDir + File.separator + path);
                    files.add(f);
                }
            }
        }
        return files;
    } catch (IOException e) {
        Activator.error(e.getMessage(), e);
    }
    return null;
}

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

License:Open Source License

private Set<File> findDotProjectFiles(List<File> files, Repository repo) {
    Set<File> result = new HashSet<File>();
    String workingTreeRootPath = repo.getWorkTree().toString();
    for (File changedFile : files) {
        File projectFile = searchEnclosingProjectInWorkDir(changedFile.getParentFile(), workingTreeRootPath);
        if (projectFile != null)
            result.add(projectFile);//from w ww .j ava  2 s . c  o m
    }
    return result;
}

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

License:Open Source License

/**
 * Remove or delete the repository//w w  w .  ja v a 2 s. c om
 *
 * @param event
 * @param delete
 *            if <code>true</code>, the repository will be deleted from disk
 */
protected void removeRepository(final ExecutionEvent event, final boolean delete) {
    IWorkbenchSite activeSite = HandlerUtil.getActiveSite(event);
    IWorkbenchSiteProgressService service = (IWorkbenchSiteProgressService) activeSite
            .getService(IWorkbenchSiteProgressService.class);

    // get selected nodes
    final List<RepositoryNode> selectedNodes;
    try {
        selectedNodes = getSelectedNodes(event);
    } catch (ExecutionException e) {
        Activator.handleError(e.getMessage(), e, true);
        return;
    }

    if (delete) {
        String title = UIText.RemoveCommand_DeleteConfirmTitle;
        if (selectedNodes.size() > 1) {
            String message = NLS.bind(UIText.RemoveCommand_DeleteConfirmSingleMessage,
                    Integer.valueOf(selectedNodes.size()));
            if (!MessageDialog.openConfirm(getShell(event), title, message))
                return;
        } else if (selectedNodes.size() == 1) {
            String name = org.eclipse.egit.core.Activator.getDefault().getRepositoryUtil()
                    .getRepositoryName(selectedNodes.get(0).getObject());
            String message = NLS.bind(UIText.RemoveCommand_DeleteConfirmMultiMessage, name);
            if (!MessageDialog.openConfirm(getShell(event), title, message))
                return;
        }
    }

    Job job = new Job("Remove Repositories Job") { //$NON-NLS-1$

        @Override
        protected IStatus run(IProgressMonitor monitor) {
            final List<IProject> projectsToDelete = new ArrayList<IProject>();

            monitor.setTaskName(UIText.RepositoriesView_DeleteRepoDeterminProjectsMessage);

            for (RepositoryNode node : selectedNodes) {
                if (node.getRepository().isBare())
                    continue;
                File workDir = node.getRepository().getWorkTree();
                final IPath wdPath = new Path(workDir.getAbsolutePath());
                for (IProject prj : ResourcesPlugin.getWorkspace().getRoot().getProjects()) {
                    if (monitor.isCanceled())
                        return Status.OK_STATUS;
                    if (wdPath.isPrefixOf(prj.getLocation())) {
                        projectsToDelete.add(prj);
                    }
                }
            }

            final boolean[] confirmedCanceled = new boolean[] { false, false };

            if (!projectsToDelete.isEmpty()) {
                Display.getDefault().syncExec(new Runnable() {

                    public void run() {
                        try {
                            confirmedCanceled[0] = confirmProjectDeletion(projectsToDelete, event);
                        } catch (OperationCanceledException e) {
                            confirmedCanceled[1] = true;
                        }
                    }
                });
            }
            if (confirmedCanceled[1]) {
                // canceled: return
                return Status.OK_STATUS;
            }
            if (confirmedCanceled[0]) {
                // confirmed deletion
                IWorkspaceRunnable wsr = new IWorkspaceRunnable() {

                    public void run(IProgressMonitor actMonitor) throws CoreException {

                        for (IProject prj : projectsToDelete)
                            prj.delete(false, false, actMonitor);
                    }
                };

                try {
                    ResourcesPlugin.getWorkspace().run(wsr, ResourcesPlugin.getWorkspace().getRoot(),
                            IWorkspace.AVOID_UPDATE, monitor);
                } catch (CoreException e1) {
                    Activator.logError(e1.getMessage(), e1);
                }
            }
            for (RepositoryNode node : selectedNodes) {
                util.removeDir(node.getRepository().getDirectory());
            }

            if (delete) {
                try {
                    for (RepositoryNode node : selectedNodes) {
                        Repository repo = node.getRepository();
                        if (!repo.isBare())
                            FileUtils.delete(repo.getWorkTree(), FileUtils.RECURSIVE | FileUtils.RETRY);
                        FileUtils.delete(repo.getDirectory(),
                                FileUtils.RECURSIVE | FileUtils.RETRY | FileUtils.SKIP_MISSING);
                    }
                } catch (IOException e) {
                    return Activator.createErrorStatus(e.getMessage(), e);
                }
            }
            return Status.OK_STATUS;
        }
    };

    service.schedule(job);
}

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

License:Open Source License

/**
 * Get submodule from selected nodes/* ww  w.  j a  v a2s. c  o m*/
 * <p>
 * Keys with null values denote repositories where all submodules should be
 * used for the current command being executed
 *
 * @param nodes
 * @return non-null but possibly empty map of parent repository's to
 *         submodule paths
 */
protected Map<Repository, List<String>> getSubmodules(final List<RepositoryTreeNode<?>> nodes) {
    final Map<Repository, List<String>> repoPaths = new HashMap<Repository, List<String>>();
    for (RepositoryTreeNode<?> node : nodes) {
        if (node.getType() == RepositoryTreeNodeType.REPO) {
            Repository parent = node.getParent().getRepository();
            String path = Repository.stripWorkDir(parent.getWorkTree(), node.getRepository().getWorkTree());
            List<String> paths = repoPaths.get(parent);
            if (paths == null) {
                paths = new ArrayList<String>();
                repoPaths.put(parent, paths);
            }
            paths.add(path);
        }
    }
    for (RepositoryTreeNode<?> node : nodes)
        if (node.getType() == RepositoryTreeNodeType.SUBMODULES)
            // Clear paths so all submodules are updated
            repoPaths.put(node.getParent().getRepository(), null);
    return repoPaths;
}

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

License:Open Source License

/**
 * TODO javadoc missing//from  w w  w . j a v a 2 s  .  c  om
 */
@SuppressWarnings("unchecked")
public IStructuredSelection findSelection(IEditorInput anInput) {
    if (!(anInput instanceof IURIEditorInput)) {
        return null;
    }

    URI uri = ((IURIEditorInput) anInput).getURI();

    if (!uri.getScheme().equals("file")) //$NON-NLS-1$
        return null;

    File file = new File(uri.getPath());

    if (!file.exists())
        return null;

    RepositoryUtil config = Activator.getDefault().getRepositoryUtil();

    List<String> repos = config.getConfiguredRepositories();
    for (String repo : repos) {
        Repository repository;
        try {
            repository = new FileRepository(new File(repo));
        } catch (IOException e) {
            continue;
        }
        if (repository.isBare())
            continue;
        if (file.getPath().startsWith(repository.getWorkTree().getPath())) {
            RepositoriesViewContentProvider cp = new RepositoriesViewContentProvider();

            RepositoryNode repoNode = new RepositoryNode(null, repository);
            RepositoryTreeNode result = null;

            for (Object child : cp.getChildren(repoNode)) {
                if (child instanceof WorkingDirNode) {
                    result = (WorkingDirNode) child;
                    break;
                }
            }

            if (result == null)
                return null;

            IPath remainingPath = new Path(
                    file.getPath().substring(repository.getWorkTree().getPath().length()));
            for (String segment : remainingPath.segments()) {
                for (Object child : cp.getChildren(result)) {
                    RepositoryTreeNode<File> fileNode;
                    try {
                        fileNode = (RepositoryTreeNode<File>) child;
                    } catch (ClassCastException e) {
                        return null;
                    }
                    if (fileNode.getObject().getName().equals(segment)) {
                        result = fileNode;
                        break;
                    }
                }
            }

            return new StructuredSelection(result);
        }
    }
    return null;
}

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

License:Open Source License

/**
 * @param repository// w  w  w.  ja  v a  2  s.  c  om
 *            to check
 */
public RepositorySaveableFilter(Repository repository) {
    super(ProjectUtil.getProjects(repository));
    this.workDir = new Path(repository.getWorkTree().getAbsolutePath());
}

From source file:org.eclipse.egit.ui.internal.resources.ResourceStateFactory.java

License:Open Source License

/**
 * Computes an {@link IResourceState} for the given {@link FileSystemItem}
 * from the given {@link IndexDiffData}.
 *
 * @param indexDiffData//from  w  ww  .jav a 2s  . com
 *            to compute the state from
 * @param file
 *            to get the state of
 * @return the state
 */
@NonNull
private IResourceState get(@NonNull IndexDiffData indexDiffData, @NonNull FileSystemItem file) {
    IPath path = file.getAbsolutePath();
    if (path == null) {
        return UNKNOWN_STATE;
    }
    Repository repository = file.getRepository();
    if (repository == null || repository.isBare()) {
        return UNKNOWN_STATE;
    }
    File workTree = repository.getWorkTree();
    String repoRelativePath = path.makeRelativeTo(new org.eclipse.core.runtime.Path(workTree.getAbsolutePath()))
            .toString();
    if (repoRelativePath.equals(path.toString())) {
        // Could not be made relative.
        return UNKNOWN_STATE;
    }
    ResourceState result = new ResourceState();
    if (file.isContainer()) {
        if (!repoRelativePath.endsWith("/")) { //$NON-NLS-1$
            repoRelativePath += '/';
        }
        if (ResourceUtil.isSymbolicLink(repository, repoRelativePath)) {
            // The Eclipse resource model handles a symlink to a folder like
            // the container it refers to but git status handles the symlink
            // source like a special file.
            extractFileProperties(indexDiffData, repoRelativePath, result);
        } else {
            extractContainerProperties(indexDiffData, repoRelativePath, file, result);
        }
    } else {
        extractFileProperties(indexDiffData, repoRelativePath, result);
    }
    return result;
}

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

License:Open Source License

private boolean isValidRepo(final Repository repository) {
    return repository != null && !repository.isBare() && repository.getWorkTree().exists()
            && org.eclipse.egit.core.Activator.getDefault().getRepositoryUtil().contains(repository);
}

From source file:org.eclipse.egit.ui.internal.synchronize.GitModelSynchronizeParticipant.java

License:Open Source License

private ICompareInput getFileFromGit(GitSynchronizeData gsd, IPath location) {
    Repository repo = gsd.getRepository();
    File workTree = repo.getWorkTree();
    String repoRelativeLocation = Repository.stripWorkDir(workTree, location.toFile());

    TreeWalk tw = new TreeWalk(repo);
    tw.setRecursive(true);//from  w  w  w .  java 2  s.  c om
    tw.setFilter(PathFilter.create(repoRelativeLocation.toString()));
    RevCommit baseCommit = gsd.getSrcRevCommit();
    RevCommit remoteCommit = gsd.getDstRevCommit();

    try {
        int baseNth = tw.addTree(baseCommit.getTree());
        int remoteNth = tw.addTree(remoteCommit.getTree());

        if (tw.next()) {
            ComparisonDataSource baseData = new ComparisonDataSource(baseCommit, tw.getObjectId(baseNth));
            ComparisonDataSource remoteData = new ComparisonDataSource(remoteCommit, tw.getObjectId(remoteNth));
            return new GitCompareInput(repo, baseData, baseData, remoteData, repoRelativeLocation);
        }
    } catch (IOException e) {
        Activator.logError(e.getMessage(), e);
    }

    return null;
}