Example usage for org.eclipse.jgit.treewalk FileTreeIterator FileTreeIterator

List of usage examples for org.eclipse.jgit.treewalk FileTreeIterator FileTreeIterator

Introduction

In this page you can find the example usage for org.eclipse.jgit.treewalk FileTreeIterator FileTreeIterator.

Prototype

public FileTreeIterator(Repository repo) 

Source Link

Document

Create a new iterator to traverse the work tree and its children.

Usage

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  va  2  s . c o m
    case GitModeMenuMgr.MODE_OTHERS://choose a GIT ref
        CompareTargetSelectionDialog dialog = new CompareTargetSelectionDialog(shell, rep, null);
        if (dialog.open() != CompareTargetSelectionDialog.OK) {
            return -2;
        }
        ObjectId obId = rep.getRef(dialog.getRefName()).getObjectId();//"master"
        tw.addTree(rw.parseCommit(obId).getTree());
        break;
    case GitModeMenuMgr.MODE_BRANCH_HEAD:
        Ref head = rep.getRef(Constants.HEAD);
        RevCommit rc = rw.parseCommit(head.getObjectId());
        tw.addTree(rc.getTree());
        break;
    default://compare to working area
        index = tw.addTree(new FileTreeIterator(rep));
        break;
    }
    return index;
}

From source file:com.github.koraktor.mavanagaiata.git.jgit.JGitRepository.java

License:Open Source License

public boolean isDirty(boolean ignoreUntracked) throws GitRepositoryException {
    try {//from w w w. j  a v a 2  s  .  com
        FileTreeIterator workTreeIterator = new FileTreeIterator(this.repository);
        IndexDiff indexDiff = new IndexDiff(this.repository, this.getHeadObject(), workTreeIterator);
        indexDiff.diff();

        if (!ignoreUntracked && !indexDiff.getUntracked().isEmpty()) {
            return true;
        }

        return !(indexDiff.getAdded().isEmpty() && indexDiff.getChanged().isEmpty()
                && indexDiff.getRemoved().isEmpty() && indexDiff.getMissing().isEmpty()
                && indexDiff.getModified().isEmpty() && indexDiff.getConflicting().isEmpty());

    } catch (IOException e) {
        throw new GitRepositoryException("Could not create repository diff.", e);
    }
}

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 a  v a2s.  com*/
    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.rimerosolutions.ant.git.tasks.UpToDateTask.java

License:Apache License

@Override
protected void doExecute() throws BuildException {
    Repository repo = git.getRepository();

    FileTreeIterator workingTreeIterator = new FileTreeIterator(repo);

    try {//from   ww  w  .j  av  a 2s.c o  m
        IndexDiff diff = new IndexDiff(repo, Constants.HEAD, workingTreeIterator);
        diff.diff();

        Status status = new Status(diff);

        if (!status.isClean()) {
            if (modificationExistProperty != null) {
                getProject().setProperty(modificationExistProperty, "true");
            }

            if (isFailOnError()) {
                StringBuilder msg = new StringBuilder();
                msg.append("The Git tree was modified.");
                msg.append("\n").append("Changed:").append(status.getChanged());
                msg.append("\n").append("Added:").append(status.getAdded());
                msg.append("\n").append("Modified:").append(status.getModified());
                msg.append("\n").append("Missing:").append(status.getMissing());
                msg.append("\n").append("Removed:").append(status.getRemoved());
                msg.append("\n").append("Untracked:").append(status.getUntracked());

                throw new GitBuildException(String.format(STATUS_NOT_CLEAN_TEMPLATE, msg.toString()));
            }
        } else {
            log(MESSAGE_UPTODATE_SUCCESS);
        }
    } catch (IOException ioe) {
        throw new GitBuildException(MESSAGE_UPTODATE_FAILED, ioe);
    }

}

From source file:com.stormcloud.ide.api.git.GitManager.java

License:Open Source License

