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

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

Introduction

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

Prototype

@NonNull
public DirCache readDirCache() throws NoWorkTreeException, CorruptObjectException, IOException 

Source Link

Document

Create a new in-core index representation and read an index from disk.

Usage

From source file:com.bacoder.scmtools.git.internal.CloneAndProcessCommand.java

License:Apache License

@Override
protected void cloneSubmodules(Repository repository) throws IOException, GitAPIException {
    SubmoduleWalk generator;/*w  ww  .j a v  a 2s  .c o  m*/
    if (isInMemory()) {
        generator = new InMemorySubmoduleWalk(repository, submodulesConfig);
        try {
            DirCache index = repository.readDirCache();
            generator.setTree(new DirCacheIterator(index));
        } catch (IOException e) {
            generator.release();
            throw e;
        }
    } else {
        generator = SubmoduleWalk.forIndex(repository);
    }

    try {
        while (generator.next()) {
            if (generator.getConfigUrl() != null) {
                continue;
            }

            String path = generator.getPath();
            String url = generator.getRemoteUrl();

            CloneAndProcessCommand command = new CloneAndProcessCommand(path, config).setProcessor(processor);
            command.setURI(url).setCloneSubmodules(true);
            command.call();
        }
    } catch (ConfigInvalidException e) {
        throw new IOException("Config invalid", e);
    }
}

From source file:com.beck.ep.team.git.GitListBuilder.java

License:BSD License

private int addTree(int mode, Shell shell, Repository rep, RevWalk rw, TreeWalk tw) throws Exception {
    int index = -1;
    switch (mode) {
    case GitModeMenuMgr.MODE_STAGING:
        tw.addTree(new DirCacheIterator(rep.readDirCache()));
        break;//from   w w  w.  j a  v  a 2  s . c o m
    case GitModeMenuMgr.MODE_OTHERS://choose a GIT ref
        CompareTargetSelectionDialog dialog = new CompareTargetSelectionDialog(shell, rep, null);
        if (dialog.open() != CompareTargetSelectionDialog.OK) {
            return -2;
        }
        ObjectId obId = rep.getRef(dialog.getRefName()).getObjectId();//"master"
        tw.addTree(rw.parseCommit(obId).getTree());
        break;
    case GitModeMenuMgr.MODE_BRANCH_HEAD:
        Ref head = rep.getRef(Constants.HEAD);
        RevCommit rc = rw.parseCommit(head.getObjectId());
        tw.addTree(rc.getTree());
        break;
    default://compare to working area
        index = tw.addTree(new FileTreeIterator(rep));
        break;
    }
    return index;
}

From source file:org.eclipse.egit.core.GitMoveDeleteHookTest.java

License:Open Source License

/**
 * Rename and move a project in the workspace containing a Git repository.
 * <p>//from  w  w  w . j  a  v a2s  .  c  om
 * The repository will be moved with the project.
 * Note that there is no way to rename a project in the workspace without
 * moving it. See https://bugs.eclipse.org/358828 for a discussion.
 *
 * @throws Exception
 */
@Test
public void testMoveAndRenameProjectContainingGitRepo() throws Exception {
    ResourcesPlugin.getWorkspace().getRoot().getProject("Project-1").delete(true, null);
    ResourcesPlugin.getWorkspace().getRoot().getProject("P2").delete(true, null);

    TestProject project = initRepoInsideProjectInsideWorkspace();
    testUtils.addFileToProject(project.getProject(), "file.txt", "some text");
    AddToIndexOperation addToIndexOperation = new AddToIndexOperation(
            new IResource[] { project.getProject().getFile("file.txt") });
    addToIndexOperation.execute(null);
    IProjectDescription description = project.getProject().getDescription();
    description.setName("P2");
    registerWorkspaceRelativeTestDir("P2");
    project.getProject().move(description, IResource.FORCE | IResource.SHALLOW, null);
    IProject project2 = ResourcesPlugin.getWorkspace().getRoot().getProject("P2");
    assertNotNull(RepositoryMapping.getMapping(project2.getProject()));
    Repository movedRepo = RepositoryMapping.getMapping(project2).getRepository();
    assertEquals("P2", movedRepo.getDirectory().getParentFile().getName());
    DirCache dc = movedRepo.readDirCache();
    assertEquals(1, dc.getEntryCount());
    assertEquals("file.txt", dc.getEntry(0).getPathString());

    assertFalse(ResourcesPlugin.getWorkspace().getRoot().getProject("Project-1").exists());
}

