Example usage for org.eclipse.jgit.dircache DirCacheEntry getStage

List of usage examples for org.eclipse.jgit.dircache DirCacheEntry getStage

Introduction

In this page you can find the example usage for org.eclipse.jgit.dircache DirCacheEntry getStage.

Prototype

public int getStage() 

Source Link

Document

Get the stage of this entry.

Usage

From source file:com.github.kaitoy.goslings.server.dao.jgit.RepositoryDaoImpl.java

License:Open Source License

@Override
public Index getIndex(String token) {
    try {/*from ww w  .  j  a v a2  s.c o m*/
        DirCache index = resolver.getRepository(token).readDirCache();
        int numEntries = index.getEntryCount();
        List<IndexEntry> entries = new ArrayList<>(numEntries);
        for (int i = 0; i < numEntries; i++) {
            DirCacheEntry dce = index.getEntry(i);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            dce.getFileMode().copyTo(baos);
            entries.add(new IndexEntry(dce.getObjectId().getName(), dce.getPathString(), baos.toString(),
                    dce.getStage()));
        }
        return new Index(entries.toArray(new IndexEntry[numEntries]));
    } catch (NoWorkTreeException e) {
        String message = new StringBuilder().append("The repository ").append(token)
                .append(" is bare and so doesn't have index.").toString();
        LOG.error(message, e);
        throw new DaoException(message, e);
    } catch (CorruptObjectException e) {
        String message = new StringBuilder().append("Filed to get index of the repository ").append(token)
                .append(" due to an internal error.").toString();
        LOG.error(message, e);
        throw new DaoException(message, e);
    } catch (IOException e) {
        String message = new StringBuilder().append("Filed to get index of the repository ").append(token)
                .append(" due to an I/O error.").toString();
        LOG.error(message, e);
        throw new DaoException(message, e);
    }

}

From source file:com.itemis.maven.plugins.unleash.scm.providers.merge.UnleashGitMerger.java

License:Eclipse Distribution License

/**
 * adds a entry to the index builder which is a copy of the specified
 * DirCacheEntry//w  ww.  ja  va  2 s.  c  o m
 *
 * @param e
 *          the entry which should be copied
 *
 * @return the entry which was added to the index
 */
private DirCacheEntry keep(DirCacheEntry e) {
    DirCacheEntry newEntry = new DirCacheEntry(e.getPathString(), e.getStage());
    newEntry.setFileMode(e.getFileMode());
    newEntry.setObjectId(e.getObjectId());
    newEntry.setLastModified(e.getLastModified());
    newEntry.setLength(e.getLength());
    this.builder.add(newEntry);
    return newEntry;
}

From source file:com.mangosolutions.rcloud.rawgist.repository.git.BareAddCommand.java

