Example usage for org.eclipse.jgit.dircache DirCacheIterator DirCacheIterator

List of usage examples for org.eclipse.jgit.dircache DirCacheIterator DirCacheIterator

Introduction

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

Prototype

public DirCacheIterator(DirCache dc) 

Source Link

Document

Create a new iterator for an already loaded DirCache instance.

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;//from ww  w  .j  av a2 s  .co 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  .ja v  a2 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:com.centurylink.mdw.dataaccess.file.VersionControlGit.java

License:Apache License

public boolean isTracked(String path) throws IOException {
    ObjectId objectId = localRepo.resolve(Constants.HEAD);
    RevTree tree;//from  ww w .  java  2  s  .  c o m
    RevWalk walk = null;
    if (objectId != null) {
        walk = new RevWalk(localRepo);
        tree = walk.parseTree(objectId);
    } else {
        tree = null;
    }

    try (TreeWalk treeWalk = new TreeWalk(localRepo)) {
        treeWalk.setRecursive(true);
        if (tree != null)
            treeWalk.addTree(tree);
        else
            treeWalk.addTree(new EmptyTreeIterator());

        treeWalk.addTree(new DirCacheIterator(localRepo.readDirCache()));
        treeWalk.setFilter(PathFilterGroup.createFromStrings(Collections.singleton(path)));
        return treeWalk.next();
    } finally {
        if (walk != null)
            walk.close();
    }
}

From source file:de.fkoeberle.autocommit.git.GitRepositoryAdapter.java

License:Open Source License

private void visitHeadIndexDelta(GitFileSetDeltaVisitor... visitors) throws IOException {
    TreeWalk treeWalk = new TreeWalk(repository);
    treeWalk.setRecursive(true);/*from  w  w w  .  j  a  va2s .  c o  m*/
    ObjectId headTreeId = repository.resolve(Constants.HEAD);
    DirCache dirCache = repository.readDirCache();
    DirCacheIterator dirCacheTree = new DirCacheIterator(dirCache);
    int dirCacheTreeIndex = treeWalk.addTree(dirCacheTree);

    if (headTreeId == null) {
        while (treeWalk.next()) {
            DirCacheIterator dirCacheMatch = treeWalk.getTree(dirCacheTreeIndex, DirCacheIterator.class);
            final String path = treeWalk.getPathString();
            ObjectId newObjectId = dirCacheMatch.getEntryObjectId();
            for (GitFileSetDeltaVisitor visitor : visitors) {
                visitor.visitAddedFile(path, newObjectId);
            }
        }
    } else {
        RevWalk revWalk = new RevWalk(repository);
        RevTree revTree = revWalk.parseTree(headTreeId);
        int revTreeIndex = treeWalk.addTree(revTree);
        TreeFilter filter = AndTreeFilter.create(TreeFilter.ANY_DIFF,
                new SkipWorkTreeFilter(dirCacheTreeIndex));
        treeWalk.setFilter(filter);

        while (treeWalk.next()) {
            AbstractTreeIterator headMatch = treeWalk.getTree(revTreeIndex, AbstractTreeIterator.class);
            DirCacheIterator dirCacheMatch = treeWalk.getTree(dirCacheTreeIndex, DirCacheIterator.class);
            final String path = treeWalk.getPathString();
            visitDeltaWithAll(path, headMatch, dirCacheMatch, visitors);
        }
    }
}

From source file:org.codice.git.GitHandler.java

License:Open Source License

@Override
public String getDiff() throws Exception {
    final ObjectId head = repo.resolve(Constants.HEAD + "^{tree}");

    if (head == null) {
        LOGGER.warning("Unable to resolve the HEAD of this git tree");
        throw new NoHeadException(JGitText.get().cannotReadTree);
    }/*  w w w  .j av a 2s. c om*/
    final CanonicalTreeParser p = new CanonicalTreeParser();
    final ObjectReader reader = repo.newObjectReader();

    try {
        p.reset(reader, head);
    } finally {
        reader.release();
    }
    final AbstractTreeIterator oldTree = p;
    final AbstractTreeIterator newTree = new DirCacheIterator(repo.readDirCache());
    final OutputStream out = new ByteArrayOutputStream();
    final ChangeOnlyDiffFormatter diffFmt = new ChangeOnlyDiffFormatter(new BufferedOutputStream(out));

    diffFmt.setRepository(repo);
    diffFmt.setPathFilter(TreeFilter.ALL);
    diffFmt.setProgressMonitor(NullProgressMonitor.INSTANCE);

    LOGGER.finer("Scanning the git tree for diffs");
    final List<DiffEntry> result = diffFmt.scan(oldTree, newTree);

    diffFmt.format(result);
    diffFmt.flush();
    diffFmt.release();

    return out.toString();
}

From source file:org.eclipse.che.git.impl.jgit.JGitDiffPage.java

