Java Code Examples for org.eclipse.jgit.revwalk.RevTree

The following examples show how to use org.eclipse.jgit.revwalk.RevTree. These examples are extracted from open source projects. 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 Project: hop   Source File: UIGit.java    License: 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 Project: SZZUnleashed   Source File: CommitUtil.java    License: MIT License 6 votes vote down vote up
/**
 * Method to read a file from a specific revision.
 *
 * @param tree the revision tree that contains the file.
 * @param path the path that leads to the file in the tree.
 * @return a list containing all lines in the file.
 */
public List<String> getFileLines(RevTree tree, String path) throws IOException, GitAPIException {

  try (TreeWalk walk = new TreeWalk(this.repo)) {
    walk.addTree(tree);
    walk.setRecursive(true);
    walk.setFilter(PathFilter.create(path));

    walk.next();
    ObjectId oId = walk.getObjectId(0);

    if (oId == ObjectId.zeroId()) {
      return new LinkedList<>();
    }

    ObjectLoader loader = this.repo.open(oId);

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    loader.copyTo(stream);

    return IOUtils.readLines(new ByteArrayInputStream(stream.toByteArray()), "UTF-8");
  } catch (Exception e) {
    return new LinkedList<>();
  }
}
 
Example 3
Source Project: Getaviz   Source File: GitCommit.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, VersionedFile> getFiles(Iterable<String> filters) throws FilesNotAvailableException {
	Map<String, VersionedFile> returnable = new HashMap<String, VersionedFile>();
	IterablePatternMatcher matcher = new IterablePatternMatcher();
	Iterable<Pattern> patterns = matcher.transformToPattern(filters);
	try {
		RevTree tree = commit.getTree();
		TreeWalk treeWalk = new TreeWalk(repository);
		treeWalk.addTree(tree);
		treeWalk.setRecursive(true);
		while (treeWalk.next()) {
			String currentFilePath = treeWalk.getPathString();
			if (matcher.isIncluded(patterns, currentFilePath)) {
				returnable.put(currentFilePath, readToByteArray(treeWalk));
			}
		}
	} catch (IOException e) {
		throw new FilesNotAvailableException(e);
	}
	return returnable;
}
 
Example 4
Source Project: onedev   Source File: BlobEditsTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testRemoveFile() throws IOException {
	createDir("client");
	addFileAndCommit("client/a.java", "a", "add a");
	addFileAndCommit("client/b.java", "b", "add b");
	
	createDir("server/src/com/example/a");
	createDir("server/src/com/example/b");
	addFileAndCommit("server/src/com/example/a/a.java", "a", "add a");
	addFileAndCommit("server/src/com/example/b/b.java", "b", "add b");
	
	String refName = "refs/heads/master";
	ObjectId oldCommitId = git.getRepository().resolve(refName);
	
	BlobEdits edits = new BlobEdits(Sets.newHashSet("/server/src/com/example/a//a.java"), Maps.newHashMap());
	ObjectId newCommitId = edits.commit(git.getRepository(), refName, oldCommitId, oldCommitId, user, "test delete");
	
	try (RevWalk revWalk = new RevWalk(git.getRepository())) {
		RevTree revTree = revWalk.parseCommit(newCommitId).getTree();
		assertNull(TreeWalk.forPath(git.getRepository(), "server/src/com/example/a", revTree));
		assertNotNull(TreeWalk.forPath(git.getRepository(), "server/src/com/example/b/b.java", revTree));
		assertNotNull(TreeWalk.forPath(git.getRepository(), "client/a.java", revTree));
		assertNotNull(TreeWalk.forPath(git.getRepository(), "client/b.java", revTree));
	}
}
 
