org.eclipse.jgit.treewalk.AbstractTreeIterator Java Examples

The following examples show how to use org.eclipse.jgit.treewalk.AbstractTreeIterator. 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: DiffCalculator.java    From diff-check with GNU Lesser General Public License v2.1 6 votes vote down vote up
private Map<String, BlobWrapper> getContentMapByTreeAndFilter(
        Git git, AbstractTreeIterator tree, TreeFilter filter) throws Exception {
    Map<String, BlobWrapper> contentMap = new LinkedHashMap<>();
    try (TreeWalk treeWalk = new TreeWalk(git.getRepository())) {
        treeWalk.addTree(tree);
        treeWalk.setRecursive(true);
        treeWalk.setFilter(filter);
        while (treeWalk.next()) {
            ObjectId objectId = treeWalk.getObjectId(0);
            ObjectLoader loader = git.getRepository().open(objectId);
            BlobWrapper blobWrapper = BlobWrapper.builder()
                    .blobId(objectId)
                    .content(loader.getBytes())
                    .build();
            contentMap.put(treeWalk.getPathString(), blobWrapper);
        }
    }
    return contentMap;
}
 
Example #2
Source File: SubtreeMerger.java    From git-merge-repos with Apache License 2.0 6 votes vote down vote up
private AbstractTreeIterator getSingleTreeIterator(TreeWalk treeWalk, String commitMessage) {
	AbstractTreeIterator result = null;
	int treeCount = treeWalk.getTreeCount();
	for (int i = 0; i < treeCount; i++) {
		AbstractTreeIterator it = treeWalk.getTree(i, AbstractTreeIterator.class);
		if (it != null) {
			if (result != null) {
				String msg = "Trees of repositories overlap in path '"
						+ it.getEntryPathString()
						+ "'. "
						+ "We can only merge non-overlapping trees, "
						+ "so make sure the repositories have been prepared for that. "
						+ "One possible way is to process each repository to move the root to a subdirectory first.\n"
						+ "Current commit:\n" + commitMessage;
				throw new IllegalStateException(msg);
			} else {
				result = it;
			}
		}
	}
	return result;
}
 
Example #3
Source File: SubtreeMerger.java    From git-merge-repos with Apache License 2.0 6 votes vote down vote up
private DirCache createTreeDirCache(Map<SubtreeConfig, RevCommit> parentCommits,
		String commitMessage) throws IOException {

	try (TreeWalk treeWalk = new TreeWalk(repository)) {
		treeWalk.setRecursive(true);
		addTrees(parentCommits, treeWalk);

		DirCacheBuilder builder = DirCache.newInCore().builder();
		while (treeWalk.next()) {
			AbstractTreeIterator iterator = getSingleTreeIterator(treeWalk, commitMessage);
			if (iterator == null) {
				throw new IllegalStateException(
						"Tree walker did not return a single tree (should not happen): "
								+ treeWalk.getPathString());
			}
			byte[] path = Arrays.copyOf(iterator.getEntryPathBuffer(),
					iterator.getEntryPathLength());
			DirCacheEntry entry = new DirCacheEntry(path);
			entry.setFileMode(iterator.getEntryFileMode());
			entry.setObjectId(iterator.getEntryObjectId());
			builder.add(entry);
		}
		builder.finish();
		return builder.getDirCache();
	}
}
 
Example #4
Source File: GitRepoMetaData.java    From GitFx with Apache License 2.0 6 votes vote down vote up
public String getDiffBetweenCommits(int commitIndex) throws IOException,GitAPIException{
    if(commitIndex+1==commitCount)
        return "Nothing to Diff. This is first commit";
    AbstractTreeIterator current = prepareTreeParser(repository,commitSHA.get(commitIndex));
    AbstractTreeIterator parent = prepareTreeParser(repository,commitSHA.get(++commitIndex));
    ObjectReader reader = repository.newObjectReader();
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    // finally get the list of changed files
    Git git = new Git(repository) ;
    List<DiffEntry> diff = git.diff().
            setOldTree(parent).
            setNewTree(current).
            //TODO Set the path filter to filter out the selected file
            //setPathFilter(PathFilter.create("README.md")).
            call();
    for (DiffEntry entry : diff) {
        System.out.println("Entry: " + entry + ", from: " + entry.getOldId() + ", to: " + entry.getNewId());
        DiffFormatter formatter = new DiffFormatter(byteStream) ;
            formatter.setRepository(repository);
            formatter.format(entry);
        }
   // System.out.println(byteStream.toString());
    String diffContent = byteStream.toString();
    return byteStream.toString();
}
 