@Override
public DirCache call() throws GitAPIException {
    if (filepatterns.isEmpty()) {
        throw new NoFilepatternException(JGitText.get().atLeastOnePatternIsRequired);
    }/*from  w ww .j  av a  2s  .  c o  m*/
    checkCallable();
    boolean addAll = filepatterns.contains("."); //$NON-NLS-1$
    try (ObjectInserter inserter = repo.newObjectInserter();
            NameConflictTreeWalk tw = new NameConflictTreeWalk(repo)) {
        tw.setOperationType(OperationType.CHECKIN_OP);
        dirCache.lock();
        DirCacheBuilder builder = dirCache.builder();
        tw.addTree(new DirCacheBuildIterator(builder));
        if (workingTreeIterator == null)
            workingTreeIterator = new FileTreeIterator(repo);
        workingTreeIterator.setDirCacheIterator(tw, 0);
        tw.addTree(workingTreeIterator);
        if (!addAll) {
            tw.setFilter(PathFilterGroup.createFromStrings(filepatterns));
        }

        byte[] lastAdded = null;

        while (tw.next()) {
            DirCacheIterator c = tw.getTree(0, DirCacheIterator.class);
            WorkingTreeIterator f = tw.getTree(1, WorkingTreeIterator.class);
            if (c == null && f != null && f.isEntryIgnored()) {
                // file is not in index but is ignored, do nothing
                continue;
            } else if (c == null && update) {
                // Only update of existing entries was requested.
                continue;
            }

            DirCacheEntry entry = c != null ? c.getDirCacheEntry() : null;
            if (entry != null && entry.getStage() > 0 && lastAdded != null
                    && lastAdded.length == tw.getPathLength()
                    && tw.isPathPrefix(lastAdded, lastAdded.length) == 0) {
                // In case of an existing merge conflict the
                // DirCacheBuildIterator iterates over all stages of
                // this path, we however want to add only one
                // new DirCacheEntry per path.
                continue;
            }

            if (tw.isSubtree() && !tw.isDirectoryFileConflict()) {
                tw.enterSubtree();
                continue;
            }

            if (f == null) { // working tree file does not exist
                if (entry != null && (!update || GITLINK == entry.getFileMode())) {
                    builder.add(entry);
                }
                continue;
            }

            if (entry != null && entry.isAssumeValid()) {
                // Index entry is marked assume valid. Even though
                // the user specified the file to be added JGit does
                // not consider the file for addition.
                builder.add(entry);
                continue;
            }

            if ((f.getEntryRawMode() == TYPE_TREE && f.getIndexFileMode(c) != FileMode.GITLINK)
                    || (f.getEntryRawMode() == TYPE_GITLINK && f.getIndexFileMode(c) == FileMode.TREE)) {
                // Index entry exists and is symlink, gitlink or file,
                // otherwise the tree would have been entered above.
                // Replace the index entry by diving into tree of files.
                tw.enterSubtree();
                continue;
            }

            byte[] path = tw.getRawPath();
            if (entry == null || entry.getStage() > 0) {
                entry = new DirCacheEntry(path);
            }
            FileMode mode = f.getIndexFileMode(c);
            entry.setFileMode(mode);

            if (GITLINK != mode) {
                entry.setLength(f.getEntryLength());
                entry.setLastModified(f.getEntryLastModified());
                long len = f.getEntryContentLength();
                try (InputStream in = f.openEntryStream()) {
                    ObjectId id = inserter.insert(OBJ_BLOB, len, in);
                    entry.setObjectId(id);
                }
            } else {
                entry.setLength(0);
                entry.setLastModified(0);
                entry.setObjectId(f.getEntryObjectId());
            }
            builder.add(entry);
            lastAdded = path;
        }
        inserter.flush();
        builder.commit();
        setCallable(false);
    } catch (IOException e) {
        Throwable cause = e.getCause();
        if (cause != null && cause instanceof FilterFailedException)
            throw (FilterFailedException) cause;
        throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfAddCommand, e);
    } finally {
        if (dirCache != null) {
            dirCache.unlock();
        }
    }
    return dirCache;

}

From source file:edu.nju.cs.inform.jgit.unfinished.ListIndex.java

License:Apache License

public static void main(String[] args) throws IOException {
    try (Repository repository = CookbookHelper.openJGitCookbookRepository()) {
        // DirCache contains all files of the repository
        DirCache index = DirCache.read(repository);
        System.out.println("DirCache has " + index.getEntryCount() + " items");
        for (int i = 0; i < index.getEntryCount(); i++) {
            // the number after the AnyObjectId is the "stage", see the constants in DirCacheEntry
            System.out.println("Item " + i + ": " + index.getEntry(i));
        }//from w w w . j a  v a 2 s  .c o  m

        //
        System.out.println("Now printing staged items...");
        for (int i = 0; i < index.getEntryCount(); i++) {
            DirCacheEntry entry = index.getEntry(i);
            if (entry.getStage() != DirCacheEntry.STAGE_0) {
                System.out.println("Item " + i + ": " + entry);
            }
        }
    }
}

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();// w w  w . ja  v  a  2 s .  co 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();//from  www  .j  a v  a  2s.c  o 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.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  a  v  a 2s  .co  m*/
 *
 * @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.internal.merge.ResourceVariantTest.java