@Override
public IndexState getIndexState(String repository) throws GitManagerException {

    IndexState indexState = new IndexState();

    try {//from w ww  . j  a v  a 2 s  . c o m

        Git git = Git.open(new File(repository));

        IndexDiff diff = new IndexDiff(git.getRepository(), "HEAD", new FileTreeIterator(git.getRepository()));

        diff.diff();

        indexState.setAdded(diff.getAdded());
        indexState.setAssumeUnchanged(diff.getAssumeUnchanged());
        indexState.setChanged(diff.getChanged());
        indexState.setConflicting(diff.getConflicting());
        indexState.setIgnoredNotInIndex(diff.getIgnoredNotInIndex());
        indexState.setMissing(diff.getMissing());
        indexState.setModified(diff.getModified());
        indexState.setRemoved(diff.getRemoved());
        indexState.setUntracked(diff.getUntracked());
        indexState.setUntrackedFolders(diff.getUntrackedFolders());

    } catch (IOException e) {
        LOG.error(e);
        throw new GitManagerException(e);
    }

    return indexState;
}

From source file:com.stormcloud.ide.api.git.GitManager.java

License:Open Source License

@Override
public boolean isModified(String repository) throws GitManagerException {

    try {/*from  w ww.  j  a  va2s  .  c o  m*/

        Git git = Git.open(new File(repository));

        IndexDiff diff = new IndexDiff(git.getRepository(), "HEAD", new FileTreeIterator(git.getRepository()));

        diff.diff();

        if (!diff.getAdded().isEmpty()) {
            return true;
        }

        if (!diff.getChanged().isEmpty()) {
            return true;
        }

        if (!diff.getMissing().isEmpty()) {
            return true;
        }

        if (!diff.getModified().isEmpty()) {
            return true;
        }

        if (!diff.getRemoved().isEmpty()) {
            return true;
        }

        if (!diff.getUntracked().isEmpty()) {
            return true;
        }

        if (!diff.getUntrackedFolders().isEmpty()) {
            return true;
        }

    } catch (IOException e) {
        LOG.error(e);
        throw new GitManagerException(e);
    }

    return false;
}

From source file:com.stormcloud.ide.api.git.GitManager.java

License:Open Source License

@Override
public void log(String repo) throws GitManagerException {

    try {// w  w  w .  j  a va 2s  . co  m
        File gitDir = new File(repo + "/.git");
        LOG.info("gitDir:" + gitDir);
        Repository repository = new FileRepository(gitDir);

        WorkingTreeIterator fileTreeIterator = new FileTreeIterator(repository);

        IndexDiff indexDiff = new IndexDiff(repository, Constants.HEAD, fileTreeIterator);

        boolean hasDiff = indexDiff.diff();

        LOG.info("hasDiff " + hasDiff);

        if (hasDiff) {

            for (String file : indexDiff.getAdded()) {
                LOG.info("Added " + file);
            }

            for (String file : indexDiff.getAssumeUnchanged()) {
                LOG.info("Assume Unchanged " + file);
            }

            for (String file : indexDiff.getChanged()) {
                LOG.info("Changed " + file);
            }

            for (String file : indexDiff.getConflicting()) {
                LOG.info("Conflicting " + file);
            }

            for (String file : indexDiff.getIgnoredNotInIndex()) {
                LOG.info("Ignored not in index " + file);
            }

            for (String file : indexDiff.getMissing()) {
                LOG.info("Missing " + file);
            }

            for (String file : indexDiff.getModified()) {
                LOG.info("Modified " + file);
            }

            for (String file : indexDiff.getRemoved()) {
                LOG.info("Removed " + file);
            }

            for (String file : indexDiff.getUntracked()) {
                LOG.info("Untracked " + file);
            }

            for (String file : indexDiff.getUntrackedFolders()) {
                LOG.info("Untracked Folders " + file);
            }
        }

    } catch (IOException e) {
        LOG.error(e);
        throw new GitManagerException(e);
    }

}

From source file:com.stormcloud.ide.api.git.GitManager.java

License:Open Source License

