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.emf.compare.egit.ui.internal.merge.ModelGitMergeEditorInput.java

License:Open Source License

private IDiffContainer buildDiffContainer(Repository repository, RevCommit headCommit, RevCommit ancestorCommit,
        List<String> filterPaths, RevWalk rw, IProgressMonitor monitor)
        throws IOException, InterruptedException {

    monitor.setTaskName(UIText.GitMergeEditorInput_CalculatingDiffTaskName);
    IDiffContainer result = new DiffNode(Differencer.CONFLICTING);

    TreeWalk tw = new TreeWalk(repository);
    try {/* w  w w . jav a2s . c  o m*/
        int dirCacheIndex = tw.addTree(new DirCacheIterator(repository.readDirCache()));
        int fileTreeIndex = tw.addTree(new FileTreeIterator(repository));
        int repositoryTreeIndex = tw.addTree(rw.parseTree(repository.resolve(Constants.HEAD)));

        // skip ignored resources
        NotIgnoredFilter notIgnoredFilter = new NotIgnoredFilter(fileTreeIndex);
        // filter by selected resources
        if (filterPaths.size() > 1) {
            List<TreeFilter> suffixFilters = new ArrayList<TreeFilter>();
            for (String filterPath : filterPaths) {
                suffixFilters.add(PathFilter.create(filterPath));
            }
            TreeFilter otf = OrTreeFilter.create(suffixFilters);
            tw.setFilter(AndTreeFilter.create(otf, notIgnoredFilter));
        } else if (filterPaths.size() > 0) {
            String path = filterPaths.get(0);
            if (path.length() == 0) {
                tw.setFilter(notIgnoredFilter);
            } else {
                tw.setFilter(AndTreeFilter.create(PathFilter.create(path), notIgnoredFilter));
            }
        } else {
            tw.setFilter(notIgnoredFilter);
        }

        tw.setRecursive(true);

        while (tw.next()) {
            if (monitor.isCanceled()) {
                throw new InterruptedException();
            }
            String gitPath = tw.getPathString();
            monitor.setTaskName(gitPath);

            FileTreeIterator fit = tw.getTree(fileTreeIndex, FileTreeIterator.class);
            if (fit == null) {
                continue;
            }

            DirCacheIterator dit = tw.getTree(dirCacheIndex, DirCacheIterator.class);

            final DirCacheEntry dirCacheEntry = dit == null ? null : dit.getDirCacheEntry();

            boolean conflicting = dirCacheEntry != null && dirCacheEntry.getStage() > 0;

            AbstractTreeIterator rt = tw.getTree(repositoryTreeIndex, AbstractTreeIterator.class);

            // compare local file against HEAD to see if it was modified
            boolean modified = rt != null && !fit.getEntryObjectId().equals(rt.getEntryObjectId());

            // if this is neither conflicting nor changed, we skip it
            if (!conflicting && !modified) {
                continue;
            }

            ITypedElement right;
            if (conflicting) {
                GitFileRevision revision = GitFileRevision.inIndex(repository, gitPath, DirCacheEntry.STAGE_3);
                String encoding = CompareCoreUtils.getResourceEncoding(repository, gitPath);
                right = new FileRevisionTypedElement(revision, encoding);
            } else {
                right = CompareUtils.getFileRevisionTypedElement(gitPath, headCommit, repository);
            }

            // can this really happen?
            if (right instanceof EmptyTypedElement) {
                continue;
            }

            IFileRevision rev;
            // if the file is not conflicting (as it was auto-merged)
            // we will show the auto-merged (local) version

            Path repositoryPath = new Path(repository.getWorkTree().getAbsolutePath());
            IPath location = repositoryPath.append(fit.getEntryPathString());
            IFile file = ResourceUtil.getFileForLocation(location, false);
            if (!conflicting || useWorkspace) {
                if (file != null) {
                    rev = new LocalFileRevision(file);
                } else {
                    rev = new WorkingTreeFileRevision(location.toFile());
                }
            } else {
                rev = GitFileRevision.inIndex(repository, gitPath, DirCacheEntry.STAGE_2);
            }

            IRunnableContext runnableContext = getContainer();
            if (runnableContext == null) {
                runnableContext = PlatformUI.getWorkbench().getProgressService();
            }

            EditableRevision leftEditable;
            if (file != null) {
                leftEditable = new ResourceEditableRevision(rev, file, runnableContext);
            } else {
                leftEditable = new LocationEditableRevision(rev, location, runnableContext);
            }
            // make sure we don't need a round trip later
            try {
                leftEditable.cacheContents(monitor);
            } catch (CoreException e) {
                throw new IOException(e.getMessage());
            }

            int kind = Differencer.NO_CHANGE;
            if (conflicting) {
                kind = Differencer.CONFLICTING;
            } else if (modified) {
                kind = Differencer.PSEUDO_CONFLICT;
            }

            IDiffContainer fileParent = getFileParent(result, repositoryPath, file, location);

            ITypedElement anc;
            if (ancestorCommit != null) {
                anc = CompareUtils.getFileRevisionTypedElement(gitPath, ancestorCommit, repository);
            } else {
                anc = null;
            }
            // we get an ugly black icon if we have an EmptyTypedElement
            // instead of null
            if (anc instanceof EmptyTypedElement) {
                anc = null;
            }
            // create the node as child
            new DiffNode(fileParent, kind, anc, leftEditable, right);
        }
        return result;
    } finally {
        tw.close();
    }
}