License:Open Source License

@Test
public void testIndexVariantsConflict() throws Exception {
    File file1 = testRepo.createFile(iProject, "file1");
    IFile iFile1 = testRepo.getIFile(iProject, file1);

    setupConflictingBranches();//  w ww .  j  ava2s . c o  m
    // end setup

    // create a conflict to force multiple stages
    new MergeOperation(repo, BRANCH).execute(null);

    DirCache cache = repo.readDirCache();
    // 3 stages for file 1, 2 stages for file 2
    assertEquals(5, cache.getEntryCount());
    for (int i = 0; i < cache.getEntryCount(); i++) {
        final DirCacheEntry entry = cache.getEntry(i);

        AbstractGitResourceVariant variant = IndexResourceVariant.create(repo, entry);
        assertEquals(entry.getObjectId().getName(), variant.getContentIdentifier());
        assertEquals(entry.getObjectId(), variant.getObjectId());
        assertEquals(entry.getRawMode(), variant.getRawMode());
        if (iFile1.getName().equals(variant.getName())) {
            switch (entry.getStage()) {
            case DirCacheEntry.STAGE_1:
                assertContentEquals(variant, INITIAL_CONTENT_1);
                break;
            case DirCacheEntry.STAGE_2:
                assertContentEquals(variant, INITIAL_CONTENT_1 + MASTER_CHANGE);
                break;
            case DirCacheEntry.STAGE_3:
                assertContentEquals(variant, BRANCH_CHANGE + INITIAL_CONTENT_1);
                break;
            case DirCacheEntry.STAGE_0:
            default:
                fail("Unexpected entry stage " + entry.getStage() + " in the index for file "
                        + entry.getPathString());
                break;
            }
        } else {
            switch (entry.getStage()) {
            case DirCacheEntry.STAGE_2:
                assertContentEquals(variant, INITIAL_CONTENT_2 + MASTER_CHANGE);
                break;
            case DirCacheEntry.STAGE_3:
                assertContentEquals(variant, BRANCH_CHANGE + INITIAL_CONTENT_2);
                break;
            case DirCacheEntry.STAGE_0:
            case DirCacheEntry.STAGE_1:
            default:
                fail("Unexpected entry stage " + entry.getStage() + " in the index for file "
                        + entry.getPathString());
                break;
            }
        }
    }
}

From source file:org.eclipse.egit.ui.internal.decorators.DecoratableResourceAdapter.java

License:Open Source License

private void extractResourceProperties(TreeWalk treeWalk) throws IOException {
    final ContainerTreeIterator workspaceIterator = treeWalk.getTree(T_WORKSPACE, ContainerTreeIterator.class);
    final ResourceEntry resourceEntry = workspaceIterator != null ? workspaceIterator.getResourceEntry() : null;

    if (resourceEntry == null)
        return;//from   w w w.j  av  a  2s  .c  o  m

    if (workspaceIterator != null && workspaceIterator.isEntryIgnored()) {
        ignored = true;
        return;
    }

    final int mHead = treeWalk.getRawMode(T_HEAD);
    final int mIndex = treeWalk.getRawMode(T_INDEX);

    if (mHead == FileMode.MISSING.getBits() && mIndex == FileMode.MISSING.getBits())
        return;

    tracked = true;

    if (mHead == FileMode.MISSING.getBits()) {
        staged = Staged.ADDED;
    } else if (mIndex == FileMode.MISSING.getBits()) {
        staged = Staged.REMOVED;
    } else if (mHead != mIndex || (mIndex != FileMode.TREE.getBits() && !treeWalk.idEqual(T_HEAD, T_INDEX))) {
        staged = Staged.MODIFIED;
    } else {
        staged = Staged.NOT_STAGED;
    }

    final DirCacheIterator indexIterator = treeWalk.getTree(T_INDEX, DirCacheIterator.class);
    final DirCacheEntry indexEntry = indexIterator != null ? indexIterator.getDirCacheEntry() : null;

    if (indexEntry == null)
        return;

    if (indexEntry.getStage() > 0)
        conflicts = true;

    if (indexEntry.isAssumeValid()) {
        dirty = false;
        assumeValid = true;
    } else {
        if (workspaceIterator != null && workspaceIterator.isModified(indexEntry, true))
            dirty = true;
    }
}