Example 5
Source Project: onedev   Source File: BlobEditsTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldFailIfOldPathIsTreeWhenRename() throws IOException {
	createDir("client");
	addFileAndCommit("client/a.java", "a", "add a");
	addFileAndCommit("client/b.java", "b", "add b");
	
	createDir("server/src/com/example/a");
	createDir("server/src/com/example/b");
	addFileAndCommit("server/src/com/example/a/a.java", "a", "add a");
	addFileAndCommit("server/src/com/example/b/b.java", "b", "add b");
	
	String refName = "refs/heads/master";
	ObjectId oldCommitId = git.getRepository().resolve(refName);
	
	Map<String, BlobContent> newBlobs = new HashMap<>();
	newBlobs.put("client/c.java", new BlobContent.Immutable("a".getBytes(), FileMode.REGULAR_FILE));
	BlobEdits edits = new BlobEdits(Sets.newHashSet("server/src/com/example/a"), newBlobs);
	ObjectId newCommitId = edits.commit(git.getRepository(), refName, oldCommitId, oldCommitId, user, 
			"test rename");
	try (RevWalk revWalk = new RevWalk(git.getRepository())) {
		RevTree revTree = revWalk.parseCommit(newCommitId).getTree();
		assertNotNull(TreeWalk.forPath(git.getRepository(), "client/c.java", revTree));
		assertNull(TreeWalk.forPath(git.getRepository(), "server/src/com/example/a", revTree));
	}
}
 