From source file:org.eclipse.egit.core.GitMoveDeleteHookTest.java

License:Open Source License

/**
 * Rename a project outside the workspace containing a Git repository.
 * <p>//from  w w w  .  ja  v a 2 s.  c o m
 * Note the similarity of the code with {@link #testMoveAndRenameProjectContainingGitRepo()}
 *
 * @throws Exception
 */
@Test
public void testRenameProjectOutsideWorkspaceContainingGitRepo() throws Exception {
    ResourcesPlugin.getWorkspace().getRoot().getProject("Project-1").delete(true, null);
    ResourcesPlugin.getWorkspace().getRoot().getProject("P2").delete(true, null);
    TestProject project = initRepoInsideProjectOutsideWorkspace();
    testUtils.addFileToProject(project.getProject(), "file.txt", "some text");
    AddToIndexOperation addToIndexOperation = new AddToIndexOperation(
            new IResource[] { project.getProject().getFile("file.txt") });
    addToIndexOperation.execute(null);
    IProjectDescription description = project.getProject().getDescription();
    description.setName("P2");
    project.getProject().move(description, IResource.FORCE | IResource.SHALLOW, null);
    IProject project2 = ResourcesPlugin.getWorkspace().getRoot().getProject("P2");
    assertNotNull(RepositoryMapping.getMapping(project2.getProject()));
    Repository movedRepo = RepositoryMapping.getMapping(project2).getRepository();
    assertEquals("Project-1", movedRepo.getDirectory().getParentFile().getName());
    DirCache dc = movedRepo.readDirCache();
    assertEquals(1, dc.getEntryCount());
    assertEquals("file.txt", dc.getEntry(0).getPathString());

    assertFalse(ResourcesPlugin.getWorkspace().getRoot().getProject("Project-1").exists());
}

From source file:org.eclipse.egit.core.GitMoveDeleteHookTest.java

License:Open Source License