License:Open Source License

/**
 * Show changes between index and working tree.
 *
 * @param formatter/*ww  w . ja  v  a 2 s .  com*/
 *            diff formatter
 * @return list of diff entries
 * @throws IOException
 *             if any i/o errors occurs
 */
private List<DiffEntry> indexToWorkingTree(DiffFormatter formatter) throws IOException {
    DirCache dirCache = null;
    ObjectReader reader = repository.newObjectReader();
    List<DiffEntry> diff;
    try {
        dirCache = repository.lockDirCache();
        DirCacheIterator iterA = new DirCacheIterator(dirCache);
        FileTreeIterator iterB = new FileTreeIterator(repository);
        // Seems bug in DiffFormatter when work with working. Disable detect
        // renames by formatter and do it later.
        formatter.setDetectRenames(false);
        diff = formatter.scan(iterA, iterB);
        if (!request.isNoRenames()) {
            // Detect renames.
            RenameDetector renameDetector = createRenameDetector();
            ContentSource.Pair sourcePairReader = new ContentSource.Pair(ContentSource.create(reader),
                    ContentSource.create(iterB));
            renameDetector.addAll(diff);
            diff = renameDetector.compute(sourcePairReader, NullProgressMonitor.INSTANCE);
        }
    } finally {
        reader.close();
        if (dirCache != null) {
            dirCache.unlock();
        }
    }
    return diff;
}

From source file:org.eclipse.che.git.impl.jgit.JGitDiffPage.java

License:Open Source License

/**
 * Show changes between specified revision and index. If
 * <code>commitId == null</code> then view changes between HEAD and index.
 *
 * @param commitId/*from  w w w  . ja  va2  s.  c om*/
 *            id of commit, pass <code>null</code> is the same as pass HEAD
 * @param formatter
 *            diff formatter
 * @return list of diff entries
 * @throws IOException
 *             if any i/o errors occurs
 */
private List<DiffEntry> commitToIndex(String commitId, DiffFormatter formatter) throws IOException {
    if (commitId == null) {
        commitId = Constants.HEAD;
    }

    ObjectId commitA = repository.resolve(commitId);
    if (commitA == null) {
        throw new IllegalArgumentException("Invalid commit id " + commitId);
    }
    RevTree treeA;
    try (RevWalk revWalkA = new RevWalk(repository)) {
        treeA = revWalkA.parseTree(commitA);
    }

    DirCache dirCache = null;
    List<DiffEntry> diff;
    try (ObjectReader reader = repository.newObjectReader()) {
        dirCache = repository.lockDirCache();
        CanonicalTreeParser iterA = new CanonicalTreeParser();
        iterA.reset(reader, treeA);
        DirCacheIterator iterB = new DirCacheIterator(dirCache);
        if (!request.isNoRenames()) {
            // Use embedded RenameDetector it works well with index and
            // revision history.
            formatter.setDetectRenames(true);
            int renameLimit = request.getRenameLimit();
            if (renameLimit > 0) {
                formatter.getRenameDetector().setRenameLimit(renameLimit);
            }
        }
        diff = formatter.scan(iterA, iterB);
    } finally {
        if (dirCache != null) {
            dirCache.unlock();
        }
    }
    return diff;
}

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

License:Open Source License

/**
 * Refreshes all resources that changed in the index since the last call to
 * this method. This is suitable for incremental updates on index changed
 * events// w ww. j ava2 s  .c om
 *
 * For bare repositories this does nothing.
 */
private void refreshIndexDelta() {
    if (repository.isBare())
        return;

    try {
        DirCache currentIndex = repository.readDirCache();
        DirCache oldIndex = lastIndex;

        lastIndex = currentIndex;

        if (oldIndex == null) {
            refresh(); // full refresh in case we have no data to compare.
            return;
        }

        Set<String> paths = new TreeSet<String>();
        TreeWalk walk = new TreeWalk(repository);

        try {
            walk.addTree(new DirCacheIterator(oldIndex));
            walk.addTree(new DirCacheIterator(currentIndex));
            walk.setFilter(new InterIndexDiffFilter());

            while (walk.next()) {
                if (walk.isSubtree())
                    walk.enterSubtree();
                else
                    paths.add(walk.getPathString());
            }
        } finally {
            walk.release();
        }

        if (!paths.isEmpty())
            refreshFiles(paths);

    } catch (IOException ex) {
        Activator.error(
                MessageFormat.format(CoreText.IndexDiffCacheEntry_errorCalculatingIndexDelta, repository), ex);
        scheduleReloadJob("Exception while calculating index delta, doing full reload instead"); //$NON-NLS-1$
    }
}

From source file:org.eclipse.egit.core.op.CreatePatchOperation.java

License:Open Source License

