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.synchronize.mapping.GitTreeTraversal.java

License:Open Source License

public GitTreeTraversal(Repository repo, RevCommit commit) {
    this(repo, commit, new Path(repo.getWorkTree().toString()));
}

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

License:Open Source License

/**
 *
 * @param root/*from  w  ww  .  j  a v a  2 s.  com*/
 *            the root node of the tree to build, which will become the
 *            parent of the first level of children
 * @param repo
 * @param changes
 * @param fileFactory
 * @param treeFactory
 * @return the children of the root nodes
 */
public static GitModelObject[] build(final GitModelObjectContainer root, final Repository repo,
        final Map<String, Change> changes, final FileModelFactory fileFactory,
        final TreeModelFactory treeFactory) {

    if (changes == null || changes.isEmpty())
        return new GitModelObject[] {};

    final IPath rootPath = new Path(repo.getWorkTree().getAbsolutePath());
    final List<GitModelObject> rootChildren = new ArrayList<GitModelObject>();

    final Map<IPath, Node> nodes = new HashMap<IPath, Node>();

    for (Map.Entry<String, Change> entry : changes.entrySet()) {
        String repoRelativePath = entry.getKey();
        Change change = entry.getValue();

        GitModelObjectContainer parent = root;
        List<GitModelObject> children = rootChildren;
        IPath path = rootPath;

        String[] segments = repoRelativePath.split("/"); //$NON-NLS-1$

        for (int i = 0; i < segments.length; i++) {
            path = path.append(segments[i]);

            // Changes represent files, so the last segment is the file name
            boolean fileNode = (i == segments.length - 1);
            if (!fileNode) {
                Node node = nodes.get(path);
                if (node == null) {
                    GitModelTree tree = treeFactory.createTreeModel(parent, path, change.getKind());
                    node = new Node(tree);
                    nodes.put(path, node);
                    children.add(tree);
                }
                parent = node.tree;
                children = node.children;
            } else {
                GitModelBlob file = fileFactory.createFileModel(parent, repo, change, path);
                children.add(file);
            }
        }
    }

    for (Node object : nodes.values()) {
        GitModelTree tree = object.tree;
        tree.setChildren(object.children);
    }

    return rootChildren.toArray(new GitModelObject[rootChildren.size()]);
}

From source file:org.eclipse.egit.ui.test.team.actions.ShowBlameActionHandlerTest.java

License:Open Source License

private IJavaProject createJavaProject(final Repository repository, final String projectName) throws Exception {
    final IJavaProject[] jProjectHolder = new IJavaProject[] { null };
    IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
        @Override/*from   www  .  ja  va2s . c  o  m*/
        public void run(IProgressMonitor monitor) throws CoreException {
            IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
            IProject project = root.getProject(projectName);
            if (project.exists()) {
                project.delete(true, null);
                TestUtil.waitForJobs(100, 5000);
            }
            IProjectDescription desc = ResourcesPlugin.getWorkspace().newProjectDescription(projectName);
            desc.setLocation(new Path(new File(repository.getWorkTree(), projectName).getPath()));
            project.create(desc, null);
            project.open(null);
            TestUtil.waitForJobs(50, 5000);
            // Create a "bin" folder
            IFolder bin = project.getFolder(BIN_FOLDER_NAME);
            if (!bin.exists()) {
                bin.create(IResource.FORCE | IResource.DERIVED, true, null);
            }
            IPath outputLocation = bin.getFullPath();
            // Create a "src" folder
            IFolder src = project.getFolder(SRC_FOLDER_NAME);
            if (!src.exists()) {
                src.create(IResource.FORCE, true, null);
            }
            addNatureToProject(project, JavaCore.NATURE_ID);
            // Set up the IJavaProject
            IJavaProject jProject = JavaCore.create(project);
            IPackageFragmentRoot srcContainer = jProject.getPackageFragmentRoot(src);
            IClasspathEntry srcEntry = JavaCore.newSourceEntry(srcContainer.getPath());
            // Create a JRE classpath entry using the default JRE
            IClasspathEntry jreEntry = JavaRuntime.getDefaultJREContainerEntry();
            jProject.setRawClasspath(new IClasspathEntry[] { srcEntry, jreEntry }, outputLocation, true, null);
            // Create a package with a single test class
            IPackageFragment javaPackage = srcContainer.createPackageFragment(PACKAGE_NAME, true, null);
            javaPackage.createCompilationUnit(JAVA_FILE_NAME,
                    "package " + PACKAGE_NAME + ";\nclass " + JAVA_CLASS_NAME + " {\n\n}", true, null);
            jProjectHolder[0] = jProject;
        }
    };
    ResourcesPlugin.getWorkspace().run(runnable, null);
    return jProjectHolder[0];
}