/**
 * Move a project outside the workspace containing a Git repository, but do not rename it.
 * <p>/* w ww .ja v  a  2s  .  com*/
 * Note the similarity of the code with {@link #testMoveAndRenameProjectContainingGitRepo()}
 *
 * @throws Exception
 */
@Test
public void testMoveButDoNotRenameProjectOutsideWorkspaceContainingGitRepo() throws Exception {
    ResourcesPlugin.getWorkspace().getRoot().getProject("Project-1").delete(true, null);
    ResourcesPlugin.getWorkspace().getRoot().getProject("P2").delete(true, null);
    TestProject project = initRepoInsideProjectOutsideWorkspace();
    testUtils.addFileToProject(project.getProject(), "file.txt", "some text");
    AddToIndexOperation addToIndexOperation = new AddToIndexOperation(
            new IResource[] { project.getProject().getFile("file.txt") });
    addToIndexOperation.execute(null);
    IProjectDescription description = project.getProject().getDescription();
    description.setLocationURI(
            URIUtil.toURI(new Path(new File(project.getWorkspaceSupplement(), "P2").getAbsolutePath())));
    project.getProject().move(description, IResource.FORCE | IResource.SHALLOW, null);
    IProject project2 = ResourcesPlugin.getWorkspace().getRoot().getProject("Project-1"); // same name
    assertNotNull(RepositoryMapping.getMapping(project2.getProject()));
    Repository movedRepo = RepositoryMapping.getMapping(project2).getRepository();
    assertEquals("P2", movedRepo.getDirectory().getParentFile().getName());
    DirCache dc = movedRepo.readDirCache();
    assertEquals(1, dc.getEntryCount());
    assertEquals("file.txt", dc.getEntry(0).getPathString());

    assertFalse(ResourcesPlugin.getWorkspace().getRoot().getProject("P2").exists());
}

From source file:org.eclipse.egit.core.GitMoveDeleteHookTest.java

License:Open Source License

@Test
public void testMoveFileWithConflictsShouldBeCanceled() throws Exception {
    TestProject project = initRepoInsideProjectInsideWorkspace();
    String filePath = "file.txt";
    IFile file = testUtils.addFileToProject(project.getProject(), filePath, "some text");

    Repository repo = testRepository.getRepository();
    DirCache index = repo.lockDirCache();
    DirCacheBuilder builder = index.builder();
    addUnmergedEntry(filePath, builder);
    builder.commit();//from w w  w  .j a v  a2s  .  c o m

    try {
        file.move(new Path("destination.txt"), false, null);
        fail("Expected move of file with conflicts to fail.");
    } catch (CoreException e) {
        IStatus status = e.getStatus();
        assertNotNull(status);
        assertEquals(IStatus.WARNING, status.getSeverity());
    }

    assertTrue("File should still exist at old location", file.exists());
    DirCache indexAfter = repo.readDirCache();
    DirCacheEntry entry = indexAfter.getEntry(filePath);
    assertEquals("Expected entry to still be in non-zero (conflict) stage", DirCacheEntry.STAGE_1,
            entry.getStage());
}

From source file:org.eclipse.egit.core.GitMoveDeleteHookTest.java

License:Open Source License

@Test
public void testMoveFolderWithFileWithConflictsShouldBeCanceled() throws Exception {
    TestProject project = initRepoInsideProjectInsideWorkspace();
    String filePath = "folder/file.txt";
    IFile file = testUtils.addFileToProject(project.getProject(), filePath, "some text");

    Repository repo = testRepository.getRepository();
    DirCache index = repo.lockDirCache();
    DirCacheBuilder builder = index.builder();
    addUnmergedEntry(filePath, builder);
    builder.commit();//  w  w  w.ja va2  s.co  m

    try {
        project.getProject().getFolder("folder").move(project.getProject().getFolder("newfolder").getFullPath(),
                false, null);
        fail("Expected move of folder with file with conflicts to fail.");
    } catch (CoreException e) {
        IStatus status = e.getStatus();
        assertNotNull(status);
        assertEquals(IStatus.WARNING, status.getSeverity());
    }

    assertTrue("File should still exist at old location", file.exists());
    DirCache indexAfter = repo.readDirCache();
    DirCacheEntry entry = indexAfter.getEntry(filePath);
    assertEquals("Expected entry to still be in non-zero (conflict) stage", DirCacheEntry.STAGE_1,
            entry.getStage());
}

From source file:org.eclipse.egit.core.internal.indexdiff.IndexDiffCacheEntry.java

License:Open Source License

/**
 * @param repository//from  w w  w  .j a v a 2 s .  c o  m
 */
public IndexDiffCacheEntry(Repository repository) {
    this.repository = repository;
    indexChangedListenerHandle = repository.getListenerList()
            .addIndexChangedListener(new IndexChangedListener() {
                public void onIndexChanged(IndexChangedEvent event) {
                    refreshIndexDelta();
                }
            });
    refsChangedListenerHandle = repository.getListenerList().addRefsChangedListener(new RefsChangedListener() {
        public void onRefsChanged(RefsChangedEvent event) {
            scheduleReloadJob("RefsChanged"); //$NON-NLS-1$
        }
    });
    scheduleReloadJob("IndexDiffCacheEntry construction"); //$NON-NLS-1$
    createResourceChangeListener();
    if (!repository.isBare()) {
        try {
            lastIndex = repository.readDirCache();
        } catch (IOException ex) {
            Activator.error(
                    MessageFormat.format(CoreText.IndexDiffCacheEntry_errorCalculatingIndexDelta, repository),
                    ex);
        }
    }
}

From source file:org.eclipse.egit.core.internal.merge.DirCacheResourceVariantTreeProvider.java

License:Open Source License

/**
 * Constructs the resource variant trees by iterating over the given
 * repository's DirCache entries.//from w  w w  .  j av a 2s . c  om
 *
 * @param repository
 *            The repository which DirCache info we need to cache as
 *            IResourceVariantTrees.
 * @throws IOException
 *             if we somehow cannot read the DirCache.
 */
public DirCacheResourceVariantTreeProvider(Repository repository) throws IOException {
    final DirCache cache = repository.readDirCache();
    final GitResourceVariantCache baseCache = new GitResourceVariantCache();
    final GitResourceVariantCache sourceCache = new GitResourceVariantCache();
    final GitResourceVariantCache remoteCache = new GitResourceVariantCache();

    for (int i = 0; i < cache.getEntryCount(); i++) {
        final DirCacheEntry entry = cache.getEntry(i);
        final IPath path = new Path(entry.getPathString());
        final IResource resource = ResourceUtil.getResourceHandleForLocation(path);
        // Resource variants only make sense for IResources. Do not consider
        // files outside of the workspace or otherwise non accessible.
        if (resource == null || resource.getProject() == null || !resource.getProject().isAccessible()) {
            continue;
        }
        switch (entry.getStage()) {
        case DirCacheEntry.STAGE_0:
            // Skipped on purpose (no conflict)
            break;
        case DirCacheEntry.STAGE_1:
            baseCache.setVariant(resource, IndexResourceVariant.create(repository, entry));
            break;
        case DirCacheEntry.STAGE_2:
            sourceCache.setVariant(resource, IndexResourceVariant.create(repository, entry));
            break;
        case DirCacheEntry.STAGE_3:
            remoteCache.setVariant(resource, IndexResourceVariant.create(repository, entry));
            break;
        default:
            throw new IllegalStateException("Invalid stage: " + entry.getStage()); //$NON-NLS-1$
        }
    }

    baseTree = new GitCachedResourceVariantTree(baseCache);
    sourceTree = new GitCachedResourceVariantTree(sourceCache);
    remoteTree = new GitCachedResourceVariantTree(remoteCache);

    roots = new LinkedHashSet<IResource>();
    roots.addAll(baseCache.getRoots());
    roots.addAll(sourceCache.getRoots());
    roots.addAll(remoteCache.getRoots());

    knownResources = new LinkedHashSet<IResource>();
    knownResources.addAll(baseCache.getKnownResources());
    knownResources.addAll(sourceCache.getKnownResources());
    knownResources.addAll(remoteCache.getKnownResources());
}

From source file:org.eclipse.egit.core.synchronize.StagedChangeCache.java

License:Open Source License

/**
 * @param repo/*from   w w  w.  ja v a  2s.c o  m*/
 *            repository which should be scanned
 * @return list of changes in git staging area
 */
public static Map<String, Change> build(Repository repo) {
    TreeWalk tw = new TreeWalk(repo);
    try {
        tw.addTree(new DirCacheIterator(repo.readDirCache()));
        ObjectId headId = repo.resolve(HEAD);
        RevCommit headCommit;
        if (headId != null)
            headCommit = new RevWalk(repo).parseCommit(headId);
        else
            headCommit = null;

        AbbreviatedObjectId commitId;
        if (headCommit != null) {
            tw.addTree(headCommit.getTree());
            commitId = AbbreviatedObjectId.fromObjectId(headCommit);
        } else {
            tw.addTree(new EmptyTreeIterator());
            commitId = AbbreviatedObjectId.fromObjectId(zeroId());
        }

        tw.setRecursive(true);
        headCommit = null;

        MutableObjectId idBuf = new MutableObjectId();
        Map<String, Change> result = new HashMap<String, Change>();
        while (tw.next()) {
            if (!shouldIncludeEntry(tw))
                continue;

            Change change = new Change();
            change.name = tw.getNameString();
            change.remoteCommitId = commitId;

            tw.getObjectId(idBuf, 0);
            change.objectId = AbbreviatedObjectId.fromObjectId(idBuf);
            tw.getObjectId(idBuf, 1);
            change.remoteObjectId = AbbreviatedObjectId.fromObjectId(idBuf);

            calculateAndSetChangeKind(RIGHT, change);

            result.put(tw.getPathString(), change);
        }
        tw.release();

        return result;
    } catch (IOException e) {
        Activator.error(e.getMessage(), e);
        return new HashMap<String, Change>(0);
    }
}