org.eclipse.jgit.treewalk.WorkingTreeIterator Java Examples

The following examples show how to use org.eclipse.jgit.treewalk.WorkingTreeIterator. 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: ResolveMerger.java    From onedev with MIT License 6 votes vote down vote up
/**
 * Process the given TreeWalk's entries.
 *
 * @param treeWalk
 *            The walk to iterate over.
 * @param ignoreConflicts
 *            see
 *            {@link org.eclipse.jgit.merge.ResolveMerger#mergeTrees(AbstractTreeIterator, RevTree, RevTree, boolean)}
 * @return Whether the trees merged cleanly.
 * @throws java.io.IOException
 * @since 3.5
 */
protected boolean mergeTreeWalk(TreeWalk treeWalk, boolean ignoreConflicts)
		throws IOException {
	boolean hasWorkingTreeIterator = tw.getTreeCount() > T_FILE;
	boolean hasAttributeNodeProvider = treeWalk
			.getAttributesNodeProvider() != null;
	while (treeWalk.next()) {
		if (!processEntry(
				treeWalk.getTree(T_BASE, CanonicalTreeParser.class),
				treeWalk.getTree(T_OURS, CanonicalTreeParser.class),
				treeWalk.getTree(T_THEIRS, CanonicalTreeParser.class),
				treeWalk.getTree(T_INDEX, DirCacheBuildIterator.class),
				hasWorkingTreeIterator ? treeWalk.getTree(T_FILE,
						WorkingTreeIterator.class) : null,
				ignoreConflicts, hasAttributeNodeProvider
						? treeWalk.getAttributes()
						: NO_ATTRIBUTES)) {
			cleanUp();
			return false;
		}
		if (treeWalk.isSubtree() && enterSubtree)
			treeWalk.enterSubtree();
	}
	return true;
}
 
Example #2
Source File: CleanCommand.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void deleteIfUnversioned(DirCache cache, String path, WorkingTreeIterator f, Repository repository, TreeWalk treeWalk) throws IOException, NoWorkTreeException {
    if (cache.getEntry(path) == null &&  // not in index 
        !f.isEntryIgnored() &&             // not ignored
        !Utils.isFromNested(f.getEntryFileMode().getBits()))
    {            
        File file = new File(repository.getWorkTree().getAbsolutePath() + File.separator + path);                        
        if(file.isDirectory()) {
            String[] s = file.list();
            if(s != null && s.length > 0) { // XXX is there no better way to find out if empty?
                // not empty
                return; 
            }
        }
        file.delete();
        listener.notifyFile(file, treeWalk.getPathString());
    }
}
 
Example #3
Source File: ResolveMerger.java    From onedev with MIT License 5 votes vote down vote up
private boolean isWorktreeDirty(WorkingTreeIterator work,
		DirCacheEntry ourDce) throws IOException {
	if (work == null)
		return false;

	final int modeF = tw.getRawMode(T_FILE);
	final int modeO = tw.getRawMode(T_OURS);

	// Worktree entry has to match ours to be considered clean
	boolean isDirty;
	if (ourDce != null)
		isDirty = work.isModified(ourDce, true, reader);
	else {
		isDirty = work.isModeDifferent(modeO);
		if (!isDirty && nonTree(modeF))
			isDirty = !tw.idEqual(T_FILE, T_OURS);
	}

	// Ignore existing empty directories
	if (isDirty && modeF == FileMode.TYPE_TREE
			&& modeO == FileMode.TYPE_MISSING)
		isDirty = false;
	if (isDirty)
		failingPaths.put(tw.getPathString(),
				MergeFailureReason.DIRTY_WORKTREE);
	return isDirty;
}
 
