org.eclipse.jgit.treewalk.CanonicalTreeParser Java Examples

The following examples show how to use org.eclipse.jgit.treewalk.CanonicalTreeParser. 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: 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 #2
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 #3
Source File: JGitDiscoveryTest.java    From multi-module-maven-release-plugin with MIT License 6 votes vote down vote up
@Test public void name() throws IOException, GitAPIException {
    ObjectId head = repo.resolve("HEAD^{tree}");
    ObjectId oldHead = repo.resolve("HEAD^^{tree}");


    ObjectReader reader = repo.newObjectReader();

    CanonicalTreeParser prevParser = new CanonicalTreeParser();
    prevParser.reset(reader, oldHead);

    CanonicalTreeParser headParser = new CanonicalTreeParser();
    headParser.reset(reader, head);

    List<DiffEntry> diffs = new Git(repo).diff()
            .setNewTree(headParser)
            .setOldTree(prevParser)
            .call();

    for (DiffEntry entry : diffs)
        System.out.println(entry);
}
 
Example #4
Source File: LayoutHelper.java    From git-as-svn with GNU General Public License v2.0 6 votes vote down vote up
@Nullable
static RevCommit loadOriginalCommit(@NotNull ObjectReader reader, @Nullable ObjectId cacheCommit) throws IOException {
  final RevWalk revWalk = new RevWalk(reader);
  if (cacheCommit != null) {
    final RevCommit revCommit = revWalk.parseCommit(cacheCommit);
    revWalk.parseTree(revCommit.getTree());

    final CanonicalTreeParser treeParser = new CanonicalTreeParser(GitRepository.emptyBytes, reader, revCommit.getTree());
    while (!treeParser.eof()) {
      if (treeParser.getEntryPathString().equals(ENTRY_COMMIT_REF)) {
        return revWalk.parseCommit(treeParser.getEntryObjectId());
      }
      treeParser.next();
    }
  }
  return null;
}
 
Example #5
Source File: ResolveMerger.java    From onedev with MIT License 6 votes vote down vote up
/**
 * Does the content merge. The three texts base, ours and theirs are
 * specified with {@link CanonicalTreeParser}. If any of the parsers is
 * specified as <code>null</code> then an empty text will be used instead.
 *
 * @param base
 * @param ours
 * @param theirs
 * @param attributes
 *
 * @return the result of the content merge
 * @throws IOException
 */
private MergeResult<RawText> contentMerge(CanonicalTreeParser base,
		CanonicalTreeParser ours, CanonicalTreeParser theirs,
		Attributes attributes)
		throws IOException {
	RawText baseText;
	RawText ourText;
	RawText theirsText;

	try {
		baseText = base == null ? RawText.EMPTY_TEXT : getRawText(
						base.getEntryObjectId(), attributes);
		ourText = ours == null ? RawText.EMPTY_TEXT : getRawText(
						ours.getEntryObjectId(), attributes);
		theirsText = theirs == null ? RawText.EMPTY_TEXT : getRawText(
						theirs.getEntryObjectId(), attributes);
	} catch (BinaryBlobException e) {
		MergeResult<RawText> r = new MergeResult<>(Collections.<RawText>emptyList());
		r.setContainsConflicts(true);
		return r;
	}
	return (mergeAlgorithm.merge(RawTextComparator.DEFAULT, baseText,
			ourText, theirsText));
}
 
Example #6
Source File: GitRepository.java    From git-as-svn with GNU General Public License v2.0 6 votes vote down vote up
@NotNull
Iterable<GitTreeEntry> loadTree(@Nullable GitTreeEntry tree) throws IOException {
  final GitObject<ObjectId> treeId = getTreeObject(tree);
  // Loading tree.
  if (treeId == null) {
    return Collections.emptyList();
  }
  final List<GitTreeEntry> result = new ArrayList<>();
  final Repository repo = treeId.getRepo();
  final CanonicalTreeParser treeParser = new CanonicalTreeParser(GitRepository.emptyBytes, repo.newObjectReader(), treeId.getObject());
  while (!treeParser.eof()) {
    result.add(new GitTreeEntry(
        treeParser.getEntryFileMode(),
        new GitObject<>(repo, treeParser.getEntryObjectId()),
        treeParser.getEntryPathString()
    ));
    treeParser.next();
  }
  return result;
}
 
Example #7
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 #8
Source File: UpdaterGenerator.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Populate all the files to update, if the system should update.
 */