From source file:org.eclipse.ice.developer.actions.GitCloneHandler.java

License:Open Source License

/**
 * This private method is used to import existing projects into the project
 * explorer.//from  w w w .  ja  va 2s.c  o m
 * 
 * @param repository
 * @param sets
 */
protected void importProjects(final Repository repository, final IWorkingSet[] sets) {
    String repoName = Activator.getDefault().getRepositoryUtil().getRepositoryName(repository);
    Job importJob = new WorkspaceJob(MessageFormat.format(UIText.GitCloneWizard_jobImportProjects, repoName)) {

        @Override
        public IStatus runInWorkspace(IProgressMonitor monitor) {
            List<File> files = new ArrayList<File>();
            ProjectUtil.findProjectFiles(files, repository.getWorkTree(), true, monitor);
            if (files.isEmpty()) {
                return Status.OK_STATUS;
            }

            Set<ProjectRecord> projectRecords = new LinkedHashSet<ProjectRecord>();
            for (File file : files) {
                projectRecords.add(new ProjectRecord(file));
            }
            try {
                ProjectUtils.createProjects(projectRecords, sets, monitor);
            } catch (InvocationTargetException | InterruptedException e) {
                Activator.logError(e.getLocalizedMessage(), e);
            }

            return Status.OK_STATUS;
        }
    };
    importJob.schedule();
}

From source file:org.eclipse.mylyn.internal.git.core.GitConnector.java

License:Open Source License

@Override
public ChangeSet getChangeSet(ScmRepository repository, IFileRevision revision, IProgressMonitor monitor)
        throws CoreException {
    Repository repository2 = ((GitRepository) repository).getRepository();
    RevWalk walk = new RevWalk(repository2);
    try {/*w w w.  j  av  a  2  s . co m*/
        RevCommit commit;
        commit = walk.parseCommit(ObjectId.fromString(revision.getContentIdentifier()));
        TreeWalk treeWalk = new TreeWalk(repository2);
        for (RevCommit p : commit.getParents()) {
            walk.parseHeaders(p);
            walk.parseBody(p);
            treeWalk.addTree(p.getTree());
            //we can compare with one parent only
            break;
        }
        treeWalk.addTree(commit.getTree());
        treeWalk.setRecursive(true);

        List<DiffEntry> entries = DiffEntry.scan(treeWalk);
        List<Change> changes = new ArrayList<Change>();
        File repoDir = repository2.getWorkTree().getAbsoluteFile();

        //define working area repo URI
        IPath repoWorkAreaPath = new Path(repoDir.getAbsolutePath()).addTrailingSeparator();

        for (DiffEntry d : entries) {
            // FIXME - could not work for renaming
            if (!d.getChangeType().equals(org.eclipse.jgit.diff.DiffEntry.ChangeType.RENAME)
                    && d.getOldId().equals(d.getNewId())) {
                continue;
            }

            //Create old and new artifacts with IResource information if available from the current workspace
            ScmArtifact newArtifact = getArtifact(repository, d, false, repoWorkAreaPath);
            ScmArtifact oldArtifact = getArtifact(repository, d, true, repoWorkAreaPath);

            changes.add(new Change(oldArtifact, newArtifact, mapChangeType(d.getChangeType())));
        }

        return changeSet(commit, repository, changes);

    } catch (Exception e) {
        e.printStackTrace();
        throw new CoreException(new Status(IStatus.ERROR, GitConnector.PLUGIN_ID, e.getMessage()));
    }

}