Example #4
Source File: CherryPickCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public ThreeWayMerger newMerger (Repository db, boolean inCore) {
    return new RecursiveMerger(db, inCore) {
        protected boolean mergeTreeWalk (TreeWalk treeWalk, boolean ignoreConflicts)
                throws IOException {
            boolean ok = true;
            boolean hasWorkingTreeIterator = tw.getTreeCount() > T_FILE;
            boolean hasAttributeNodeProvider = treeWalk.getAttributesNodeProvider() != null;
            while (treeWalk.next()) {
                if (!processEntry(
                        treeWalk.getTree(T_BASE, CanonicalTreeParser.class),
                        treeWalk.getTree(T_OURS, CanonicalTreeParser.class),
                        treeWalk.getTree(T_THEIRS, CanonicalTreeParser.class),
                        treeWalk.getTree(T_INDEX, DirCacheBuildIterator.class),
                        hasWorkingTreeIterator ? treeWalk.getTree(T_FILE, WorkingTreeIterator.class) : null,
                        ignoreConflicts,
                        hasAttributeNodeProvider ? treeWalk.getAttributes() : NO_ATTRIBUTES
                )) {
                    ok = false;
                }
                if (treeWalk.isSubtree() && enterSubtree) {
                    treeWalk.enterSubtree();
                }
            }
            if (!ok) {
                cleanUp();
            }
            return ok;
        }
    };
}
 
Example #5
Source File: NoGitignoreIterator.java    From writelatex-git-bridge with MIT License 5 votes vote down vote up
protected NoGitignoreIterator(
        WorkingTreeIterator p,
        File root,
        FS fs,
        FileModeStrategy fileModeStrategy
) {
    super(p, root, fs, fileModeStrategy);
}
 
Example #6
Source File: RecursiveMerger.java    From onedev with MIT License 4 votes vote down vote up
/**
 * Get a single base commit for two given commits. If the two source commits
 * have more than one base commit recursively merge the base commits
 * together until a virtual common base commit has been found.
 *
 * @param a
 *            the first commit to be merged
 * @param b
 *            the second commit to be merged
 * @param callDepth
 *            the callDepth when this method is called recursively
 * @return the merge base of two commits. If a criss-cross merge required a
 *         synthetic merge base this commit is visible only the merger's
 *         RevWalk and will not be in the repository.
 * @throws java.io.IOException
 * @throws IncorrectObjectTypeException
 *             one of the input objects is not a commit.
 * @throws NoMergeBaseException
 *             too many merge bases are found or the computation of a common
 *             merge base failed (e.g. because of a conflict).
 */
protected RevCommit getBaseCommit(RevCommit a, RevCommit b, int callDepth)
		throws IOException {
	ArrayList<RevCommit> baseCommits = new ArrayList<>();
	walk.reset();
	walk.setRevFilter(RevFilter.MERGE_BASE);
	walk.markStart(a);
	walk.markStart(b);
	RevCommit c;
	while ((c = walk.next()) != null)
		baseCommits.add(c);

	if (baseCommits.isEmpty())
		return null;
	if (baseCommits.size() == 1)
		return baseCommits.get(0);
	if (baseCommits.size() >= MAX_BASES)
		throw new NoMergeBaseException(NoMergeBaseException.MergeBaseFailureReason.TOO_MANY_MERGE_BASES, MessageFormat.format(
				JGitText.get().mergeRecursiveTooManyMergeBasesFor,
				Integer.valueOf(MAX_BASES), a.name(), b.name(),
						Integer.valueOf(baseCommits.size())));

	// We know we have more than one base commit. We have to do merges now
	// to determine a single base commit. We don't want to spoil the current
	// dircache and working tree with the results of this intermediate
	// merges. Therefore set the dircache to a new in-memory dircache and
	// disable that we update the working-tree. We set this back to the
	// original values once a single base commit is created.
	RevCommit currentBase = baseCommits.get(0);
	DirCache oldDircache = dircache;
	boolean oldIncore = inCore;
	WorkingTreeIterator oldWTreeIt = workingTreeIterator;
	workingTreeIterator = null;
	try {
		dircache = DirCache.read(reader, currentBase.getTree());
		inCore = true;

		List<RevCommit> parents = new ArrayList<>();
		parents.add(currentBase);
		for (int commitIdx = 1; commitIdx < baseCommits.size(); commitIdx++) {
			RevCommit nextBase = baseCommits.get(commitIdx);
			if (commitIdx >= MAX_BASES)
				throw new NoMergeBaseException(
						NoMergeBaseException.MergeBaseFailureReason.TOO_MANY_MERGE_BASES,
						MessageFormat.format(
						JGitText.get().mergeRecursiveTooManyMergeBasesFor,
						Integer.valueOf(MAX_BASES), a.name(), b.name(),
								Integer.valueOf(baseCommits.size())));
			parents.add(nextBase);
			RevCommit bc = getBaseCommit(currentBase, nextBase,
					callDepth + 1);
			AbstractTreeIterator bcTree = (bc == null) ? new EmptyTreeIterator()
					: openTree(bc.getTree());
			if (mergeTrees(bcTree, currentBase.getTree(),
					nextBase.getTree(), true))
				currentBase = createCommitForTree(resultTree, parents);
			else
				throw new NoMergeBaseException(
						NoMergeBaseException.MergeBaseFailureReason.CONFLICTS_DURING_MERGE_BASE_CALCULATION,
						MessageFormat.format(
								JGitText.get().mergeRecursiveConflictsWhenMergingCommonAncestors,
								currentBase.getName(), nextBase.getName()));
		}
	} finally {
		inCore = oldIncore;
		dircache = oldDircache;
		workingTreeIterator = oldWTreeIt;
		toBeCheckedOut.clear();
		toBeDeleted.clear();
		modifiedFiles.clear();
		unmergedPaths.clear();
		mergeResults.clear();
		failingPaths.clear();
	}
	return currentBase;
}
 