private void populateDiff() {
    try {
        git.fetch().call();
        Repository repo = git.getRepository();
        ObjectId fetchHead = repo.resolve("FETCH_HEAD^{tree}");
        ObjectId head = repo.resolve("HEAD^{tree}");
        
        ObjectReader reader = repo.newObjectReader();
        CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
        oldTreeIter.reset(reader, head);
        CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
        newTreeIter.reset(reader, fetchHead);
        List<DiffEntry> diffs = git.diff().setShowNameAndStatusOnly(true)
                .setNewTree(newTreeIter)
                .setOldTree(oldTreeIter)
                .call();
        
        pluginsToUpdate = new ArrayList<PluginToUpdate>();
        
        checkDiffEmpty(diffs);
        
    } catch (GitAPIException | IOException ex) {
        Logger.getLogger(UpdaterGenerator.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example #9
Source File: SMAGit.java    From salesforce-migration-assistant with MIT License 5 votes vote down vote up
/**
 * Returns the diff between two commits.
 *
 * @return List that contains DiffEntry objects of the changes made between the previous and current commits.
 * @throws Exception
 */
private void getDiffs() throws Exception
{
    OutputStream out = new ByteArrayOutputStream();
    CanonicalTreeParser oldTree = getTree(prevCommit);
    CanonicalTreeParser newTree = getTree(curCommit);
    DiffCommand diff = git.diff().setOutputStream(out).setOldTree(oldTree).setNewTree(newTree);
    diffs = diff.call();
}
 
Example #10
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 #11
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 #12
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 #13
Source File: UpdaterGenerator.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Populate all the files to update, if the system should update.
 */
private boolean populateDiff() {
    try {
        git.fetch().call();
        Repository repo = git.getRepository();
        ObjectId fetchHead = repo.resolve("FETCH_HEAD^{tree}");
        ObjectId head = repo.resolve("HEAD^{tree}");
        
        ObjectReader reader = repo.newObjectReader();
        CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
        oldTreeIter.reset(reader, head);
        CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
        newTreeIter.reset(reader, fetchHead);
        List<DiffEntry> diffs = git.diff().setShowNameAndStatusOnly(true)
                .setNewTree(newTreeIter)
                .setOldTree(oldTreeIter)
                .call();
        
        if (diffs.isEmpty()) {
            System.out.println("No diff");
            return false;
        }else{
            return true;
        }
    } catch (GitAPIException | IOException ex) {
        Logger.getLogger(UpdaterGenerator.class.getName()).log(Level.SEVERE, null, ex);
    }return true;//assume true
}
 
Example #14
Source File: GitMonitoringService.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @throws GitAPIException
 * @throws IOException
 */
List<DiffEntry> getChanges() throws GitAPIException, IOException {
  // get tree for last processed commit
  ObjectId oldHeadTree = git.getRepository().resolve(this.lastProcessedGitHash + "^{tree}");

  // refresh to latest and reset hard to handle forced pushes
  this.git.fetch()
      .setRemote(REMOTE_NAME)
      .setCredentialsProvider(getCredentialsProvider())
      .setTransportConfigCallback(buildTransportConfigCallback())
      .call();
  // reset hard to get a clean working set since pull --rebase may leave files around
  this.git.reset().setMode(ResetCommand.ResetType.HARD).setRef(REMOTE_NAME + "/" + this.branchName).call();

  ObjectId head = this.git.getRepository().resolve("HEAD");
  ObjectId headTree = this.git.getRepository().resolve("HEAD^{tree}");

  // remember the hash for the current HEAD. This will be checkpointed after the diff is processed.
  latestGitHash = head.getName();

  // diff old and new heads to find changes
  ObjectReader reader = this.git.getRepository().newObjectReader();
  CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
  oldTreeIter.reset(reader, oldHeadTree);
  CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
  newTreeIter.reset(reader, headTree);

  return this.git.diff()
      .setNewTree(newTreeIter)
      .setOldTree(oldTreeIter)
      .setShowNameAndStatusOnly(true)
      .call();
}
 
Example #15
Source File: DiffCalculator.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Map<String, BlobWrapper> getRevFileContentMap(
        Git git, RevCommit commit, Set<String> filePathSet, ObjectReader reader) throws Exception {
    if (filePathSet == null || filePathSet.isEmpty()) {
        return Collections.emptyMap();
    }
    TreeFilter filter = filePathSet.size() > 1
            ? OrTreeFilter.create(filePathSet.stream()
                    .map(PathFilter::create)
                    .collect(Collectors.toList()))
            : PathFilter.create(filePathSet.iterator().next());
     return getContentMapByTreeAndFilter(git, new CanonicalTreeParser(null, reader, commit.getTree()), filter);
}
 
Example #16
Source File: SMAGit.java    From salesforce-migration-assistant with MIT License 5 votes vote down vote up
/**
 * Returns the Canonical Tree Parser representation of a commit.
 *
 * @param commit Commit in the repository.
 * @return CanonicalTreeParser representing the tree for the commit.
 * @throws IOException
 */
private CanonicalTreeParser getTree(String commit) throws IOException
{
    CanonicalTreeParser tree = new CanonicalTreeParser();
    ObjectReader reader = repository.newObjectReader();
    ObjectId head = repository.resolve(commit + "^{tree}");
    tree.reset(reader, head);
    return tree;
}
 
Example #17
Source File: ConfigRepository.java    From gocd with Apache License 2.0 5 votes vote down vote up
private byte[] contentFromTree(RevTree tree) {
    try (final ObjectReader reader = gitRepo.newObjectReader()) {
        CanonicalTreeParser parser = new CanonicalTreeParser();
        parser.reset(reader, tree);

        String lastPath = null;
        while (true) {
            final String path = parser.getEntryPathString();
            parser = parser.next();
            if (path.equals(lastPath)) {
                break;
            }

            lastPath = path;

            if (path.equals(CRUISE_CONFIG_XML)) {
                final ObjectId id = parser.getEntryObjectId();
                final ObjectLoader loader = reader.open(id);
                return loader.getBytes();
            }
        }
        return null;
    } catch (IOException e) {
        LOGGER.error("Could not fetch content from the config repository found at path '{}'", workingDir.getAbsolutePath(), e);
        throw new RuntimeException("Error while fetching content from the config repository.", e);
    }
}
 
Example #18
Source File: SubtreeMerger.java    From git-merge-repos with Apache License 2.0 5 votes vote down vote up
private void addTrees(Map<SubtreeConfig, RevCommit> parentCommits, TreeWalk treeWalk)
		throws IOException {
	for (Map.Entry<SubtreeConfig, RevCommit> entry : parentCommits.entrySet()) {
		String directory = entry.getKey().getSubtreeDirectory();
		RevCommit parentCommit = entry.getValue();
		if (".".equals(directory)) {
			treeWalk.addTree(parentCommit.getTree());
		} else {
			byte[] prefix = directory.getBytes(RawParseUtils.UTF8_CHARSET);
			CanonicalTreeParser treeParser = new CanonicalTreeParser(prefix,
					treeWalk.getObjectReader(), parentCommit.getTree());
			treeWalk.addTree(treeParser);
		}
	}
}
 
Example #19
Source File: CurioGenericCiPlugin.java    From curiostack with MIT License 5 votes vote down vote up
private static Set<String> computeAffectedFilesForMaster(Git git, Project rootProject)
    throws IOException {
  ObjectId oldTreeId = git.getRepository().resolve("HEAD^{tree}");
  ObjectId newTreeId = git.getRepository().resolve("HEAD^^{tree}");

  final CanonicalTreeParser oldTreeParser;
  final CanonicalTreeParser newTreeParser;
  try (ObjectReader reader = git.getRepository().newObjectReader()) {
    oldTreeParser = parser(reader, oldTreeId);
    newTreeParser = parser(reader, newTreeId);
  }

  return computeAffectedFiles(git, oldTreeParser, newTreeParser, rootProject);
}
 
Example #20
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 #21
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 #22
Source File: ResolveMerger.java    From onedev with MIT License 5 votes vote down vote up
/**
 * adds a new path with the specified stage to the index builder
 *
 * @param path
 * @param p
 * @param stage
 * @param lastMod
 * @param len
 * @return the entry which was added to the index
 */
private DirCacheEntry add(byte[] path, CanonicalTreeParser p, int stage,
		Instant lastMod, long len) {
	if (p != null && !p.getEntryFileMode().equals(FileMode.TREE)) {
		DirCacheEntry e = new DirCacheEntry(path, stage);
		e.setFileMode(p.getEntryFileMode());
		e.setObjectId(p.getEntryObjectId());
		e.setLastModified(lastMod);
		e.setLength(len);
		builder.add(e);
		return e;
	}
	return null;
}
 
Example #23
Source File: GitUtils.java    From onedev with MIT License 5 votes vote down vote up
public static List<DiffEntry> diff(Repository repository, AnyObjectId oldRevId, AnyObjectId newRevId) {
	List<DiffEntry> diffs = new ArrayList<>();
	try (	DiffFormatter diffFormatter = new DiffFormatter(NullOutputStream.INSTANCE);
			RevWalk revWalk = new RevWalk(repository);
			ObjectReader reader = repository.newObjectReader();) {
    	diffFormatter.setRepository(repository);
    	diffFormatter.setDetectRenames(true);
    	diffFormatter.setDiffComparator(RawTextComparator.DEFAULT);
    	
    	CanonicalTreeParser oldTreeParser = new CanonicalTreeParser();
    	if (!oldRevId.equals(ObjectId.zeroId()))
    		oldTreeParser.reset(reader, revWalk.parseCommit(oldRevId).getTree());
    	
    	CanonicalTreeParser newTreeParser = new CanonicalTreeParser();
    	if (!newRevId.equals(ObjectId.zeroId()))
    		newTreeParser.reset(reader, revWalk.parseCommit(newRevId).getTree());
    	
    	for (DiffEntry entry: diffFormatter.scan(oldTreeParser, newTreeParser)) {
    		if (!Objects.equal(entry.getOldPath(), entry.getNewPath())
    				|| !Objects.equal(entry.getOldMode(), entry.getNewMode())
    				|| entry.getOldId()==null || !entry.getOldId().isComplete()
    				|| entry.getNewId()== null || !entry.getNewId().isComplete()
    				|| !entry.getOldId().equals(entry.getNewId())) {
    			diffs.add(entry);
    		}
    	}
	} catch (IOException e) {
		throw new RuntimeException(e);
	}			
	return diffs;
}
 
Example #24
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 #25
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 #26
Source File: GitRepository.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private Map<String, Change<?>> blockingPreviewDiff(Revision baseRevision, Iterable<Change<?>> changes) {
    requireNonNull(baseRevision, "baseRevision");
    requireNonNull(changes, "changes");
    baseRevision = normalizeNow(baseRevision);

    readLock();
    try (ObjectReader reader = jGitRepository.newObjectReader();
         RevWalk revWalk = newRevWalk(reader);
         DiffFormatter diffFormatter = new DiffFormatter(null)) {

        final ObjectId baseTreeId = toTree(revWalk, baseRevision);
        final DirCache dirCache = DirCache.newInCore();
        final int numEdits = applyChanges(baseRevision, baseTreeId, dirCache, changes);
        if (numEdits == 0) {
            return Collections.emptyMap();
        }

        final CanonicalTreeParser p = new CanonicalTreeParser();
        p.reset(reader, baseTreeId);
        diffFormatter.setRepository(jGitRepository);
        final List<DiffEntry> result = diffFormatter.scan(p, new DirCacheIterator(dirCache));
        return toChangeMap(result);
    } catch (IOException e) {
        throw new StorageException("failed to perform a dry-run diff", e);
    } finally {
        readUnlock();
    }
}
 
Example #27
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 #28
Source File: CurioGenericCiPlugin.java    From curiostack with MIT License 5 votes vote down vote up
private static Set<String> computeAffectedFilesForBranch(
    Git git, String branch, Project rootProject) throws IOException {
  String masterRemote =
      git.getRepository().getRemoteNames().contains("upstream") ? "upstream" : "origin";
  CanonicalTreeParser oldTreeParser =
      parserForBranch(
          git, git.getRepository().exactRef("refs/remotes/" + masterRemote + "/master"));
  CanonicalTreeParser newTreeParser =
      parserForBranch(git, git.getRepository().exactRef(Constants.HEAD));
  return computeAffectedFiles(git, oldTreeParser, newTreeParser, rootProject);
}
 
Example #29
Source File: CurioGenericCiPlugin.java    From curiostack with MIT License 5 votes vote down vote up
private static CanonicalTreeParser parserForBranch(Git git, Ref branch) throws IOException {
  try (RevWalk walk = new RevWalk(git.getRepository())) {
    RevCommit commit = walk.parseCommit(branch.getObjectId());
    RevTree tree = walk.parseTree(commit.getTree().getId());

    final CanonicalTreeParser parser;
    try (ObjectReader reader = git.getRepository().newObjectReader()) {
      parser = parser(reader, tree.getId());
    }

    walk.dispose();

    return parser;
  }
}
 
Example #30
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();
    }
}