org.eclipse.jgit.treewalk.FileTreeIterator Java Examples

The following examples show how to use org.eclipse.jgit.treewalk.FileTreeIterator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UIGit.java    From hop with Apache License 2.0 6 votes vote down vote up
private AbstractTreeIterator getTreeIterator( String commitId ) throws Exception {
  if ( commitId == null ) {
    return new EmptyTreeIterator();
  }
  if ( commitId.equals( WORKINGTREE ) ) {
    return new FileTreeIterator( git.getRepository() );
  } else if ( commitId.equals( INDEX ) ) {
    return new DirCacheIterator( git.getRepository().readDirCache() );
  } else {
    ObjectId id = git.getRepository().resolve( commitId );
    if ( id == null ) { // commitId does not exist
      return new EmptyTreeIterator();
    } else {
      CanonicalTreeParser treeIterator = new CanonicalTreeParser();
      try ( RevWalk rw = new RevWalk( git.getRepository() ) ) {
        RevTree tree = rw.parseTree( id );
        try ( ObjectReader reader = git.getRepository().newObjectReader() ) {
          treeIterator.reset( reader, tree.getId() );
        }
      }
      return treeIterator;
    }
  }
}
 
Example #2
Source File: ExportDiffTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testDiffRenameDetectionProblem () throws Exception {
    File file = new File(workDir, "file");
    File renamed = new File(workDir, "renamed");
    write(file, "hey, i will be renamed\n");
    add(file);
    commit(file);

    file.renameTo(renamed);
    write(renamed, "hey, i will be renamed\nand now i am\n");
    ByteArrayOutputStream baos = new ByteArrayOutputStream(10240);
    try (OutputStream out = new BufferedOutputStream(baos);
        DiffFormatter formatter = new DiffFormatter(out);) {
        formatter.setRepository(repository);
        formatter.setDetectRenames(true);
        AbstractTreeIterator firstTree = new DirCacheIterator(repository.readDirCache());
        AbstractTreeIterator secondTree = new FileTreeIterator(repository);
        formatter.format(firstTree, secondTree);
        formatter.flush();
    }
    assertFalse(
        "Fixed in JGit, modify and simplify the sources in ExportDiff command",
        baos.toString().contains("similarity index ")
    );
}
 
Example #3
Source File: GitManagerImpl.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private AbstractTreeIterator prepareTreeParser(Repository repository, String ref) throws IOException {
    if ("~~staged~~".equals(ref)) {
        return new DirCacheIterator(DirCache.read(repository));
    } else if ("~~unstaged~~".equals(ref)) {
        return new FileTreeIterator(repository);
    }

    try (RevWalk walk = new RevWalk(repository)) {
        ObjectId commitObjectId = repository.resolve(ref);
        if (commitObjectId == null) {
            throw new GitInvalidRefException(format("invalid git ref %s", ref));
        }

        log.debug("ref: {}, commit id: {}", ref, commitObjectId.toString());

        RevCommit commit = walk.parseCommit(commitObjectId);
        RevTree tree = walk.parseTree(commit.getTree().getId());

        CanonicalTreeParser treeParser = new CanonicalTreeParser();
        try (ObjectReader objectReader = repository.newObjectReader()) {
            treeParser.reset(objectReader, tree.getId());
        }

        return treeParser;
    }
}
 
Example #4
Source File: RepositoryPGit.java    From coming with MIT License 6 votes vote down vote up
protected void detectRenames(RevTree revTree)
		throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException {
	TreeWalk tw = new TreeWalk(repository);
	tw.setRecursive(true);
	tw.addTree(revTree);
	tw.addTree(new FileTreeIterator(repository));
	RenameDetector rd = new RenameDetector(repository);
	rd.addAll(DiffEntry.scan(tw));

	List<DiffEntry> lde = rd.compute(/* tw.getObjectReader(), null */);
	for (DiffEntry de : lde) {
		if (de.getScore() >= rd.getRenameScore()) {
			System.out.println("file: " + de.getOldPath() + " copied/moved to: " + de.getNewPath() + " ");
		}
	}
}
 
Example #5
Source File: ExportDiffCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private AbstractTreeIterator getIterator (String commit, ObjectReader or) throws IOException, GitException {
    Repository repository = getRepository();
    switch (commit) {
        case Constants.HEAD:
            return getHeadIterator(or);
        case GitClient.INDEX:
            return new DirCacheIterator(repository.readDirCache());
        case GitClient.WORKING_TREE:
            return new FileTreeIterator(repository);
        default:
            CanonicalTreeParser p = new CanonicalTreeParser();
            p.reset(or, Utils.findCommit(repository, commit).getTree());
            return p;
    }
}
 
