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

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

Introduction

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

Prototype

public DirCacheEntry getDirCacheEntry() 

Source Link

Document

Get the DirCacheEntry for the current file.

Usage

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 ww  w  .ja v a 2  s . c om
    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:com.mangosolutions.rcloud.rawgist.repository.git.BareCommitCommand.java

private DirCache createTemporaryIndex(ObjectId headId, DirCache index, RevWalk rw) throws IOException {
    ObjectInserter inserter = null;/*from www  .j ava  2 s. c  o m*/

    // get DirCacheBuilder for existing index
    DirCacheBuilder existingBuilder = index.builder();

    // get DirCacheBuilder for newly created in-core index to build a
    // temporary index for this commit
    DirCache inCoreIndex = DirCache.newInCore();
    DirCacheBuilder tempBuilder = inCoreIndex.builder();

    onlyProcessed = new boolean[only.size()];
    boolean emptyCommit = true;

    try (TreeWalk treeWalk = new TreeWalk(repo)) {
        treeWalk.setOperationType(OperationType.CHECKIN_OP);
        int dcIdx = treeWalk.addTree(new DirCacheBuildIterator(existingBuilder));

        FileModeStrategy fileModeStrategy = this.getRepository().getConfig().get(WorkingTreeOptions.KEY)
                .isDirNoGitLinks() ? NoGitlinksStrategy.INSTANCE : DefaultFileModeStrategy.INSTANCE;

        FileTreeIterator fti = new FileTreeIterator(this.workingFolder, this.getRepository().getFS(),
                this.getRepository().getConfig().get(WorkingTreeOptions.KEY), fileModeStrategy);

        fti.setDirCacheIterator(treeWalk, 0);
        int fIdx = treeWalk.addTree(fti);
        int hIdx = -1;
        if (headId != null) {
            hIdx = treeWalk.addTree(rw.parseTree(headId));
        }
        treeWalk.setRecursive(true);

        String lastAddedFile = null;
        while (treeWalk.next()) {
            String path = treeWalk.getPathString();
            // check if current entry's path matches a specified path
            int pos = lookupOnly(path);

            CanonicalTreeParser hTree = null;
            if (hIdx != -1) {
                hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
            }

            DirCacheIterator dcTree = treeWalk.getTree(dcIdx, DirCacheIterator.class);

            if (pos >= 0) {
                // include entry in commit

                FileTreeIterator fTree = treeWalk.getTree(fIdx, FileTreeIterator.class);

                // check if entry refers to a tracked file
                boolean tracked = dcTree != null || hTree != null;
                if (!tracked) {
                    continue;
                }

                // for an unmerged path, DirCacheBuildIterator will yield 3
                // entries, we only want to add one
                if (path.equals(lastAddedFile)) {
                    continue;
                }

                lastAddedFile = path;

                if (fTree != null) {
                    // create a new DirCacheEntry with data retrieved from
                    // disk
                    final DirCacheEntry dcEntry = new DirCacheEntry(path);
                    long entryLength = fTree.getEntryLength();
                    dcEntry.setLength(entryLength);
                    dcEntry.setLastModified(fTree.getEntryLastModified());
                    dcEntry.setFileMode(fTree.getIndexFileMode(dcTree));

                    boolean objectExists = (dcTree != null && fTree.idEqual(dcTree))
                            || (hTree != null && fTree.idEqual(hTree));
                    if (objectExists) {
                        dcEntry.setObjectId(fTree.getEntryObjectId());
                    } else {
                        if (FileMode.GITLINK.equals(dcEntry.getFileMode())) {
                            dcEntry.setObjectId(fTree.getEntryObjectId());
                        } else {
                            // insert object
                            if (inserter == null) {
                                inserter = repo.newObjectInserter();
                            }
                            long contentLength = fTree.getEntryContentLength();
                            InputStream inputStream = fTree.openEntryStream();
                            try {
                                dcEntry.setObjectId(
                                        inserter.insert(Constants.OBJ_BLOB, contentLength, inputStream));
                            } finally {
                                inputStream.close();
                            }
                        }
                    }

                    // add to existing index
                    existingBuilder.add(dcEntry);
                    // add to temporary in-core index
                    tempBuilder.add(dcEntry);

                    if (emptyCommit && (hTree == null || !hTree.idEqual(fTree)
                            || hTree.getEntryRawMode() != fTree.getEntryRawMode())) {
                        // this is a change
                        emptyCommit = false;
                    }
                } else {
                    // if no file exists on disk, neither add it to
                    // index nor to temporary in-core index

                    if (emptyCommit && hTree != null) {
                        // this is a change
                        emptyCommit = false;
                    }
                }

                // keep track of processed path
                onlyProcessed[pos] = true;
            } else {
                // add entries from HEAD for all other paths
                if (hTree != null) {
                    // create a new DirCacheEntry with data retrieved from
                    // HEAD
                    final DirCacheEntry dcEntry = new DirCacheEntry(path);
                    dcEntry.setObjectId(hTree.getEntryObjectId());
                    dcEntry.setFileMode(hTree.getEntryFileMode());

                    // add to temporary in-core index
                    tempBuilder.add(dcEntry);
                }

                // preserve existing entry in index
                if (dcTree != null) {
                    existingBuilder.add(dcTree.getDirCacheEntry());
                }
            }
        }
    }

    // there must be no unprocessed paths left at this point; otherwise an
    // untracked or unknown path has been specified
    for (int i = 0; i < onlyProcessed.length; i++) {
        if (!onlyProcessed[i]) {
            throw new JGitInternalException(
                    MessageFormat.format(JGitText.get().entryNotFoundByPath, only.get(i)));
        }
    }

    // there must be at least one change
    if (emptyCommit) {
        // Would like to throw a EmptyCommitException. But this would break the API
        // TODO(ch): Change this in the next release
        //         throw new JGitInternalException(JGitText.get().emptyCommit);
    }

    // update index
    existingBuilder.commit();
    // finish temporary in-core index used for this commit
    tempBuilder.finish();
    return inCoreIndex;
}

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  ww w  . j  a  v  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  w ww.  j a v a2s.  com

    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);
}

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