Example #7
Source File: ExportDiffCommand.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
  protected void run() throws GitException {
      Repository repository = getRepository();
      String workTreePath = repository.getWorkTree().getAbsolutePath();
      try (DiffFormatter formatter = new DiffFormatter(out);
          ObjectReader or = repository.newObjectReader()) {
          formatter.setRepository(repository);
          Collection<PathFilter> pathFilters = Utils.getPathFilters(repository.getWorkTree(), roots);
          if (!pathFilters.isEmpty()) {
              formatter.setPathFilter(PathFilterGroup.create(pathFilters));
          }
          if (repository.getConfig().get(WorkingTreeOptions.KEY).getAutoCRLF() != CoreConfig.AutoCRLF.FALSE) {
              // work-around for autocrlf
              formatter.setDiffComparator(new AutoCRLFComparator());
          }
          AbstractTreeIterator firstTree = getIterator(firstCommit, or);
          AbstractTreeIterator secondTree = getIterator(secondCommit, or);
          List<DiffEntry> diffEntries;
          if (secondTree instanceof WorkingTreeIterator) {
              // remote when fixed in JGit, see ExportDiffTest.testDiffRenameDetectionProblem
              formatter.setDetectRenames(false);
              diffEntries = formatter.scan(firstTree, secondTree);
              formatter.setDetectRenames(true);
              RenameDetector detector = formatter.getRenameDetector();
              detector.reset();
              detector.addAll(diffEntries);
diffEntries = detector.compute(new ContentSource.Pair(ContentSource.create(or), ContentSource.create((WorkingTreeIterator) secondTree)), NullProgressMonitor.INSTANCE);
          } else {
              formatter.setDetectRenames(true);
              diffEntries = formatter.scan(firstTree, secondTree);
          }
          for (DiffEntry ent : diffEntries) {
              if (monitor.isCanceled()) {
                  break;
              }
              listener.notifyFile(new File(workTreePath + File.separator + ent.getNewPath()), ent.getNewPath());
              formatter.format(ent);
          }
          formatter.flush();
      } catch (IOException ex) {
          throw new GitException(ex);
      }
  }
 
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
@Deprecated
protected NoGitignoreIterator(WorkingTreeIterator p, File root, FS fs) {
    super(p, root, fs);
}
 
Example #10
Source File: ResolveMerger.java    From onedev with MIT License 2 votes vote down vote up
/**
 * Sets the WorkingTreeIterator to be used by this merger. If no
 * WorkingTreeIterator is set this merger will ignore the working tree and
 * fail if a content merge is necessary.
 * <p>
 * TODO: enhance WorkingTreeIterator to support write operations. Then this
 * merger will be able to merge with a different working tree abstraction.
 *
 * @param workingTreeIterator
 *            the workingTreeIt to set
 */
public void setWorkingTreeIterator(WorkingTreeIterator workingTreeIterator) {
	this.workingTreeIterator = workingTreeIterator;
}
 
Example #11
Source File: CustomAddCommand.java    From VoxelGamesLibv2 with MIT License 2 votes vote down vote up
/**
 * Allow clients to provide their own implementation of a FileTreeIterator
 *
 * @param f f
 * @return {@code this}
 */
@Nonnull
public CustomAddCommand setWorkingTreeIterator(@Nonnull WorkingTreeIterator f) {
    workingTreeIterator = f;
    return this;
}