@Override
public String getStatus(String file, String userHome) throws GitManagerException {

    String tmpRelativePath = new File(file).getAbsolutePath().replaceFirst(userHome + "/projects", "")
            .replaceFirst("/", "");

    String project;/*  w  w  w.  j  a  va  2s  . c  o m*/

    if (tmpRelativePath.contains("/")) {

        project = tmpRelativePath.substring(0, tmpRelativePath.indexOf('/'));

    } else {

        project = tmpRelativePath;
    }

    String repository = userHome + "/projects/" + project;
    String relativePath = tmpRelativePath.replaceFirst(project, "").replaceFirst("/", "");

    String status = "unmodified";

    try {

        Git git = Git.open(new File(repository));

        IndexDiff diff = new IndexDiff(git.getRepository(), "HEAD", new FileTreeIterator(git.getRepository()));

        diff.setFilter(PathFilterGroup.createFromStrings(relativePath));

        diff.diff();

        if (!diff.getModified().isEmpty() || !diff.getChanged().isEmpty()) {
            return "modified";
        }

        if (!diff.getMissing().isEmpty() || !diff.getRemoved().isEmpty()) {
            return "missing";
        }

        if (!diff.getUntracked().isEmpty() || !diff.getUntrackedFolders().isEmpty()
                || !diff.getAdded().isEmpty()) {

            return "untracked";
        }

        if (!diff.getConflicting().isEmpty()) {
            return "conflict";
        }

        return status;

    } catch (IOException e) {
        LOG.error(e);
        throw new GitManagerException(e);
    }
}

From source file:com.tenxdev.ovcs.command.DiffCommand.java

License:Open Source License

/**
 * {@inheritDoc}/*  w  w  w. j a  v a  2 s .c  o m*/
 */
@Override
public void execute(final String... args) throws OvcsException {
    if (args.length != 1 && args.length != 2) {
        throw new UsageException(USAGE);
    }
    String targetObject = null;
    if (args.length == 2) {
        targetObject = args[1].toUpperCase(Locale.getDefault());
        if (!targetObject.toLowerCase(Locale.getDefault()).endsWith(".sql")) {
            targetObject = targetObject + ".sql";
        }
    }
    final FileRepository fileRepository = getRepoForCurrentDir();
    try {
        writeChanges(fileRepository);
        final DiffFormatter formatter = new DiffFormatter(System.out);
        formatter.setNewPrefix("new/");
        formatter.setOldPrefix("old/");
        formatter.setRepository(fileRepository);
        if (targetObject != null) {
            formatter.setPathFilter(PathFilter.create(targetObject));
        }
        final AbstractTreeIterator commitTreeIterator = GitUtils.prepareHeadTreeParser(fileRepository);
        final FileTreeIterator workTreeIterator = new FileTreeIterator(fileRepository);
        final List<DiffEntry> diffEntries = formatter.scan(commitTreeIterator, workTreeIterator);

        for (final DiffEntry entry : diffEntries) {
            System.out.println("Entry: " + entry);
            formatter.format(entry);
        }
    } catch (final IOException e) {
        throw new OvcsException("Unable to generate diff: " + e.getMessage(), e);
    } finally {
        fileRepository.close();
    }
}

From source file:elegit.DiffHelper.java

License:Open Source License

private String getDiffString() throws GitAPIException, IOException {
    ObjectId head = this.repo.resolve("HEAD");
    if (head == null)
        return "";

    // The following code is largely written by Tk421 on StackOverflow
    //      (http://stackoverflow.com/q/23486483)
    // Thanks! NOTE: comments are mine.
    ByteArrayOutputStream diffOutputStream = new ByteArrayOutputStream();
    DiffFormatter formatter = new DiffFormatter(diffOutputStream);
    formatter.setRepository(this.repo);
    formatter.setPathFilter(PathFilter.create(this.pathFilter.replaceAll("\\\\", "/")));

    AbstractTreeIterator commitTreeIterator = prepareTreeParser(this.repo, head.getName());
    FileTreeIterator workTreeIterator = new FileTreeIterator(this.repo);

    // Scan gets difference between the two iterators.
    formatter.format(commitTreeIterator, workTreeIterator);

    return diffOutputStream.toString();
}