License:Open Source License

private GitModelObject extractFromCache(TreeWalk tw) throws IOException {
    DirCacheIterator cacheIterator = tw.getTree(dirCacheIteratorNth, DirCacheIterator.class);
    if (cacheIterator == null)
        return null;

    DirCacheEntry cacheEntry = cacheIterator.getDirCacheEntry();
    if (cacheEntry == null)
        return null;

    if (shouldIncludeEntry(tw)) {
        String path = new String(tw.getRawPath());
        ObjectId repoId = tw.getObjectId(BASE_NTH);
        ObjectId cacheId = tw.getObjectId(REMOTE_NTH);

        if (path.split("/").length > 1) //$NON-NLS-1$
            return handleCacheTree(repoId, cacheId, path);

        return fileFactory.createFileModel(this, baseCommit, repoId, cacheId, path);
    }//from w  w  w . ja  v  a  2s  . c o m

    return null;
}

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

License:Open Source License

/**
 * Add files modified by model mergers to the index.
 *
 * @throws CorruptObjectException/*from  w ww  .j  av  a2 s.  c o  m*/
 * @throws MissingObjectException
 * @throws IncorrectObjectTypeException
 * @throws IOException
 */
private void indexModelMergedFiles()
        throws CorruptObjectException, MissingObjectException, IncorrectObjectTypeException, IOException {
    TreeWalk syncingTreeWalk = new TreeWalk(getRepository());
    try {
        syncingTreeWalk.addTree(new DirCacheIterator(dircache));
        syncingTreeWalk.addTree(new FileTreeIterator(getRepository()));
        syncingTreeWalk.setRecursive(true);
        syncingTreeWalk.setFilter(PathFilterGroup.createFromStrings(makeInSync));
        String lastAdded = null;
        while (syncingTreeWalk.next()) {
            String path = syncingTreeWalk.getPathString();
            if (path.equals(lastAdded)) {
                continue;
            }

            WorkingTreeIterator workingTree = syncingTreeWalk.getTree(1, WorkingTreeIterator.class);
            DirCacheIterator dirCache = syncingTreeWalk.getTree(0, DirCacheIterator.class);
            if (dirCache == null && workingTree != null && workingTree.isEntryIgnored()) {
                // nothing to do on this one
            } else if (workingTree != null) {
                if (dirCache == null || dirCache.getDirCacheEntry() == null
                        || !dirCache.getDirCacheEntry().isAssumeValid()) {
                    final DirCacheEntry dce = new DirCacheEntry(path);
                    final FileMode mode = workingTree.getIndexFileMode(dirCache);
                    dce.setFileMode(mode);

                    if (FileMode.GITLINK != mode) {
                        dce.setLength(workingTree.getEntryLength());
                        dce.setLastModified(workingTree.getEntryLastModified());
                        InputStream is = workingTree.openEntryStream();
                        try {
                            dce.setObjectId(getObjectInserter().insert(Constants.OBJ_BLOB,
                                    workingTree.getEntryContentLength(), is));
                        } finally {
                            is.close();
                        }
                    } else {
                        dce.setObjectId(workingTree.getEntryObjectId());
                    }
                    builder.add(dce);
                    lastAdded = path;
                } else {
                    builder.add(dirCache.getDirCacheEntry());
                }
            } else if (dirCache != null && FileMode.GITLINK == dirCache.getEntryFileMode()) {
                builder.add(dirCache.getDirCacheEntry());
            }
        }
    } finally {
        syncingTreeWalk.close();
    }
}

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 {/*from w w w  . j a  v  a  2  s.  c  om*/
        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.orion.server.git.jobs.StashApplyCommand.java

License:Eclipse Distribution License

private void resetIndex(RevTree tree) throws IOException {
    DirCache dc = repo.lockDirCache();//from  w ww .  ja  va 2 s .  c o m
    TreeWalk walk = null;
    try {
        DirCacheBuilder builder = dc.builder();

        walk = new TreeWalk(repo);
        walk.addTree(tree);
        walk.addTree(new DirCacheIterator(dc));
        walk.setRecursive(true);

        while (walk.next()) {
            AbstractTreeIterator cIter = walk.getTree(0, AbstractTreeIterator.class);
            if (cIter == null) {
                // Not in commit, don't add to new index
                continue;
            }

            final DirCacheEntry entry = new DirCacheEntry(walk.getRawPath());
            entry.setFileMode(cIter.getEntryFileMode());
            entry.setObjectIdFromRaw(cIter.idBuffer(), cIter.idOffset());

            DirCacheIterator dcIter = walk.getTree(1, DirCacheIterator.class);
            if (dcIter != null && dcIter.idEqual(cIter)) {
                DirCacheEntry indexEntry = dcIter.getDirCacheEntry();
                entry.setLastModified(indexEntry.getLastModified());
                entry.setLength(indexEntry.getLength());
            }

            builder.add(entry);
        }

        builder.commit();
    } finally {
        dc.unlock();
        if (walk != null)
            walk.release();
    }
}

From source file:org.exist.git.xquery.Status.java

License:Open Source License

public void diff(final Repository repository, final String revstr,
        final WorkingTreeIterator initialWorkingTreeIterator, final StatusBuilder builder, final String folder,
        boolean recursive) throws IOException {

    RevTree tree = null;/*from   w ww.  java  2s . co m*/

    ObjectId objectId = repository.resolve(revstr);
    if (objectId != null)
        tree = new RevWalk(repository).parseTree(objectId);
    else
        tree = null;

    PathFilter filter = folder == null || folder.isEmpty() ? null : PathFilter.create(folder);
    IndexDiffFilter indexDiffFilter;

    DirCache dirCache = repository.readDirCache();

    TreeWalk treeWalk = new TreeWalk(repository);
    //      TreeWalk treeWalk = TreeWalk.forPath(repository, folder, tree);
    treeWalk.setRecursive(recursive);
    // add the trees (tree, dirchache, workdir)
    if (tree != null)
        treeWalk.addTree(tree);
    else
        treeWalk.addTree(new EmptyTreeIterator());
    treeWalk.addTree(new DirCacheIterator(dirCache));
    treeWalk.addTree(initialWorkingTreeIterator);
    Collection<TreeFilter> filters = new ArrayList<TreeFilter>(4);

    if (filter != null)
        filters.add(filter);
    filters.add(new SkipWorkTreeFilter(INDEX));
    indexDiffFilter = new IndexDiffFilter(INDEX, WORKDIR);
    filters.add(indexDiffFilter);
    treeWalk.setFilter(AndTreeFilter.create(filters));
    if (filter != null) {
        while (treeWalk.next()) {
            if (filter.include(treeWalk)) {
                if (filter.isDone(treeWalk)) {
                    if (treeWalk.isSubtree()) {
                        treeWalk.enterSubtree();
                    }
                    break;
                } else if (treeWalk.isSubtree()) {
                    treeWalk.enterSubtree();
                }
            }
        }
    }

    while (treeWalk.next()) {
        AbstractTreeIterator treeIterator = treeWalk.getTree(TREE, AbstractTreeIterator.class);
        DirCacheIterator dirCacheIterator = treeWalk.getTree(INDEX, DirCacheIterator.class);
        WorkingTreeIterator workingTreeIterator = treeWalk.getTree(WORKDIR, WorkingTreeIterator.class);

        if (dirCacheIterator != null) {
            final DirCacheEntry dirCacheEntry = dirCacheIterator.getDirCacheEntry();
            if (dirCacheEntry != null && dirCacheEntry.getStage() > 0) {
                builder.conflict(treeWalk.getFileMode(2), treeWalk.getPathString());
                continue;
            }
        }

        if (treeIterator != null) {
            if (dirCacheIterator != null) {
                if (!treeIterator.idEqual(dirCacheIterator)
                        || treeIterator.getEntryRawMode() != dirCacheIterator.getEntryRawMode()) {
                    // in repo, in index, content diff => changed
                    builder.changed(treeWalk.getFileMode(2), treeWalk.getPathString());
                    continue;
                }
            } else {
                // in repo, not in index => removed
                builder.removed(treeWalk.getFileMode(2), treeWalk.getPathString());
                if (workingTreeIterator != null) //XXX: 2 statuses
                    builder.untracked(treeWalk.getFileMode(2), treeWalk.getPathString());
                continue;
            }
        } else {
            if (dirCacheIterator != null) {
                // not in repo, in index => added
                builder.added(treeWalk.getFileMode(2), treeWalk.getPathString());
                continue;
            } else {
                // not in repo, not in index => untracked
                if (workingTreeIterator != null && !workingTreeIterator.isEntryIgnored()) {
                    builder.untracked(treeWalk.getFileMode(2), treeWalk.getPathString());
                    continue;
                }
            }
        }

        if (dirCacheIterator != null) {
            if (workingTreeIterator == null) {
                // in index, not in workdir => missing
                builder.missing(treeWalk.getFileMode(2), treeWalk.getPathString());
                continue;
            } else {
                if (dirCacheIterator.getDirCacheEntry() == null) {
                    //XXX: null on collections - to fix
                    //                  builder.unchanged(treeWalk.getFileMode(2), treeWalk.getPathString());

                } else if (workingTreeIterator.isModified(dirCacheIterator.getDirCacheEntry(), true)) {
                    // in index, in workdir, content differs => modified
                    builder.modified(treeWalk.getFileMode(2), treeWalk.getPathString());
                    continue;
                }
            }
        }
        builder.unchanged(treeWalk.getFileMode(2), treeWalk.getPathString());
    }

    //      for (String path : indexDiffFilter.getUntrackedFolders()) {
    //         builder.untrackedFolders(path);
    //      }
    //      
    for (String path : indexDiffFilter.getIgnoredPaths()) {
        //XXX: to fix FileMode
        builder.ignored(FileMode.REGULAR_FILE, path);
    }
}

From source file:org.oecd.ant.git.custom.CustomAddCommand.java

License:Eclipse Distribution License

/**
 * Executes the {@code Add} command. Each instance of this class should only be used for one invocation of the command. Don't call this method twice on an
 * instance.//from ww  w .  j  av a  2 s.c  om
 *
 * @return the DirCache after Add
 */
@Override
public DirCache call() throws GitAPIException, NoFilepatternException {

    if (filepatterns.isEmpty())
        throw new NoFilepatternException(JGitText.get().atLeastOnePatternIsRequired);
    checkCallable();
    DirCache dc = null;
    boolean addAll = false;
    if (filepatterns.contains(".")) //$NON-NLS-1$
        addAll = true;

    try (ObjectInserter inserter = repo.newObjectInserter(); final TreeWalk tw = new TreeWalk(repo)) {
        dc = repo.lockDirCache();
        DirCacheIterator c;

        DirCacheBuilder builder = dc.builder();
        tw.addTree(new DirCacheBuildIterator(builder));
        if (workingTreeIterator == null)
            workingTreeIterator = new FileTreeIterator(repo);
        tw.addTree(workingTreeIterator);
        tw.setRecursive(true);
        if (!addAll)
            tw.setFilter(PathFilterGroup.createFromStrings(filepatterns));

        String lastAddedFile = null;

        while (tw.next()) {
            String path = tw.getPathString();

            WorkingTreeIterator f = tw.getTree(1, WorkingTreeIterator.class);
            if (tw.getTree(0, DirCacheIterator.class) == null && f != null && f.isEntryIgnored()) {
                // file is not in index but is ignored, do nothing
            }
            // 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.
            else if (!(path.equals(lastAddedFile))) {
                if (all || !(update && tw.getTree(0, DirCacheIterator.class) == null)) {
                    c = tw.getTree(0, DirCacheIterator.class);
                    if (f != null) { // the file exists
                        long sz = f.getEntryLength();
                        DirCacheEntry entry = new DirCacheEntry(path);
                        if (c == null || c.getDirCacheEntry() == null
                                || !c.getDirCacheEntry().isAssumeValid()) {
                            FileMode mode = f.getIndexFileMode(c);
                            entry.setFileMode(mode);

                            if (FileMode.GITLINK != mode) {
                                entry.setLength(sz);
                                entry.setLastModified(f.getEntryLastModified());
                                long contentSize = f.getEntryContentLength();
                                InputStream in = f.openEntryStream();
                                try {
                                    entry.setObjectId(inserter.insert(Constants.OBJ_BLOB, contentSize, in));
                                } finally {
                                    in.close();
                                }
                            } else
                                entry.setObjectId(f.getEntryObjectId());
                            builder.add(entry);
                            lastAddedFile = path;
                        } else {
                            builder.add(c.getDirCacheEntry());
                        }

                    } else if (c != null && (!(all || update) || FileMode.GITLINK == c.getEntryFileMode()))
                        builder.add(c.getDirCacheEntry());
                }
            }
        }
        inserter.flush();
        builder.commit();
        setCallable(false);
    } catch (IOException e) {
        throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfAddCommand, e);
    } finally {
        if (dc != null)
            dc.unlock();
    }

    return dc;
}