Example #6
Source File: CheckoutIndex.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void checkout() throws IOException, GitException {
    try (ObjectReader od = repository.newObjectReader();
        TreeWalk treeWalk = new TreeWalk(repository);) {
        Collection<String> relativePaths = Utils.getRelativePaths(repository.getWorkTree(), roots);
        if (!relativePaths.isEmpty()) {
            treeWalk.setFilter(PathFilterGroup.createFromStrings(relativePaths));
        }
        treeWalk.setRecursive(true);
        treeWalk.reset();
        treeWalk.addTree(new DirCacheIterator(cache));
        treeWalk.addTree(new FileTreeIterator(repository));
        String lastAddedPath = null;
        while (treeWalk.next() && !monitor.isCanceled()) {
            File path = new File(repository.getWorkTree(), treeWalk.getPathString());
            if (treeWalk.getPathString().equals(lastAddedPath)) {
                // skip conflicts
                continue;
            } else {
                lastAddedPath = treeWalk.getPathString();
            }
            DirCacheIterator dit = treeWalk.getTree(0, DirCacheIterator.class);
            FileTreeIterator fit = treeWalk.getTree(1, FileTreeIterator.class);
            if (dit != null && (recursively || directChild(roots, repository.getWorkTree(), path)) && (fit == null || fit.isModified(dit.getDirCacheEntry(), checkContent, od))) {
                // update entry
                listener.notifyFile(path, treeWalk.getPathString());
                checkoutEntry(repository, path, dit.getDirCacheEntry(), od);
            }
        }
    }
}
 
Example #7
Source File: UpToDateTask.java    From ant-git-tasks with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute() throws BuildException {
        Repository repo = git.getRepository();

        FileTreeIterator workingTreeIterator = new FileTreeIterator(repo);

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

}
 
Example #8
Source File: AddTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testAddMixedLineEndings () throws Exception {
    File f = new File(workDir, "f");
    String content = "";
    for (int i = 0; i < 10000; ++i) {
        content += i + "\r\n";
    }
    write(f, content);
    File[] files = new File[] { f };
    GitClient client = getClient(workDir);
    client.add(files, NULL_PROGRESS_MONITOR);
    client.commit(files, "commit", null, null, NULL_PROGRESS_MONITOR);
    
    Map<File, GitStatus> statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, workDir, f, true, Status.STATUS_NORMAL, Status.STATUS_NORMAL, Status.STATUS_NORMAL, false);
    
    // lets turn autocrlf on
    StoredConfig cfg = repository.getConfig();
    cfg.setString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, "true");
    cfg.save();
    
    // when this starts failing, remove the work around
    ObjectInserter inserter = repository.newObjectInserter();
    TreeWalk treeWalk = new TreeWalk(repository);
    treeWalk.setFilter(PathFilterGroup.createFromStrings("f"));
    treeWalk.setRecursive(true);
    treeWalk.reset();
    treeWalk.addTree(new FileTreeIterator(repository));
    while (treeWalk.next()) {
        String path = treeWalk.getPathString();
        assertEquals("f", path);
        WorkingTreeIterator fit = treeWalk.getTree(0, WorkingTreeIterator.class);
        try (InputStream in = fit.openEntryStream()) {
            inserter.insert(Constants.OBJ_BLOB, fit.getEntryLength(), in);
            fail("this should fail, remove the work around");
        } catch (EOFException ex) {
            assertEquals("Input did not match supplied length. 10.000 bytes are missing.", ex.getMessage());
        } finally {
            inserter.close();
        }
        break;
    }
    
    // no err should occur
    write(f, content + "hello");
    statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, workDir, f, true, Status.STATUS_NORMAL, Status.STATUS_MODIFIED, Status.STATUS_MODIFIED, false);
    client.add(files, NULL_PROGRESS_MONITOR);
    statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, workDir, f, true, Status.STATUS_MODIFIED, Status.STATUS_NORMAL, Status.STATUS_MODIFIED, false);
    client.commit(files, "message", null, null, NULL_PROGRESS_MONITOR);
    statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, workDir, f, true, Status.STATUS_NORMAL, Status.STATUS_NORMAL, Status.STATUS_NORMAL, false);
}
 
Example #9
Source File: NoGitignoreIterator.java    From writelatex-git-bridge with MIT License 4 votes vote down vote up
protected NoGitignoreIterator(FileTreeIterator p, File root, FS fs) {
    super(p, root, fs);
}