From source file:org.eclipse.mylyn.internal.github.ui.pr.PullRequestContextSynchronizer.java

License:Open Source License

public void taskActivated(ITask task) {
    if (task == null)
        return;//  w ww. ja  va  2s .  c om
    if (!PullRequestConnector.KIND.equals(task.getConnectorKind()))
        return;
    IInteractionContext context = ContextCore.getContextManager().getActiveContext();
    if (context == null)
        return;

    RevWalk walk = null;
    try {
        TaskData data = TasksUi.getTaskDataManager().getTaskData(task);
        PullRequestComposite prComp = PullRequestConnector.getPullRequest(data);
        if (prComp == null)
            return;
        PullRequest request = prComp.getRequest();
        Repository repository = PullRequestUtils.getRepository(request);
        if (repository == null)
            return;
        walk = new RevWalk(repository);
        TreeWalk diffs = new TreeWalk(walk.getObjectReader());
        diffs.setFilter(TreeFilter.ANY_DIFF);
        diffs.setRecursive(true);
        diffs.addTree(walk.parseCommit(ObjectId.fromString(request.getHead().getSha())).getTree());
        diffs.addTree(walk.parseCommit(ObjectId.fromString(request.getBase().getSha())).getTree());
        Set<IResource> resources = new HashSet<IResource>();
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        String base = repository.getWorkTree().getAbsolutePath() + "/"; //$NON-NLS-1$
        while (diffs.next()) {
            IFile file = root.getFileForLocation(Path.fromOSString(base + diffs.getPathString()));
            if (file != null)
                resources.add(file);
        }
        if (!resources.isEmpty())
            ResourcesUi.addResourceToContext(resources, InteractionEvent.Kind.SELECTION);
    } catch (MissingObjectException ignored) {
        // Ignored
    } catch (IOException e) {
        GitHubUi.logError(e);
    } catch (CoreException e) {
        GitHubUi.logError(e);
    } finally {
        if (walk != null)
            walk.release();
    }
}

From source file:org.eclipse.mylyn.reviews.r4e.ui.tests.utils.TestUtils.java

License:Open Source License

private static String getWorkDir(Repository aRepository) throws CoreException, IOException {
    String workDir;//from www. j  av  a  2  s .  co m
    try {
        workDir = aRepository.getWorkTree().getCanonicalPath();
    } catch (IOException err) {
        workDir = aRepository.getWorkTree().getAbsolutePath();
    }
    workDir = workDir.replace('\\', '/');
    if (!workDir.endsWith("/")) {
        workDir += "/"; //$NON-NLS-1$
    }
    return workDir;
}

From source file:org.eclipse.oomph.gitbash.GitApplyAction.java

License:Open Source License

private void addActionsToMenu() {
    ITaskAttachment attachment = getSelectedAttachment();
    if (attachment == null) {
        return;/*from w  w w. java  2  s .  com*/
    }

    Repository[] repositories = getRepositories();
    List<Repository> sorted = Arrays.asList(repositories);
    Collections.sort(sorted, new Comparator<Repository>() {
        public int compare(Repository r1, Repository r2) {
            String n1 = r1.getWorkTree().getName();
            String n2 = r2.getWorkTree().getName();
            return n1.compareTo(n2);
        }
    });

    for (Repository repository : sorted) {
        RepositorySelectionAction action = new RepositorySelectionAction(attachment, repository);
        ActionContributionItem item = new ActionContributionItem(action);
        item.fill(dropDownMenu, -1);
    }
}

