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

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

Introduction

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

Prototype

public DirCacheBuildIterator(DirCacheBuilder dcb) 

Source Link

Document

Create a new iterator for an already loaded DirCache instance.

Usage

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

License:Eclipse Distribution License

/**
 * The resolve conflict way of three way merging
 *
 * @param baseTree//from  w w  w. j av  a2 s .c o  m
 * @param headTree
 * @param mergeTree
 * @param ignoreConflicts
 *          Controls what to do in case a content-merge is done and a
 *          conflict is detected. The default setting for this should be
 *          <code>false</code>. In this case the working tree file is
 *          filled with new content (containing conflict markers) and the
 *          index is filled with multiple stages containing BASE, OURS and
 *          THEIRS content. Having such non-0 stages is the sign to git
 *          tools that there are still conflicts for that path.
 *          <p>
 *          If <code>true</code> is specified the behavior is different.
 *          In case a conflict is detected the working tree file is again
 *          filled with new content (containing conflict markers). But
 *          also stage 0 of the index is filled with that content. No
 *          other stages are filled. Means: there is no conflict on that
 *          path but the new content (including conflict markers) is
 *          stored as successful merge result. This is needed in the
 *          context of {@link RecursiveMerger} where when determining
 *          merge bases we don't want to deal with content-merge
 *          conflicts.
 * @return whether the trees merged cleanly
 * @throws IOException
 * @since 3.5
 */
@Override
protected boolean mergeTrees(AbstractTreeIterator baseTree, RevTree headTree, RevTree mergeTree,
        boolean ignoreConflicts) throws IOException {

    this.builder = this.dircache.builder();
    DirCacheBuildIterator buildIt = new DirCacheBuildIterator(this.builder);

    this.tw = new NameConflictTreeWalk(this.reader);
    this.tw.addTree(baseTree);
    this.tw.addTree(headTree);
    this.tw.addTree(mergeTree);
    this.tw.addTree(buildIt);
    if (this.workingTreeIterator != null) {
        this.tw.addTree(this.workingTreeIterator);
    } else {
        this.tw.setFilter(TreeFilter.ANY_DIFF);
    }

    if (!mergeTreeWalk(this.tw, ignoreConflicts)) {
        return false;
    }

    if (!this.inCore) {
        // No problem found. The only thing left to be done is to
        // checkout all files from "theirs" which have been selected to
        // go into the new index.
        checkout();

        // All content-merges are successfully done. If we can now write the
        // new index we are on quite safe ground. Even if the checkout of
        // files coming from "theirs" fails the user can work around such
        // failures by checking out the index again.
        if (!this.builder.commit()) {
            cleanUp();
            throw new IndexWriteException();
        }
        this.builder = null;

    } else {
        this.builder.finish();
        this.builder = null;
    }

    if (getUnmergedPaths().isEmpty() && !failed()) {
        this.resultTree = this.dircache.writeTree(getObjectInserter());
        return true;
    } else {
        this.resultTree = null;
        return false;
    }
}

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  . j  av  a  2 s.  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:com.mangosolutions.rcloud.rawgist.repository.git.BareCommitCommand.java

private DirCache createTemporaryIndex(ObjectId headId, DirCache index, RevWalk rw) throws IOException {
    ObjectInserter inserter = null;/*  w w w . j a v  a 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:com.mangosolutions.rcloud.rawgist.repository.git.BareRmCommand.java

/**
 * Executes the {@code Rm} 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   www  .j ava  2s  .com*/
 *
 * @return the DirCache after Rm
 */
public DirCache call() throws GitAPIException, NoFilepatternException {

    if (filepatterns.isEmpty()) {
        throw new NoFilepatternException(JGitText.get().atLeastOnePatternIsRequired);
    }
    checkCallable();

    try (final TreeWalk tw = new TreeWalk(repo)) {
        index.lock();
        DirCacheBuilder builder = index.builder();
        tw.reset(); // drop the first empty tree, which we do not need here
        tw.setRecursive(true);
        tw.setFilter(PathFilterGroup.createFromStrings(filepatterns));
        tw.addTree(new DirCacheBuildIterator(builder));

        while (tw.next()) {
            if (!cached) {
                final FileMode mode = tw.getFileMode(0);
                if (mode.getObjectType() == Constants.OBJ_BLOB) {
                    final File path = new File(repo.getWorkTree(), tw.getPathString());
                    // Deleting a blob is simply a matter of removing
                    // the file or symlink named by the tree entry.
                    delete(path);
                }
            }
        }
        builder.commit();
        setCallable(false);
    } catch (IOException e) {
        throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfRmCommand, e);
    } finally {
        if (index != null) {
            index.unlock();
        }
    }

    return index;
}

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  a  v a  2 s  .  c o m*/
 *
 * @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;
}