From source file:org.eclipse.egit.ui.view.repositories.GitRepositoriesViewRepoDeletionTest.java

License:Open Source License

@Test
public void testDeleteSubmoduleRepository() throws Exception {
    deleteAllProjects();//from w w  w  .  j  av  a  2 s. c o  m
    assertProjectExistence(PROJ1, false);
    clearView();
    Activator.getDefault().getRepositoryUtil().addConfiguredRepository(repositoryFile);
    shareProjects(repositoryFile);
    assertProjectExistence(PROJ1, true);
    refreshAndWait();
    assertHasRepo(repositoryFile);

    Repository db = lookupRepository(repositoryFile);
    SubmoduleAddCommand command = new SubmoduleAddCommand(db);
    String path = "sub";
    command.setPath(path);
    String uri = db.getDirectory().toURI().toString();
    command.setURI(uri);
    Repository subRepo = command.call();
    assertNotNull(subRepo);

    refreshAndWait();

    SWTBotTree tree = getOrOpenView().bot().tree();
    tree.getAllItems()[0].expand().expandNode(UIText.RepositoriesViewLabelProvider_SubmodulesNodeText)
            .getItems()[0].select();
    ContextMenuHelper.clickContextMenu(tree,
            myUtil.getPluginLocalizedValue(DELETE_REPOSITORY_CONTEXT_MENU_LABEL));
    SWTBotShell shell = bot.shell(UIText.DeleteRepositoryConfirmDialog_DeleteRepositoryWindowTitle);
    shell.activate();
    String workDir = subRepo.getWorkTree().getPath();
    String checkboxLabel = NLS.bind(UIText.DeleteRepositoryConfirmDialog_DeleteWorkingDirectoryCheckbox,
            workDir);
    shell.bot().checkBox(checkboxLabel).select();
    shell.bot().button(IDialogConstants.OK_LABEL).click();
    TestUtil.joinJobs(JobFamilies.REPOSITORY_DELETE);

    refreshAndWait();
    assertFalse(subRepo.getDirectory().exists());
    assertFalse(subRepo.getWorkTree().exists());
}

From source file:org.eclipse.egit.ui.view.repositories.GitRepositoriesViewTest.java

License:Open Source License

 /**
 * Checks the first level of the working directory
 * /*w  w w.ja va2s  .c  o  m*/
 * @throws Exception
 */
@Test
public void testExpandWorkDir() throws Exception {
   SWTBotTree tree = getOrOpenView().bot().tree();
   Repository myRepository = lookupRepository(repositoryFile);
   List<String> children = Arrays
         .asList(myRepository.getWorkTree().list());
   List<String> treeChildren = myRepoViewUtil.getWorkdirItem(tree,
         repositoryFile).expand().getNodes();
   assertTrue(children.containsAll(treeChildren)
         && treeChildren.containsAll(children));
   myRepoViewUtil.getWorkdirItem(tree, repositoryFile).expand().getNode(
         PROJ1).expand().getNode(FOLDER).expand().getNode(FILE1);
}

From source file:org.eclipse.egit.ui.view.repositories.GitRepositoriesViewTestBase.java

License:Open Source License