From source file:org.eclipse.egit.ui.internal.merge.GitMergeEditorInput.java

License:Open Source License

private void fileToDiffNode(final IFile file, String gitPath, RepositoryMapping map, IDiffContainer root,
        RevCommit rightCommit, RevCommit headCommit, RevCommit ancestorCommit, RevWalk rw,
        IProgressMonitor monitor) throws IOException, InterruptedException {

    if (monitor.isCanceled())
        throw new InterruptedException();

    TreeWalk tw = new TreeWalk(map.getRepository());

    List<String> paths = new ArrayList<String>();
    paths.add(map.getRepoRelativePath(file));
    tw.setFilter(PathFilterGroup.createFromStrings(paths));

    int dcindex = tw.addTree(new DirCacheIterator(map.getRepository().readDirCache()));
    int ftindex = tw.addTree(new FileTreeIterator(map.getRepository()));
    int rtindex = tw.addTree(rw.parseTree(map.getRepository().resolve(Constants.HEAD)));

    tw.setRecursive(tw.getFilter().shouldBeRecursive());
    tw.next();/*from   www  .j  av  a  2 s.co m*/

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

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

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

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

    FileTreeIterator fit = tw.getTree(ftindex, FileTreeIterator.class);
    if (fit != null && fit.isEntryIgnored())
        return;
    // compare local file against HEAD to see if it was modified
    boolean modified = fit != null && rt != null && !fit.getEntryObjectId().equals(rt.getEntryObjectId());

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

    ITypedElement right;
    if (conflicting)
        right = CompareUtils.getFileRevisionTypedElement(gitPath, rightCommit, map.getRepository());
    else
        right = CompareUtils.getFileRevisionTypedElement(gitPath, headCommit, map.getRepository());

    // can this really happen?
    if (right instanceof EmptyTypedElement)
        return;

    IFileRevision rev;
    // if the file is not conflicting (as it was auto-merged)
    // we will show the auto-merged (local) version
    if (!conflicting || useWorkspace)
        rev = new LocalFileRevision(file);
    else
        rev = GitFileRevision.inCommit(map.getRepository(), headCommit, gitPath, null);

    EditableRevision leftEditable = new EditableRevision(rev) {
        @Override
        public void setContent(final byte[] newContent) {
            try {
                run(false, false, new IRunnableWithProgress() {
                    public void run(IProgressMonitor myMonitor)
                            throws InvocationTargetException, InterruptedException {
                        try {
                            file.setContents(new ByteArrayInputStream(newContent), false, true, myMonitor);
                        } catch (CoreException e) {
                            throw new InvocationTargetException(e);
                        }
                    }
                });
            } catch (InvocationTargetException e) {
                Activator.handleError(e.getTargetException().getMessage(), e.getTargetException(), true);
            } catch (InterruptedException e) {
                // ignore here
            }
        }
    };
    // 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;

    DiffNode fileParent = getFileParent(root, file);

    ITypedElement anc;
    if (ancestorCommit != null)
        anc = CompareUtils.getFileRevisionTypedElement(gitPath, ancestorCommit, map.getRepository());
    else
        anc = null;
    // create the node as child
    new DiffNode(fileParent, kind, anc, leftEditable, right);
}