Example #5
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 #6
Source File: GitManagerImpl.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public String diff(Workspace ws, String path, String oldRef, String newRef) throws IOException, GitAPIException {
    Repository repository = getRepository(ws.getSpaceKey());

    AbstractTreeIterator oldTreeParser = prepareTreeParser(repository, oldRef);
    AbstractTreeIterator newTreeParser = prepareTreeParser(repository, newRef);

    Config config = new Config();
    config.setBoolean("diff", null, "renames", true);
    DiffConfig diffConfig = config.get(DiffConfig.KEY);

    String relativePath = ws.getRelativePath(path).toString();

    try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
         Git git = Git.wrap(repository)) {

        git.diff()
            .setOldTree(oldTreeParser)
            .setNewTree(newTreeParser)
            .setPathFilter(FollowFilter.create(relativePath, diffConfig))
            .setOutputStream(baos)
            .call();

        return baos.toString();
    }
}
 
Example #7
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 #8
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 #9
Source File: ThreeWayMerger.java    From onedev with MIT License 5 votes vote down vote up
/**
 * Create an iterator to walk the merge base.
 *
 * @return an iterator over the caller-specified merge base, or the natural
 *         merge base of the two input commits.
 * @throws java.io.IOException
 */
protected AbstractTreeIterator mergeBase() throws IOException {
	if (baseTree != null) {
		return openTree(baseTree);
	}
	RevCommit baseCommit = (baseCommitId != null) ? walk
			.parseCommit(baseCommitId) : getBaseCommit(sourceCommits[0],
			sourceCommits[1]);
	if (baseCommit == null) {
		baseCommitId = null;
		return new EmptyTreeIterator();
	}
	baseCommitId = baseCommit.toObjectId();
	return openTree(baseCommit.getTree());
}
 
Example #10
Source File: DiffCalculator.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
private List<DiffEntryWrapper> doCalculateCommitDiff(
        RevCommit oldCommit,
        RevCommit newCommit,
        ObjectReader reader,
        Git git,
        File repoDir,
        Set<String> excludedPathSet) throws Exception {

    if (Objects.equals(oldCommit.getId(), newCommit.getId())) {
        return Collections.emptyList();
    }

    if (Objects.equals(oldCommit.getTree().getId(), newCommit.getTree().getId())) {
        return Collections.emptyList();
    }

    RenameDetector detector = new RenameDetector(git.getRepository());
    AbstractTreeIterator oldTree = new CanonicalTreeParser(null, reader, oldCommit.getTree());
    AbstractTreeIterator newTree = new CanonicalTreeParser(null, reader, newCommit.getTree());

    List<DiffEntry> entries = git.diff()
            .setOldTree(oldTree)
            .setNewTree(newTree)
            .call();
    detector.reset();
    detector.addAll(entries);
    entries = detector.compute();

    return entries.stream()
            .filter(entry -> !excludedPathSet.contains(entry.getNewPath()))
            .map(entry -> {
                RawText oldText = newRawText(entry, DiffEntry.Side.OLD, reader);
                RawText newText = newRawText(entry, DiffEntry.Side.NEW, reader);
                return DiffEntryWrapper.builder()
                        .gitDir(repoDir)
                        .diffEntry(entry)
                        .editList(calculateEditList(oldText, newText))
                        .build();
            }).collect(Collectors.toList());
}
 
Example #11
Source File: AppraiseGitReviewClient.java    From git-appraise-eclipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets the diff between two commits.
 */
private List<DiffEntry> calculateCommitDiffs(Git git, RevCommit first, RevCommit last)
    throws IOException, GitAPIException {
  AbstractTreeIterator oldTreeParser = prepareTreeParser(first);
  AbstractTreeIterator newTreeParser = prepareTreeParser(last);
  return git.diff().setOldTree(oldTreeParser).setNewTree(newTreeParser).call();
}
 