public void execute(IProgressMonitor monitor) throws CoreException {
    EclipseGitProgressTransformer gitMonitor;
    if (monitor == null)
        gitMonitor = new EclipseGitProgressTransformer(new NullProgressMonitor());
    else/*w w w.  j  a  va  2  s  . co  m*/
        gitMonitor = new EclipseGitProgressTransformer(monitor);

    final StringBuilder sb = new StringBuilder();
    final DiffFormatter diffFmt = new DiffFormatter(new ByteArrayOutputStream() {

        @Override
        public synchronized void write(byte[] b, int off, int len) {
            super.write(b, off, len);
            if (currentEncoding == null)
                sb.append(toString());
            else
                try {
                    sb.append(toString(currentEncoding));
                } catch (UnsupportedEncodingException e) {
                    sb.append(toString());
                }
            reset();
        }
    }) {
        private IProject project;

        @Override
        public void format(DiffEntry ent) throws IOException, CorruptObjectException, MissingObjectException {
            // for "workspace patches" add project header each time project changes
            if (DiffHeaderFormat.WORKSPACE == headerFormat) {
                IProject p = getProject(ent);
                if (!p.equals(project)) {
                    project = p;
                    getOutputStream().write(encodeASCII("#P " + project.getName() + "\n")); //$NON-NLS-1$ //$NON-NLS-2$
                }
            }
            super.format(ent);
        }
    };

    diffFmt.setProgressMonitor(gitMonitor);
    diffFmt.setContext(contextLines);

    if (headerFormat != null && headerFormat != DiffHeaderFormat.NONE)
        writeGitPatchHeader(sb);

    diffFmt.setRepository(repository);
    diffFmt.setPathFilter(pathFilter);

    try {
        if (commit != null) {
            RevCommit[] parents = commit.getParents();
            if (parents.length > 1)
                throw new IllegalStateException(CoreText.CreatePatchOperation_cannotCreatePatchForMergeCommit);
            if (parents.length == 0)
                throw new IllegalStateException(CoreText.CreatePatchOperation_cannotCreatePatchForFirstCommit);

            List<DiffEntry> diffs = diffFmt.scan(parents[0].getId(), commit.getId());
            for (DiffEntry ent : diffs) {
                String path;
                if (ChangeType.DELETE.equals(ent.getChangeType()))
                    path = ent.getOldPath();
                else
                    path = ent.getNewPath();
                currentEncoding = CompareCoreUtils.getResourceEncoding(repository, path);
                diffFmt.format(ent);
            }
        } else
            diffFmt.format(new DirCacheIterator(repository.readDirCache()), new FileTreeIterator(repository));
    } catch (IOException e) {
        Activator.logError(CoreText.CreatePatchOperation_patchFileCouldNotBeWritten, e);
    }

    if (DiffHeaderFormat.WORKSPACE == headerFormat)
        updateWorkspacePatchPrefixes(sb, diffFmt);

    // trim newline
    if (sb.charAt(sb.length() - 1) == '\n')
        sb.setLength(sb.length() - 1);

    patchContent = sb.toString();
}

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

License:Open Source License

private static void loadDataFromGit(GitSynchronizeData gsd, TreeFilter filter, GitSyncObjectCache repoCache) {
    Repository repo = gsd.getRepository();
    TreeWalk tw = new TreeWalk(repo);
    if (filter != null)
        tw.setFilter(filter);/*www . j a  va 2 s.c  o  m*/

    try {
        // setup local tree
        FileTreeIterator fti = null;
        if (gsd.shouldIncludeLocal()) {
            fti = new FileTreeIterator(repo);
            tw.addTree(fti);
            if (filter != null)
                tw.setFilter(AndTreeFilter.create(filter, new NotIgnoredFilter(0)));
            else
                tw.setFilter(new NotIgnoredFilter(0));
        } else if (gsd.getSrcRevCommit() != null)
            tw.addTree(gsd.getSrcRevCommit().getTree());
        else
            tw.addTree(new EmptyTreeIterator());

        // setup base tree
        if (gsd.getCommonAncestorRev() != null)
            tw.addTree(gsd.getCommonAncestorRev().getTree());
        else
            tw.addTree(new EmptyTreeIterator());

        // setup remote tree
        if (gsd.getDstRevCommit() != null)
            tw.addTree(gsd.getDstRevCommit().getTree());
        else
            tw.addTree(new EmptyTreeIterator());

        DirCacheIterator dci = null;
        if (fti != null) {
            dci = new DirCacheIterator(DirCache.read(repo));
            tw.addTree(dci);
            fti.setDirCacheIterator(tw, 3);
        }
        List<ThreeWayDiffEntry> diffEntrys = ThreeWayDiffEntry.scan(tw);
        tw.release();

        for (ThreeWayDiffEntry diffEntry : diffEntrys)
            repoCache.addMember(diffEntry);
    } catch (Exception e) {
        Activator.logError(e.getMessage(), e);
    }
}