protected static File createProjectAndCommitToRepository() throws Exception {

    File gitDir = new File(new File(getTestDirectory(), REPO1), Constants.DOT_GIT);
    gitDir.mkdir();/*w ww. ja  v  a  2 s .co  m*/
    Repository myRepository = lookupRepository(gitDir);
    myRepository.create();

    // TODO Bug: for some reason, this seems to be required
    myRepository.getConfig().setString(ConfigConstants.CONFIG_CORE_SECTION, null,
            ConfigConstants.CONFIG_KEY_REPO_FORMAT_VERSION, "0");

    myRepository.getConfig().save();

    // we need to commit into master first
    IProject firstProject = ResourcesPlugin.getWorkspace().getRoot().getProject(PROJ1);

    if (firstProject.exists())
        firstProject.delete(true, null);
    IProjectDescription desc = ResourcesPlugin.getWorkspace().newProjectDescription(PROJ1);
    desc.setLocation(new Path(new File(myRepository.getWorkTree(), PROJ1).getPath()));
    firstProject.create(desc, null);
    firstProject.open(null);

    IFolder folder = firstProject.getFolder(FOLDER);
    folder.create(false, true, null);
    IFile textFile = folder.getFile(FILE1);
    textFile.create(new ByteArrayInputStream("Hello, world".getBytes(firstProject.getDefaultCharset())), false,
            null);
    IFile textFile2 = folder.getFile(FILE2);
    textFile2.create(new ByteArrayInputStream("Some more content".getBytes(firstProject.getDefaultCharset())),
            false, null);

    new ConnectProviderOperation(firstProject, gitDir).execute(null);

    IProject secondPoject = ResourcesPlugin.getWorkspace().getRoot().getProject(PROJ2);

    if (secondPoject.exists())
        secondPoject.delete(true, null);

    desc = ResourcesPlugin.getWorkspace().newProjectDescription(PROJ2);
    desc.setLocation(new Path(new File(myRepository.getWorkTree(), PROJ2).getPath()));
    secondPoject.create(desc, null);
    secondPoject.open(null);

    IFolder secondfolder = secondPoject.getFolder(FOLDER);
    secondfolder.create(false, true, null);
    IFile secondtextFile = secondfolder.getFile(FILE1);
    secondtextFile.create(new ByteArrayInputStream("Hello, world".getBytes(firstProject.getDefaultCharset())),
            false, null);
    IFile secondtextFile2 = secondfolder.getFile(FILE2);
    secondtextFile2.create(
            new ByteArrayInputStream("Some more content".getBytes(firstProject.getDefaultCharset())), false,
            null);

    new ConnectProviderOperation(secondPoject, gitDir).execute(null);

    IFile[] commitables = new IFile[] { firstProject.getFile(".project"), textFile, textFile2, secondtextFile,
            secondtextFile2 };
    ArrayList<IFile> untracked = new ArrayList<IFile>();
    untracked.addAll(Arrays.asList(commitables));
    // commit to stable
    CommitOperation op = new CommitOperation(commitables, new ArrayList<IFile>(), untracked,
            "Test Author <test.author@test.com>", "Test Committer <test.commiter@test.com>", "Initial commit");
    op.execute(null);

    // now create a stable branch (from master)
    createStableBranch(myRepository);
    // and check in some stuff into master again
    touchAndSubmit(null);
    return gitDir;
}

From source file:org.eclipse.egit.ui.view.synchronize.AbstractSynchronizeViewTest.java

License:Open Source License

protected void createEmptyRepository() throws Exception {
    File gitDir = new File(new File(getTestDirectory(), EMPTY_REPOSITORY), Constants.DOT_GIT);
    Repository myRepository = new FileRepository(gitDir);
    myRepository.create();/*w  ww  .  j  av a2  s. co m*/

    // we need to commit into master first
    IProject firstProject = ResourcesPlugin.getWorkspace().getRoot().getProject(EMPTY_PROJECT);

    if (firstProject.exists())
        firstProject.delete(true, null);
    IProjectDescription desc = ResourcesPlugin.getWorkspace().newProjectDescription(EMPTY_PROJECT);
    desc.setLocation(new Path(new File(myRepository.getWorkTree(), EMPTY_PROJECT).getPath()));
    firstProject.create(desc, null);
    firstProject.open(null);

    IFolder folder = firstProject.getFolder(FOLDER);
    folder.create(false, true, null);
    IFile textFile = folder.getFile(FILE1);
    textFile.create(new ByteArrayInputStream("Hello, world".getBytes(firstProject.getDefaultCharset())), false,
            null);
    IFile textFile2 = folder.getFile(FILE2);
    textFile2.create(new ByteArrayInputStream("Some more content".getBytes(firstProject.getDefaultCharset())),
            false, null);

    new ConnectProviderOperation(firstProject, gitDir).execute(null);
}