Example #12
Source File: AppraiseGitReviewClient.java    From git-appraise-eclipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets the diff between heads on two branches.
 * See
 * https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/ShowBranchDiff.java.
 */
private List<DiffEntry> calculateBranchDiffs(Git git, String targetRef, String reviewRef)
    throws IOException, GitAPIException {
  AbstractTreeIterator oldTreeParser = prepareTreeParser(targetRef);
  AbstractTreeIterator newTreeParser = prepareTreeParser(reviewRef);
  return git.diff().setOldTree(oldTreeParser).setNewTree(newTreeParser).call();
}
 
Example #13
Source File: AppraiseGitReviewClient.java    From git-appraise-eclipse with Eclipse Public License 1.0 5 votes vote down vote up
private AbstractTreeIterator prepareTreeParserHelper(RevWalk walk, RevCommit commit)
    throws IOException, MissingObjectException, IncorrectObjectTypeException {
  RevTree tree = walk.parseTree(commit.getTree().getId());
  CanonicalTreeParser oldTreeParser = new CanonicalTreeParser();
  try (ObjectReader oldReader = repo.newObjectReader()) {
    oldTreeParser.reset(oldReader, tree.getId());
  }
  return oldTreeParser;
}
 
Example #14
Source File: AppraiseGitReviewClient.java    From git-appraise-eclipse with Eclipse Public License 1.0 5 votes vote down vote up
private AbstractTreeIterator prepareTreeParser(RevCommit commit)
    throws IOException, MissingObjectException, IncorrectObjectTypeException {
  // from the commit we can build the tree which allows us to construct the TreeParser
  try (RevWalk walk = new RevWalk(repo)) {
    return prepareTreeParserHelper(walk, commit);
  }
}
 
Example #15
Source File: AppraiseGitReviewClient.java    From git-appraise-eclipse with Eclipse Public License 1.0 5 votes vote down vote up
private AbstractTreeIterator prepareTreeParser(String ref)
    throws IOException, MissingObjectException, IncorrectObjectTypeException {
  // from the commit we can build the tree which allows us to construct the TreeParser
  Ref head = repo.getRef(ref);
  try (RevWalk walk = new RevWalk(repo)) {
    RevCommit commit = walk.parseCommit(head.getObjectId());
    return prepareTreeParserHelper(walk, commit);
  }
}
 
Example #16
Source File: PGA.java    From coming with MIT License 5 votes vote down vote up
private AbstractTreeIterator prepareTreeParser(Repository repository, String objectId) throws IOException {
    // from the commit we can build the tree which allows us to construct the TreeParser
    //noinspection Duplicates
    RevWalk walk = new RevWalk(repository);
    RevCommit commit = walk.parseCommit(repository.resolve(objectId));
    RevTree tree = walk.parseTree(commit.getTree().getId());

    CanonicalTreeParser treeParser = new CanonicalTreeParser();
    ObjectReader reader = repository.newObjectReader();
    treeParser.reset(reader, tree.getId());

    walk.dispose();

    return treeParser;
}
 
Example #17
Source File: CommitUtil.java    From SZZUnleashed with MIT License 5 votes vote down vote up
/**
 * Returns a revision tree parser wich could be used to compare revisions and extract revision
 * files.
 *
 * @param commitId a unique ID for a commit in the repository.
 * @return a tree iterator that could iterate through the revision tree.
 */
private AbstractTreeIterator getCanonicalTreeParser(ObjectId commitId) throws IOException {
  try (RevWalk walk = new RevWalk(this.git.getRepository())) {
    RevCommit commit = walk.parseCommit(commitId);
    ObjectId treeId = commit.getTree().getId();
    try (ObjectReader reader = git.getRepository().newObjectReader()) {
      return new CanonicalTreeParser(null, reader, treeId);
    }
  }
}
 