Example 6
Source Project: blueocean-plugin   Source File: GitUtils.java    License: MIT License 6 votes vote down vote up
@SuppressFBWarnings(value={"RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE"}, justification="JDK11 produces different bytecode - https://github.com/spotbugs/spotbugs/issues/756")
static byte[] readFile(Repository repository, String ref, String filePath) {
    try (ObjectReader reader = repository.newObjectReader()) {
        ObjectId branchRef = repository.resolve(ref); // repository.exactRef(ref);
        if (branchRef != null) { // for empty repositories, branchRef may be null
            RevWalk revWalk = new RevWalk(repository);
            RevCommit commit = revWalk.parseCommit(branchRef);
            // and using commit's tree find the path
            RevTree tree = commit.getTree();
            TreeWalk treewalk = TreeWalk.forPath(reader, filePath, tree);
            if (treewalk != null) {
                // use the blob id to read the file's data
                return reader.open(treewalk.getObjectId(0)).getBytes();
            }
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    return null;
}
 
Example 7
Source Project: piper   Source File: JGitTemplate.java    License: Apache License 2.0 6 votes vote down vote up
private List<IdentifiableResource> getHeadFiles (Repository aRepository, String... aSearchPaths) {
  List<String> searchPaths = Arrays.asList(aSearchPaths);
  List<IdentifiableResource> resources = new ArrayList<>();
  try (ObjectReader reader = aRepository.newObjectReader(); RevWalk walk = new RevWalk(reader); TreeWalk treeWalk = new TreeWalk(aRepository,reader);) {
    final ObjectId id = aRepository.resolve(Constants.HEAD);
    if(id == null) {
      return List.of();
    }
    RevCommit commit = walk.parseCommit(id);
    RevTree tree = commit.getTree();
    treeWalk.addTree(tree);
    treeWalk.setRecursive(true);
    while (treeWalk.next()) {
      String path = treeWalk.getPathString();        
      if(!path.startsWith(".") && (searchPaths == null || searchPaths.size() == 0 || searchPaths.stream().anyMatch((sp)->path.startsWith(sp)))) {
        ObjectId objectId = treeWalk.getObjectId(0);
        logger.debug("Loading {} [{}]",path,objectId.name());
        resources.add(readBlob(aRepository, path.substring(0, path.indexOf('.')), objectId.name()));
      }
    }
    return resources;
  }
  catch (Exception e) {
    throw Throwables.propagate(e);
  } 
}
 
Example 8
Source Project: mdw   Source File: VersionControlGit.java    License: Apache License 2.0 6 votes vote down vote up
public byte[] readFromCommit(String commitId, String path) throws Exception {
    try (RevWalk revWalk = new RevWalk(localRepo)) {
        RevCommit commit = revWalk.parseCommit(ObjectId.fromString(commitId));
        // use commit's tree to find the path
        RevTree tree = commit.getTree();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (TreeWalk treeWalk = new TreeWalk(localRepo)) {
            treeWalk.addTree(tree);
            treeWalk.setRecursive(true);
            treeWalk.setFilter(PathFilter.create(path));
            if (!treeWalk.next()) {
                return null;
            }

            ObjectId objectId = treeWalk.getObjectId(0);
            ObjectLoader loader = localRepo.open(objectId);

            loader.copyTo(baos);
        }
        revWalk.dispose();
        return baos.toByteArray();
    }
}
 
Example 9
Source Project: mdw   Source File: VersionControlGit.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Find package assets that are present at the specified commit.
 */
public List<String> getAssetsAtCommit(String commitId, String packagePath) throws Exception {
    try (RevWalk revWalk = new RevWalk(localRepo)) {
        RevCommit commit = revWalk.parseCommit(ObjectId.fromString(commitId));
        // use commit's tree to find the path
        RevTree tree = commit.getTree();
        try (TreeWalk treeWalk = new TreeWalk(localRepo)) {
            treeWalk.addTree(tree);
            treeWalk.setRecursive(true);
            treeWalk.setFilter(PathFilter.create(packagePath));
            List<String> assets = new ArrayList<>();
            while (treeWalk.next()) {
                if (treeWalk.getPathString().equals(packagePath + "/" + treeWalk.getNameString())) {
                    // direct member of package
                    assets.add(treeWalk.getNameString());
                }
            }
            return assets;
        }
        finally {
            revWalk.dispose();
        }
    }
}
 
Example 10
Source Project: coming   Source File: RepositoryPGit.java    License: 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 11
Source Project: coming   Source File: PGA.java    License: MIT License 6 votes vote down vote up
private void obtainDiff(Repository repository, RevCommit commit, List<String> paths) throws IOException, GitAPIException {
        // and using commit's tree find the path
        RevTree tree = commit.getTree();
        System.out.println("Having tree: " + tree);

        // now try to find a specific file
        TreeWalk treeWalk = new TreeWalk(repository);
        treeWalk.addTree(tree);
        treeWalk.setRecursive(true);
        for (String path : paths) {
            String filePath = SIVA_COMMITS_DIR + commit.getName() + "/" + path;
            File file = new File(filePath);
            if (!file.exists()) {
                treeWalk.setFilter(PathFilter.create(path));
                if (!treeWalk.next()) {
                    throw new IllegalStateException("Did not find expected file '" + path + "'");
                }

                ObjectId objectId = treeWalk.getObjectId(0);
                ObjectLoader loader = repository.open(objectId);
                // and then one can the loader to read the file
//                loader.copyTo(System.out);
                loader.copyTo(FileUtils.openOutputStream(file));
            }
        }
    }
 
Example 12
Source Project: studio   Source File: GitContentRepository.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public long getContentSize(final String site, final String path) {
    Repository repo = helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX);
    try {
        RevTree tree = helper.getTreeForLastCommit(repo);
        try (TreeWalk tw = TreeWalk.forPath(repo, helper.getGitPath(path), tree)) {
            if (tw != null && tw.getObjectId(0) != null) {
                ObjectId id = tw.getObjectId(0);
                ObjectLoader objectLoader = repo.open(id);
                return objectLoader.getSize();
            }
        }
    } catch (IOException e) {
        logger.error("Error while getting content for file at site: " + site + " path: " + path, e);
    }
    return -1L;
}
 
Example 13
Source Project: git-client-plugin   Source File: JGitAPIImpl.java    License: MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public List<IndexEntry> getSubmodules(String treeIsh) throws GitException {
    try (Repository repo = getRepository();
         ObjectReader or = repo.newObjectReader();
         RevWalk w = new RevWalk(or)) {
        List<IndexEntry> r = new ArrayList<>();

        RevTree t = w.parseTree(repo.resolve(treeIsh));
        SubmoduleWalk walk = new SubmoduleWalk(repo);
        walk.setTree(t);
        walk.setRootTree(t);
        while (walk.next()) {
            r.add(new IndexEntry(walk));
        }

        return r;
    } catch (IOException e) {
        throw new GitException(e);
    }
}
 
Example 14
Source Project: onedev   Source File: Merger.java    License: MIT License 5 votes vote down vote up
/**
 * Merge together two or more tree-ish objects.
 * <p>
 * Any tree-ish may be supplied as inputs. Commits and/or tags pointing at
 * trees or commits may be passed as input objects.
 *
 * @since 3.5
 * @param flush
 *            whether to flush and close the underlying object inserter when
 *            finished to store any content-merged blobs and virtual merged
 *            bases; if false, callers are responsible for flushing.
 * @param tips
 *            source trees to be combined together. The merge base is not
 *            included in this set.
 * @return true if the merge was completed without conflicts; false if the
 *         merge strategy cannot handle this merge or there were conflicts
 *         preventing it from automatically resolving all paths.
 * @throws IncorrectObjectTypeException
 *             one of the input objects is not a commit, but the strategy
 *             requires it to be a commit.
 * @throws java.io.IOException
 *             one or more sources could not be read, or outputs could not
 *             be written to the Repository.
 */
public boolean merge(boolean flush, AnyObjectId... tips)
		throws IOException {
	sourceObjects = new RevObject[tips.length];
	for (int i = 0; i < tips.length; i++)
		sourceObjects[i] = walk.parseAny(tips[i]);

	sourceCommits = new RevCommit[sourceObjects.length];
	for (int i = 0; i < sourceObjects.length; i++) {
		try {
			sourceCommits[i] = walk.parseCommit(sourceObjects[i]);
		} catch (IncorrectObjectTypeException err) {
			sourceCommits[i] = null;
		}
	}

	sourceTrees = new RevTree[sourceObjects.length];
	for (int i = 0; i < sourceObjects.length; i++)
		sourceTrees[i] = walk.parseTree(sourceObjects[i]);

	try {
		boolean ok = mergeImpl();
		if (ok && flush)
			inserter.flush();
		return ok;
	} finally {
		if (flush)
			inserter.close();
		reader.close();
	}
}
 
Example 15
Source Project: onedev   Source File: Project.java    License: MIT License 5 votes vote down vote up
public InputStream getInputStream(BlobIdent ident) {
	try (RevWalk revWalk = new RevWalk(getRepository())) {
		ObjectId commitId = getObjectId(ident.revision, true);
		RevTree revTree = revWalk.parseCommit(commitId).getTree();
		TreeWalk treeWalk = TreeWalk.forPath(getRepository(), ident.path, revTree);
		if (treeWalk != null) {
			ObjectLoader objectLoader = treeWalk.getObjectReader().open(treeWalk.getObjectId(0));
			return objectLoader.openStream();
		} else {
			throw new ObjectNotFoundException("Unable to find blob path '" + ident.path + "' in revision '" + ident.revision + "'");
		}
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example 16
Source Project: onedev   Source File: BlobEditsTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testMoveFiles() throws IOException {
	createDir("client");
	addFileAndCommit("client/a.java", "a", "add a");
	addFileAndCommit("client/b.java", "b", "add b");
	
	createDir("server/src/com/example/a");
	createDir("server/src/com/example/b");
	addFileAndCommit("server/src/com/example/a/a.java", "a", "add a");
	addFileAndCommit("server/src/com/example/b/b.java", "b", "add b");
	
	String refName = "refs/heads/master";
	ObjectId oldCommitId = git.getRepository().resolve(refName);

	Set<String> oldPaths = Sets.newHashSet("server/src/com/example/a/a.java", 
			"server/src/com/example/b/b.java");
	Map<String, BlobContent> newBlobs = new HashMap<>();
	newBlobs.put("client/c.java", new BlobContent.Immutable("a".getBytes(), FileMode.REGULAR_FILE));
	newBlobs.put("client/d.java", new BlobContent.Immutable("a".getBytes(), FileMode.REGULAR_FILE));
	BlobEdits edits = new BlobEdits(oldPaths, newBlobs);
	ObjectId newCommitId = edits.commit(git.getRepository(), refName, oldCommitId, oldCommitId, user, "test rename");
	try (RevWalk revWalk = new RevWalk(git.getRepository())) {
		RevTree revTree = revWalk.parseCommit(newCommitId).getTree();
		assertNotNull(TreeWalk.forPath(git.getRepository(), "client/a.java", revTree));
		assertNotNull(TreeWalk.forPath(git.getRepository(), "client/b.java", revTree));
		assertNotNull(TreeWalk.forPath(git.getRepository(), "client/c.java", revTree));
		assertNotNull(TreeWalk.forPath(git.getRepository(), "client/d.java", revTree));
		assertNull(TreeWalk.forPath(git.getRepository(), "server/src/com/example/a", revTree));
		assertNull(TreeWalk.forPath(git.getRepository(), "server/src/com/example/b", revTree));
	}
}
 
Example 17
Source Project: centraldogma   Source File: CacheableCompareTreesCall.java    License: Apache License 2.0 5 votes vote down vote up
CacheableCompareTreesCall(Repository repo, @Nullable RevTree treeA, @Nullable RevTree treeB) {
    super(repo);

    this.treeA = treeA;
    this.treeB = treeB;
    hashCode = Objects.hash(treeA, treeB) * 31 + System.identityHashCode(repo);
}
 
Example 18
Source Project: centraldogma   Source File: GitRepository.java    License: Apache License 2.0 5 votes vote down vote up
private List<DiffEntry> blockingCompareTreesUncached(@Nullable RevTree treeA,
                                                     @Nullable RevTree treeB,
                                                     TreeFilter filter) {
    readLock();
    try (DiffFormatter diffFormatter = new DiffFormatter(null)) {
        diffFormatter.setRepository(jGitRepository);
        diffFormatter.setPathFilter(filter);
        return ImmutableList.copyOf(diffFormatter.scan(treeA, treeB));
    } catch (IOException e) {
        throw new StorageException("failed to compare two trees: " + treeA + " vs. " + treeB, e);
    } finally {
        readUnlock();
    }
}
 
Example 19
Source Project: centraldogma   Source File: GitRepository.java    License: Apache License 2.0 5 votes vote down vote up
private RevTree toTree(RevWalk revWalk, Revision revision) {
    final ObjectId commitId = commitIdDatabase.get(revision);
    try {
        return revWalk.parseCommit(commitId).getTree();
    } catch (IOException e) {
        throw new StorageException("failed to parse a commit: " + commitId, e);
    }
}
 
Example 20
Source Project: curiostack   Source File: CurioGenericCiPlugin.java    License: 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 21
Source Project: scava   Source File: ChurnRateCalculator.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public RevTree getTree(String commit) throws MissingObjectException, IncorrectObjectTypeException, IOException {

		// convert SHA into ObjectId
		ObjectId commitId = ObjectId.fromString(commit);

		try (RevWalk revWalk = new RevWalk(myrepo)) {
			RevCommit mycommit = revWalk.parseCommit(commitId);
			System.out.println("got the tree" + mycommit.getTree());
			return mycommit.getTree();
		}
	}
 
Example 22
Source Project: mdw   Source File: VersionControlGit.java    License: Apache License 2.0 5 votes vote down vote up
public ObjectStream getRemoteContentStream(String branch, String path) throws Exception {
    ObjectId id = localRepo.resolve("refs/remotes/origin/" + branch);
    try (ObjectReader reader = localRepo.newObjectReader();
            RevWalk walk = new RevWalk(reader)) {
        RevCommit commit = walk.parseCommit(id);
        RevTree tree = commit.getTree();
        TreeWalk treewalk = TreeWalk.forPath(reader, path, tree);
        if (treewalk != null) {
            return reader.open(treewalk.getObjectId(0)).openStream();
        }
        else {
            return null;
        }
    }
}
 
Example 23
Source Project: ParallelGit   Source File: TreeUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void existsTest() throws IOException {
  writeToCache("a/b.txt");
  RevTree tree = commitToMaster().getTree();
  assertTrue(TreeUtils.exists("a", tree, repo));
  assertTrue(TreeUtils.exists("a/b.txt", tree, repo));
  assertFalse(TreeUtils.exists("a/b", tree, repo));
}
 
Example 24
Source Project: ParallelGit   Source File: TreeUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void isDirectoryTest() throws IOException {
  writeToCache("a/b.txt");
  RevTree tree = commitToMaster().getTree();
  assertTrue(TreeUtils.isDirectory("a", tree, repo));
  assertFalse(TreeUtils.isDirectory("a/b.txt", tree, repo));
  assertFalse(TreeUtils.isDirectory("a/b", tree, repo));
}
 
Example 25
Source Project: ParallelGit   Source File: TreeUtilsNewTreeWalkTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void createTreeWalkForTree_shouldReturnNonRecursiveTreeWalk() throws IOException {
  writeMultipleToCache("/a.txt", "/b.txt", "/c/d.txt", "/c/e.txt", "/f/g.txt");
  RevTree tree = commitToMaster().getTree();
  TreeWalk treeWalk = TreeUtils.newTreeWalk(tree, repo);

  assertNextEntry(treeWalk, "a.txt");
  assertNextEntry(treeWalk, "b.txt");
  assertNextEntry(treeWalk, "c");
  assertNextEntry(treeWalk, "f");
  assertFalse(treeWalk.next());
}
 
Example 26
Source Project: ParallelGit   Source File: TreeUtilsNewTreeWalkTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void createTreeWalkForTreeAndPath_shouldReturnTreeWalkPointingToTheSpecifiedNode() throws IOException {
  writeMultipleToCache("/a.txt", "/b.txt", "/c/d.txt", "/c/e.txt", "/f/g.txt");
  RevTree tree = commitToMaster().getTree();
  TreeWalk treeWalk = TreeUtils.forPath("/c/d.txt", tree, repo);

  assertNotNull(treeWalk);
  assertEquals("d.txt", treeWalk.getNameString());
}
 
Example 27
Source Project: ParallelGit   Source File: TreeUtilsNewTreeWalkTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void createTreeWalkForTreeAndNonExistentPath_shouldReturnNull() throws IOException {
  writeMultipleToCache("/a.txt", "/b.txt", "/c/d.txt", "/c/e.txt", "/f/g.txt");
  RevTree tree = commitToMaster().getTree();
  TreeWalk treeWalk = TreeUtils.forPath("/non_existent_file.txt", tree, repo);

  assertNull(treeWalk);
}
 
Example 28
Source Project: GitFx   Source File: GitRepoMetaData.java    License: Apache License 2.0 5 votes vote down vote up
public ArrayList<String> getShortMessage() {
        for (RevCommit revision : walk) {
            shortMessage.add(revision.getShortMessage());
//[LOG]            logger.debug(revision.getShortMessage());
            DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
            df.setRepository(repository);
            df.setDiffComparator(RawTextComparator.DEFAULT);
            df.setDetectRenames(true);
            RevCommit parent = null;
            if(revision.getParentCount()!=0) {
                try {
                    parent = walk.parseCommit(revision.getParent(0).getId());
                    RevTree tree = revision.getTree();
                    List<DiffEntry> diffs = df.scan(parent.getTree(), revision.getTree());
                    for (DiffEntry diff : diffs) {
                        String changeType = diff.getChangeType().name();
                        if(changeType.equals(ADD)|| changeType.equals(MODIFY))
                        {
//[LOG]                            logger.debug(diff.getChangeType().name());
//[LOG]                            logger.debug(diff.getNewPath());
                            tempCommitHistory.add(diff.getNewPath());
                        }
                    }
                }catch (IOException ex) {
//[LOG]                    logger.debug("IOException", ex);
                }
            }
            commitSHA.add(commitCount,revision.name());
            commitHistory.add(commitCount++,new ArrayList<String>(tempCommitHistory));
            tempCommitHistory.clear();
        }
        walk.reset();
        return shortMessage;
    }
 
Example 29
Source Project: GitFx   Source File: GitRepoMetaData.java    License: 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 30
Source Project: coming   Source File: PGA.java    License: 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;
}