From source file:org.eclipse.egit.ui.view.synchronize.SynchronizeViewRemoteAwareChangeSetModelTest.java

License:Open Source License

protected void createMockLogicalRepository() throws Exception {
    File gitDir = new File(new File(getTestDirectory(), MOCK_LOGICAL_PROJECT), Constants.DOT_GIT);
    Repository repo = FileRepositoryBuilder.create(gitDir);
    repo.create();/*from  ww  w. jav  a  2 s  . c  o m*/

    // we need to commit into master first
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(MOCK_LOGICAL_PROJECT);

    if (project.exists()) {
        project.delete(true, null);
        TestUtil.waitForJobs(100, 5000);
    }
    IProjectDescription desc = ResourcesPlugin.getWorkspace().newProjectDescription(MOCK_LOGICAL_PROJECT);
    desc.setLocation(new Path(new File(repo.getWorkTree(), MOCK_LOGICAL_PROJECT).getPath()));
    project.create(desc, null);
    project.open(null);
    assertTrue("Project is not accessible: " + project, project.isAccessible());

    TestUtil.waitForJobs(50, 5000);
    try {
        new ConnectProviderOperation(project, gitDir).execute(null);
    } catch (Exception e) {
        Activator.logError("Failed to connect project to repository", e);
    }
    assertConnected(project);

    mockLogicalFile = project.getFile("index.mocklogical");
    mockLogicalFile.create(
            new ByteArrayInputStream("file1.txt\nfile2.txt".getBytes(project.getDefaultCharset())), false,
            null);
    IFile file1 = project.getFile("file1.txt");
    file1.create(new ByteArrayInputStream("Content 1".getBytes(project.getDefaultCharset())), false, null);
    IFile file2 = project.getFile("file2.txt");
    file2.create(new ByteArrayInputStream("Content 2".getBytes(project.getDefaultCharset())), false, null);

    IFile[] commitables = new IFile[] { mockLogicalFile, file1, file2 };
    List<IFile> untracked = new ArrayList<>();
    untracked.addAll(Arrays.asList(commitables));
    CommitOperation op = new CommitOperation(commitables, untracked, TestUtil.TESTAUTHOR,
            TestUtil.TESTCOMMITTER, "Initial commit");
    op.execute(null);
    RevCommit firstCommit = op.getCommit();

    CreateLocalBranchOperation createBranchOp = new CreateLocalBranchOperation(repo, "refs/heads/stable",
            firstCommit);
    createBranchOp.execute(null);

    // Delete file2.txt from logical model and add file3
    mockLogicalFile = touch(MOCK_LOGICAL_PROJECT, "index.mocklogical", "file1.txt\nfile3.txt");
    file2.delete(true, null);
    touch(MOCK_LOGICAL_PROJECT, "file1.txt", "Content 1 modified");
    IFile file3 = project.getFile("file3.txt");
    file3.create(new ByteArrayInputStream("Content 3".getBytes(project.getDefaultCharset())), false, null);
    commitables = new IFile[] { mockLogicalFile, file1, file2, file3 };
    untracked = new ArrayList<>();
    untracked.add(file3);
    op = new CommitOperation(commitables, untracked, TestUtil.TESTAUTHOR, TestUtil.TESTCOMMITTER,
            "Second commit");
    op.execute(null);
}

From source file:org.eclipse.emf.compare.egit.internal.merge.TreeWalkResourceVariantTreeProvider.java

License:Open Source License