Example #18
Source File: GitRepoMetaData.java    From GitFx with Apache License 2.0 5 votes vote down vote up
private static AbstractTreeIterator prepareTreeParser(Repository repository, String objectId) throws IOException,
        MissingObjectException,
        IncorrectObjectTypeException {
    RevWalk walk = new RevWalk(repository) ;
    RevCommit commit = walk.parseCommit(ObjectId.fromString(objectId));
    RevTree tree = walk.parseTree(commit.getTree().getId());
    CanonicalTreeParser oldTreeParser = new CanonicalTreeParser();
    ObjectReader oldReader = repository.newObjectReader();
    oldTreeParser.reset(oldReader, tree.getId());
    walk.dispose();
    return oldTreeParser;
}
 
Example #19
Source File: GitDiffHandlerV1.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
private AbstractTreeIterator getTreeIterator(Repository db, String name) throws IOException {
	final ObjectId id = db.resolve(name);
	if (id == null)
		throw new IllegalArgumentException(name);
	final CanonicalTreeParser p = new CanonicalTreeParser();
	final ObjectReader or = db.newObjectReader();
	try {
		p.reset(or, new RevWalk(db).parseTree(id));
		return p;
	} finally {
		or.close();
	}
}
 
Example #20
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 #21
Source File: StrategySimpleTwoWayInCore.java    From onedev with MIT License 4 votes vote down vote up
private AbstractTreeIterator getTree(int tree) {
	return tw.getTree(tree, AbstractTreeIterator.class);
}
 
Example #22
Source File: ResolveMerger.java    From onedev with MIT License 4 votes vote down vote up
/**
 * The resolve conflict way of three way merging
 *
 * @param baseTree
 *            a {@link org.eclipse.jgit.treewalk.AbstractTreeIterator}
 *            object.
 * @param headTree
 *            a {@link org.eclipse.jgit.revwalk.RevTree} object.
 * @param mergeTree
 *            a {@link org.eclipse.jgit.revwalk.RevTree} object.
 * @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 org.eclipse.jgit.merge.RecursiveMerger}
 *            where when determining merge bases we don't want to deal with
 *            content-merge conflicts.
 * @return whether the trees merged cleanly
 * @throws java.io.IOException
 * @since 3.5
 */