From source file:org.eclipse.oomph.gitbash.repository.AbstractRepositoryAction.java

License:Open Source License

@Override
protected void run(Shell shell, Repository repository) throws Exception {
    run(shell, repository.getWorkTree());
}

From source file:org.eclipse.oomph.gitbash.repository.ListFilesAction.java

License:Open Source License

private File checkHistory(Repository repository, IProgressMonitor monitor) throws Exception {
    Git git = new Git(repository);

    int commitCount = getCommitCount(git);
    monitor.beginTask("Listing all files", commitCount);

    Map<String, Set<String>> namesByExtension = new HashMap<String, Set<String>>();

    for (RevCommit commit : git.log().call()) {
        TreeWalk walk = new TreeWalk(repository);
        walk.setRecursive(true);//from   w  w w .  jav a  2 s .  c  o m
        walk.addTree(commit.getTree());

        while (walk.next()) {
            checkCancelation(monitor);

            String name = walk.getNameString();
            String extension;

            int lastDot = name.lastIndexOf('.');
            if (lastDot == -1) {
                extension = "";
            } else {
                extension = name.substring(lastDot + 1);
                name = name.substring(0, lastDot);
            }

            Set<String> names = namesByExtension.get(extension);
            if (names == null) {
                names = new HashSet<String>();
                namesByExtension.put(extension, names);
            }

            names.add(name);
        }

        try {
            walk.close();
        } catch (Throwable ex) {
            try {
                Method method = walk.getClass().getMethod("release");
                method.invoke(walk);
            } catch (Throwable ignore) {
                //$FALL-THROUGH$
            }
        }

        monitor.worked(1);
    }

    final File file = new File("files-in-" + repository.getWorkTree().getName() + ".txt");
    PrintStream stream = new PrintStream(file);

    try {
        for (String extension : sort(namesByExtension.keySet())) {
            List<String> names = sort(namesByExtension.get(extension));
            System.out.println(extension + "\t" + names.size());

            stream.println(extension + "\t" + names.size());
            for (String name : names) {
                stream.println("\t" + name);
            }
        }
    } finally {
        stream.close();
    }

    return file;
}

From source file:org.eclipse.oomph.gitbash.repository.UpdateCopyrightsAction.java

License:Open Source License

@Override
protected void run(final Shell shell, final Repository repository) throws Exception {
    IRunnableWithProgress runnable = new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                git = new Git(repository);
                workTree = repository.getWorkTree();
                workTreeLength = workTree.getAbsolutePath().length() + 1;

                fileCount = countFiles(workTree);
                monitor.beginTask(getTitle(), fileCount);

                final long start = System.currentTimeMillis();
                checkFolder(monitor, workTree);

                shell.getDisplay().syncExec(new Runnable() {
                    public void run() {
                        try {
                            handleResult(shell, workTree, formatDuration(start));
                        } catch (Exception ex) {
                            Activator.log(ex);
                        }/* ww  w .  j  a  va  2 s. co m*/
                    }
                });
            } catch (OperationCanceledException ex) {
                // Do nothing
            } catch (Exception ex) {
                throw new InvocationTargetException(ex);
            } finally {
                missingCopyrights.clear();
                rewriteCount = 0;
                fileCount = 0;
                workTreeLength = 0;
                workTree = null;
                git = null;
                monitor.done();
            }
        }
    };

    WORKBENCH.getProgressService().run(true, true, runnable);
}

From source file:org.eclipse.oomph.gitbash.revision.AbstractRevisionAction.java

License:Open Source License

@Override
protected void run(Shell shell, RevObject revision) throws Exception {
    Repository repository = getRepository();
    if (repository != null) {
        File workTree = repository.getWorkTree();
        String id = revision.getId().name();
        run(shell, workTree, id);/*from w  ww . j a v  a  2  s  .c om*/
    }
}