/**
 * Returns a resource handle for this path in the workspace. Note that neither the resource nor the result
 * need exist in the workspace : this may return inexistent or otherwise non-accessible IResources.
 *
 * @param repository/* w  w w. j  a  va 2s .co  m*/
 *            The repository within which is tracked this file.
 * @param repoRelativePath
 *            Repository-relative path of the file we need an handle for.
 * @param isFolder
 *            <code>true</code> if the file being sought is a folder.
 * @return The resource handle for the given path in the workspace.
 */
public IResource getResourceHandleForLocation(Repository repository, String repoRelativePath,
        boolean isFolder) {
    IResource resource = null;

    final String workDir = repository.getWorkTree().getAbsolutePath();
    final IPath path = new Path(workDir + '/' + repoRelativePath);
    final File file = path.toFile();
    if (file.exists()) {
        if (isFolder) {
            resource = ResourceUtil.getContainerForLocation(path, false);
        } else {
            resource = ResourceUtil.getFileForLocation(path, false);
        }
    }

    if (repoRelativePath.endsWith(".project")) { //$NON-NLS-1$
        IPath parentPath = path.removeLastSegments(1);
        IProject p = ResourcesPlugin.getWorkspace().getRoot().getProject(parentPath.lastSegment().toString());
        if (map.get(parentPath) == null) {
            map.put(parentPath, p);
        }
    }

    if (resource == null) {
        // It may be a file that only exists on remote side. We need to
        // create an IResource for it.
        // If it is a project file, then create an IProject.
        final List<IPath> list = new ArrayList<IPath>(map.keySet());
        for (int i = list.size() - 1; i >= 0; i--) {
            IPath projectPath = list.get(i);
            if (projectPath.isPrefixOf(path) && !projectPath.equals(path)) {
                final IPath projectRelativePath = path.makeRelativeTo(projectPath);
                if (isFolder) {
                    resource = map.get(projectPath).getFolder(projectRelativePath);
                } else {
                    resource = map.get(projectPath).getFile(projectRelativePath);
                }
                break;
            }
        }
    }

    if (resource == null) {
        // This is a file that no longer exists locally, yet we still need
        // to determine an IResource for it.
        // Try and find a Project in the workspace which path is a prefix of
        // the file we seek and which is mapped to the current repository.
        final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        for (IProject project : root.getProjects()) {
            if (RepositoryProvider.getProvider(project, GitProvider.ID) != null) {
                final IPath projectLocation = project.getLocation();
                if (projectLocation != null && projectLocation.isPrefixOf(path)) {
                    final IPath projectRelativePath = path.makeRelativeTo(projectLocation);
                    if (isFolder) {
                        resource = project.getFolder(projectRelativePath);
                    } else {
                        resource = project.getFile(projectRelativePath);
                    }
                    break;
                }
            }
        }
    }

    return resource;
}

From source file:org.eclipse.emf.compare.egit.internal.ModelEGitResourceUtil.java

License:Open Source License

public static IResource getResourceHandleForLocation(Repository repository, String repoRelativePath,
        boolean isFolder) {
    final String workDir = repository.getWorkTree().getAbsolutePath();
    final IPath path = new Path(workDir + '/' + repoRelativePath);
    final File file = path.toFile();
    if (file.exists()) {
        if (isFolder) {
            return ResourceUtil.getContainerForLocation(path, false);
        }/*ww  w  .  java 2  s . c  om*/
        return ResourceUtil.getFileForLocation(path, false);
    }

    // This is a file that no longer exists locally, yet we still need to
    // determine an IResource for it.
    // Try and find a Project in the workspace which path is a prefix of the
    // file we seek and which is mapped to the current repository.
    final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    for (IProject project : root.getProjects()) {
        if (RepositoryProvider.getProvider(project, GitProvider.ID) != null) {
            final IPath projectLocation = project.getLocation();
            if (projectLocation != null && projectLocation.isPrefixOf(path)) {
                final IPath projectRelativePath = path.makeRelativeTo(projectLocation);
                if (isFolder) {
                    return project.getFolder(projectRelativePath);
                } else {
                    return project.getFile(projectRelativePath);
                }
            }
        }
    }
    return null;
}