protected boolean mergeTrees(AbstractTreeIterator baseTree,
		RevTree headTree, RevTree mergeTree, boolean ignoreConflicts)
		throws IOException {

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

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

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

	if (!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 (!builder.commit()) {
			cleanUp();
			throw new IndexWriteException();
		}
		builder = null;

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

	if (getUnmergedPaths().isEmpty() && !failed()) {
		resultTree = dircache.writeTree(getObjectInserter());
		return true;
	}
	resultTree = null;
	return false;
}
 
Example #23
Source File: GfsTreeIterator.java    From ParallelGit with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public AbstractTreeIterator createSubtreeIterator(ObjectReader reader) throws IOException {
  GfsTreeEntry entry = currentEntry();
  return new GfsTreeIterator(entry.listChildren(), this);
}
 
Example #24
Source File: Index.java    From git-code-format-maven-plugin with MIT License 4 votes vote down vote up
public AbstractTreeIterator treeIterator() {
  return new DirCacheIterator(dirCache);
}
 
Example #25
Source File: GitStagedFiles.java    From git-code-format-maven-plugin with MIT License 4 votes vote down vote up
private AbstractTreeIterator treeIterator(DirCache dirCache) {
  return new DirCacheIterator(dirCache);
}
 
Example #26
Source File: GitMigrator.java    From phoebus with Eclipse Public License 1.0 4 votes vote down vote up
private void createSnapshots(Node saveSetNode, String relativeSnpFilePath){
    try {
        List<RevCommit> commits = findCommitsFor(relativeSnpFilePath);
        Map<String, RevTag> tags = loadTagsForRevisions(commits);
        for(RevCommit commit : commits){
            try (ObjectReader objectReader = git.getRepository().newObjectReader(); TreeWalk treeWalk = new TreeWalk(objectReader)) {
                CanonicalTreeParser treeParser = new CanonicalTreeParser();
                treeParser.reset(objectReader, commit.getTree());
                int treeIndex = treeWalk.addTree(treeParser);
                treeWalk.setFilter(PathFilter.create(relativeSnpFilePath));
                treeWalk.setRecursive(true);
                if (treeWalk.next()) {
                    AbstractTreeIterator iterator = treeWalk.getTree(treeIndex, AbstractTreeIterator.class);
                    ObjectId objectId = iterator.getEntryObjectId();
                    ObjectLoader objectLoader = objectReader.open(objectId);
                    RevTag tag = tags.get(commit.getName());
                    try (InputStream stream = objectLoader.openStream()) {
                        List<SnapshotItem> snapshotItems = FileReaderHelper.readSnapshot(stream);
                        if(tag != null){
                            System.out.println();
                        }
                        if(!isSnapshotCompatibleWithSaveSet(saveSetNode, snapshotItems)){
                            continue;
                        }
                        snapshotItems = setConfigPvIds(saveSetNode, snapshotItems);
                        Date commitTime = new Date(commit.getCommitTime() * 1000L);
                        Node snapshotNode = saveAndRestoreService.saveSnapshot(saveSetNode,
                                snapshotItems,
                                commitTime.toString(),
                                commit.getFullMessage());

                        snapshotNode = saveAndRestoreService.getNode(snapshotNode.getUniqueId());
                        Map<String, String> properties = snapshotNode.getProperties();
                        if(properties == null){
                            properties = new HashMap<>();
                        }
                        if(tag != null){
                            properties.put("golden", "true");
                            snapshotNode.setProperties(properties);
                        }
                        snapshotNode.setUserName(commit.getCommitterIdent().getName());
                        saveAndRestoreService.updateNode(snapshotNode);
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #27
Source File: GitCommit.java    From compiler with Apache License 2.0 4 votes vote down vote up
private void updateChangedFiles(final RevCommit parent, final int parentIndex, final RevCommit child) {
	final DiffFormatter df = new DiffFormatter(NullOutputStream.INSTANCE);
	df.setRepository(repository);
	df.setDiffComparator(RawTextComparator.DEFAULT);
	df.setDetectRenames(true);

	try {
		final AbstractTreeIterator parentIter = new CanonicalTreeParser(null, repository.newObjectReader(), parent.getTree());
		final AbstractTreeIterator childIter = new CanonicalTreeParser(null, repository.newObjectReader(), child.getTree());
		List<DiffEntry> diffs = df.scan(parentIter, childIter);
		for (final DiffEntry diff : diffs) {
			if (diff.getChangeType() == ChangeType.MODIFY) {
				if (diff.getNewMode().getObjectType() == Constants.OBJ_BLOB) {
					updateChangedFiles(parent, child, diff, ChangeKind.MODIFIED);
				}
			// RENAMED file may have the same/different object id(s) for old and new
			} else if (diff.getChangeType() == ChangeType.RENAME) {
				if (diff.getNewMode().getObjectType() == Constants.OBJ_BLOB) {
					updateChangedFiles(parent, child, diff, ChangeKind.RENAMED);
				}
			} else if (diff.getChangeType() == ChangeType.COPY) {
				if (diff.getNewMode().getObjectType() == Constants.OBJ_BLOB) {
					updateChangedFiles(parent, child, diff, ChangeKind.COPIED);
				}
			// ADDED file should not have old path and its old object id is 0's
			} else if (diff.getChangeType() == ChangeType.ADD) {
				if (diff.getNewMode().getObjectType() == Constants.OBJ_BLOB) {
					updateChangedFiles(parent, child, diff, ChangeKind.ADDED);
				}
			// DELETED file's new object id is 0's and doesn't have new path
			} else if (diff.getChangeType() == ChangeType.DELETE) {
				if (diff.getOldMode().getObjectType() == Constants.OBJ_BLOB) {
					String oldPath = diff.getOldPath();
					String oldObjectId = diff.getOldId().toObjectId().getName();
					ChangedFile.Builder cfb = getChangedFile(oldPath, ChangeKind.DELETED);
					filePathGitObjectIds.put(oldPath, diff.getNewId().toObjectId());
				}
			}
		}
	} catch (final IOException e) {
		if (debug)
			System.err.println("Git Error getting commit diffs: " + e.getMessage());
	}
	df.close();
}
 
Example #28
Source File: GfsTreeIterator.java    From ParallelGit with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public AbstractTreeIterator createSubtreeIterator(ObjectReader reader) throws IOException {
  GfsTreeEntry entry = currentEntry();
  return new GfsTreeIterator(entry.listChildren(), this);
}
 
Example #29
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 #30
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;
}