org.eclipse.jgit.treewalk.TreeWalk Java Examples

The following examples show how to use org.eclipse.jgit.treewalk.TreeWalk. 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: PullRequestUpdate.java    From onedev with MIT License 6 votes vote down vote up
public Collection<String> getChangedFiles() {
	if (changedFiles == null) {
		changedFiles = new HashSet<>();
		
		Repository repository = getRequest().getWorkProject().getRepository();
		try (	RevWalk revWalk = new RevWalk(repository);
				TreeWalk treeWalk = new TreeWalk(repository)) {
			RevCommit baseCommit = revWalk.parseCommit(ObjectId.fromString(getBaseCommitHash()));
			RevCommit headCommit = revWalk.parseCommit(ObjectId.fromString(getHeadCommitHash()));
			RevCommit comparisonBaseCommit = revWalk.parseCommit(getRequest().getComparisonBase(baseCommit, headCommit));
			treeWalk.addTree(headCommit.getTree());
			treeWalk.addTree(comparisonBaseCommit.getTree());
			treeWalk.setFilter(TreeFilter.ANY_DIFF);
			while (treeWalk.next())
				changedFiles.add(treeWalk.getPathString());
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	return changedFiles;
}
 
Example #3
Source File: Project.java    From onedev with MIT License 6 votes vote down vote up
public int getMode(String revision, @Nullable String path) {
	if (path != null) {
		RevCommit commit = getRevCommit(revision, true);
		try {
			TreeWalk treeWalk = TreeWalk.forPath(getRepository(), path, commit.getTree());
			if (treeWalk != null) {
				return treeWalk.getRawMode(0);
			} else {
				throw new ObjectNotFoundException("Unable to find blob path '" + path
						+ "' in revision '" + revision + "'");
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	} else {
		return FileMode.TREE.getBits();
	}
}
 
Example #4
Source File: JGitTemplate.java    From piper with 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 #5
Source File: BlobEditsTest.java    From onedev with 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 File: GitUtils.java    From blueocean-plugin with 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 File: VersionControlGit.java    From mdw with 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 #8
Source File: VersionControlGit.java    From mdw with 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 #9
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 #10
Source File: GitUtilsTest.java    From onedev with MIT License 6 votes vote down vote up
@Test
public void testMergeWithContentConflict() throws Exception {
	addFileAndCommit("initial", "", "initial");
	git.checkout().setCreateBranch(true).setName("dev").call();
	addFileAndCommit("dev1", "", "dev1");
	addFileAndCommit("conflict", "1", "dev2");
	git.checkout().setName("master").call();
	addFileAndCommit("master1", "", "master1");
	addFileAndCommit("conflict", "2", "master2");
	assertNull(GitUtils.merge(git.getRepository(), git.getRepository().resolve("master"), 
			git.getRepository().resolve("dev"), false, user, user, "merge commit", false));
	
	ObjectId mergeCommitId = GitUtils.merge(git.getRepository(), git.getRepository().resolve("master"), 
			git.getRepository().resolve("dev"), false, user, user, "merge commit", true);
	assertNotNull(mergeCommitId);
	
	try (	RevWalk revWalk = new RevWalk(git.getRepository())) {
		RevCommit mergeCommit = revWalk.parseCommit(mergeCommitId);
		TreeWalk treeWalk = TreeWalk.forPath(git.getRepository(), "conflict", mergeCommit.getTree());
		BlobIdent blobIdent = new BlobIdent(mergeCommit.name(), "conflict", FileMode.REGULAR_FILE.getBits());
		Blob blob = new Blob(blobIdent, treeWalk.getObjectId(0), treeWalk.getObjectReader());
		assertEquals("2", blob.getText().getContent());
	}
	
}
 
Example #11
Source File: AbstractGitRepositoryTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected List<String> listFilesInCommit(Repository repository) throws IOException, GitAPIException {
    List<String> result = new ArrayList<>();
    try (Git git = new Git(repository)) {
        RevCommit commit = git.log().add(git.getRepository().resolve(Constants.MASTER)).call().iterator().next();
        if (commit.getParentCount() > 0) {
            try (TreeWalk treeWalk = new TreeWalk(repository)) {
                treeWalk.addTree(commit.getParent(0).getTree());
                treeWalk.addTree(commit.getTree());
                treeWalk.setRecursive(true);
                List<DiffEntry> diff = DiffEntry.scan(treeWalk, false, null);
                for (DiffEntry diffEntry : diff) {
                    if(diffEntry.getChangeType() == DiffEntry.ChangeType.DELETE) {
                        result.add("-" + diffEntry.getOldPath());
                    } else {
                        result.add(diffEntry.getNewPath());
                    }
                }
            }
        }
    }
    Collections.sort(result);
    return result;
}
 
Example #12
Source File: CommitUtil.java    From SZZUnleashed with 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 #13
Source File: GfsTreeWalkTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Nonnull
private String[] toArrayWithLeadingSlash(TreeWalk tw) throws IOException {
  List<String> list = new ArrayList<>();
  while(tw.next())
    list.add("/" + tw.getPathString());
  String[] ret = new String[list.size()];
  return list.toArray(ret);
}
 
Example #14
Source File: GfsTreeWalkTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Nonnull
private TreeWalk forPath(String path) throws IOException {
  TreeWalk tw = prepareTreeWalk(false);
  PathFilter filter = PathFilter.create(path.charAt(0) == '/' ? path.substring(1) : path);
  tw.setFilter(filter);
  tw.setRecursive(false);
  while(tw.next()) {
    if(filter.isDone(tw))
      return tw;
    if(tw.isSubtree())
      tw.enterSubtree();
  }
  throw new IllegalStateException();
}
 
Example #15
Source File: GitBranch.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@NotNull
private Map<String, String> collectRename(@NotNull GitFile oldTree, @NotNull GitFile newTree) throws IOException {
  if (!repository.hasRenameDetection()) {
    return Collections.emptyMap();
  }
  final GitObject<ObjectId> oldTreeId = oldTree.getObjectId();
  final GitObject<ObjectId> newTreeId = newTree.getObjectId();
  if (oldTreeId == null || newTreeId == null || !Objects.equals(oldTreeId.getRepo(), newTreeId.getRepo())) {
    return Collections.emptyMap();
  }
  final TreeWalk tw = new TreeWalk(repository.getGit());
  tw.setRecursive(true);
  tw.setFilter(TreeFilter.ANY_DIFF);
  tw.addTree(oldTreeId.getObject());
  tw.addTree(newTreeId.getObject());

  final RenameDetector rd = new RenameDetector(repository.getGit());
  rd.addAll(DiffEntry.scan(tw));

  final Map<String, String> result = new HashMap<>();
  for (DiffEntry diff : rd.compute(tw.getObjectReader(), null)) {
    if (diff.getScore() >= rd.getRenameScore()) {
      result.put(StringHelper.normalize(diff.getNewPath()), StringHelper.normalize(diff.getOldPath()));
    }
  }
  return result;
}
 
Example #16
Source File: TreeUtilsNewTreeWalkTest.java    From ParallelGit with 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 #17
Source File: WalkCommitTreeAdapter.java    From coderadar with MIT License 5 votes vote down vote up
@Override
public void walkCommitTree(
    String projectRoot, String name, WalkTreeCommandInterface commandInterface)
    throws UnableToWalkCommitTreeException {
  try {
    Git git = Git.open(new File(projectRoot));
    ObjectId commitId = git.getRepository().resolve(name);

    RevWalk walk = new RevWalk(git.getRepository());
    RevCommit commit = walk.parseCommit(commitId);
    RevTree tree = commit.getTree();
    TreeWalk treeWalk = new TreeWalk(git.getRepository());
    treeWalk.addTree(tree);
    treeWalk.setRecursive(true);

    while (treeWalk.next()) {
      if (!treeWalk.getPathString().endsWith(".java")
          || treeWalk.getPathString().contains("build")
          || treeWalk.getPathString().contains("out")
          || treeWalk.getPathString().contains("classes")
          || treeWalk.getPathString().contains("node_modules")
          || treeWalk.getPathString().contains("test")) {
        continue;
      }
      commandInterface.walkMethod(treeWalk.getPathString());
    }
    git.close();
  } catch (IOException e) {
    throw new UnableToWalkCommitTreeException(e.getMessage());
  }
}
 
Example #18
Source File: GitContentRepository.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void unLockItem(String site, String path) {
    Repository repo = helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX);

    synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX)) {
        try (TreeWalk tw = new TreeWalk(repo)) {
            RevTree tree = helper.getTreeForLastCommit(repo);
            tw.addTree(tree); // tree ‘0’
            tw.setRecursive(false);
            tw.setFilter(PathFilter.create(path));

            if (!tw.next()) {
                return;
            }

            File repoRoot = repo.getWorkTree();
            Paths.get(repoRoot.getPath(), tw.getPathString());
            File file = new File(tw.getPathString());
            LockFile lock = new LockFile(file);
            lock.unlock();

            tw.close();

        } catch (IOException e) {
            logger.error("Error while unlocking file for site: " + site + " path: " + path, e);
        }
    }
}
 
Example #19
Source File: VersionControlGit.java    From mdw with 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 #20
Source File: GfsTreeWalkTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test
public void getObjectIdFromFileNode_shouldReturnTheBlobIdOfTheFile() throws IOException {
  initRepository();
  byte[] data = someBytes();
  writeToCache("/test_file.txt", data);
  commitToMaster();
  initGitFileSystem();

  TreeWalk tw = forPath("/test_file.txt");
  assertEquals(calculateBlobId(data), TreeUtils.getObjectId(tw));
}
 
Example #21
Source File: DifferentFiles.java    From gitflow-incremental-builder with MIT License 5 votes vote down vote up
private Set<Path> getBranchDiff() throws IOException {
    RevCommit base = getBranchCommit(configuration.baseBranch);
    final TreeWalk treeWalk = new TreeWalk(git.getRepository());
    try {
        treeWalk.addTree(base.getTree());
        treeWalk.addTree(resolveReference(base).getTree());
        treeWalk.setFilter(TreeFilter.ANY_DIFF);
        treeWalk.setRecursive(true);
        return getDiff(treeWalk, workTree);
    } finally {
        treeWalk.close();
    }
}
 
Example #22
Source File: GfsTreeWalkTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test
public void getFileModeFromDirectoryNode_shouldEqualTree() throws IOException {
  initGitFileSystem("/dir/some_file.txt");
  TreeWalk tw = forPath("/dir");
  assertEquals(TREE, tw.getFileMode(0));
  assertTrue(TreeUtils.isDirectory(tw));
}
 
Example #23
Source File: RepositoryS3.java    From github-bucket with ISC License 5 votes vote down vote up
@Override
public Status call() throws Exception {
    // Get S3 file list
    final List<S3ObjectSummary> files = getS3ObjectSummaries();
    final Iterator<S3ObjectSummary> iter = files.iterator();

    try (final TreeWalk walker = new TreeWalk(repository)) {
        walker.addTree(getRevTree());
        walker.setRecursive(false);

        // Walk all files
        while (walker.next()) {
            // Enter directories
            if (walker.isSubtree()) {
                walker.enterSubtree();
                continue;
            }
            // Only accept file types (no symlinks, no gitlinks) as they cannot be created in S3
            if ((walker.getFileMode().getBits() & TYPE_MASK) != TYPE_FILE) {
                continue;
            }
            // Here we have a real file!
            if (walk(iter, walker.getObjectId(0), walker.getPathString())) {
                LOG.info("Uploaded file: {}", walker.getPathString());
            }
        }
    }

    // Delete remaining objects, as they are not in the repo anymore
    for (S3ObjectSummary file : files) {
        LOG.info("Deleting file: {}", file.getKey());
        s3.deleteObject(file.getBucketName(), file.getKey());
    }
    return Status.SUCCESS;
}
 
Example #24
Source File: GitServiceImpl.java    From RefactoringMiner with MIT License 5 votes vote down vote up
public void fileTreeDiff(Repository repository, RevCommit currentCommit, List<String> javaFilesBefore, List<String> javaFilesCurrent, Map<String, String> renamedFilesHint) throws Exception {
       if (currentCommit.getParentCount() > 0) {
       	ObjectId oldTree = currentCommit.getParent(0).getTree();
        ObjectId newTree = currentCommit.getTree();
       	final TreeWalk tw = new TreeWalk(repository);
       	tw.setRecursive(true);
       	tw.addTree(oldTree);
       	tw.addTree(newTree);

       	final RenameDetector rd = new RenameDetector(repository);
       	rd.setRenameScore(80);
       	rd.addAll(DiffEntry.scan(tw));

       	for (DiffEntry diff : rd.compute(tw.getObjectReader(), null)) {
       		ChangeType changeType = diff.getChangeType();
       		String oldPath = diff.getOldPath();
       		String newPath = diff.getNewPath();
       		if (changeType != ChangeType.ADD) {
        		if (isJavafile(oldPath)) {
        			javaFilesBefore.add(oldPath);
        		}
        	}
       		if (changeType != ChangeType.DELETE) {
        		if (isJavafile(newPath)) {
        			javaFilesCurrent.add(newPath);
        		}
       		}
       		if (changeType == ChangeType.RENAME && diff.getScore() >= rd.getRenameScore()) {
       			if (isJavafile(oldPath) && isJavafile(newPath)) {
       				renamedFilesHint.put(oldPath, newPath);
       			}
       		}
       	}
       }
}
 
Example #25
Source File: LayoutHelper.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@NotNull
static String loadRepositoryId(@NotNull ObjectReader objectReader, ObjectId commit) throws IOException {
  RevWalk revWalk = new RevWalk(objectReader);
  TreeWalk treeWalk = TreeWalk.forPath(objectReader, ENTRY_UUID, revWalk.parseCommit(commit).getTree());
  if (treeWalk != null) {
    return GitRepository.loadContent(objectReader, treeWalk.getObjectId(0));
  }
  throw new FileNotFoundException(ENTRY_UUID);
}
 
Example #26
Source File: PathPatternFilter.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
public boolean matches(TreeWalk walker) {
    if (pathPatterns == null) {
        return true;
    }

    for (Pattern p: pathPatterns) {
        if (p.matcher(walker.getPathString()).matches()) {
            return true;
        }
    }

    return false;
}
 
Example #27
Source File: SMAGit.java    From salesforce-migration-assistant with MIT License 5 votes vote down vote up
/**
 * Returns the blob information for the file at the specified path and commit
 *
 * @param repoItem
 * @param commit
 * @return
 * @throws Exception
 */
public byte[] getBlob(String repoItem, String commit) throws Exception
{
    byte[] data;

    String parentPath = repository.getDirectory().getParent();

    ObjectId commitId = repository.resolve(commit);

    ObjectReader reader = repository.newObjectReader();
    RevWalk revWalk = new RevWalk(reader);
    RevCommit revCommit = revWalk.parseCommit(commitId);
    RevTree tree = revCommit.getTree();
    TreeWalk treeWalk = TreeWalk.forPath(reader, repoItem, tree);

    if (treeWalk != null)
    {
        data = reader.open(treeWalk.getObjectId(0)).getBytes();
    }
    else
    {
        throw new IllegalStateException("Did not find expected file '" + repoItem + "'");
    }

    reader.release();

    return data;
}
 
Example #28
Source File: GitContentRepository.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void lockItemForPublishing(String site, String path) {
    Repository repo = helper.getRepository(site, PUBLISHED);

    synchronized (repo) {
        try (TreeWalk tw = new TreeWalk(repo)) {
            RevTree tree = helper.getTreeForLastCommit(repo);
            tw.addTree(tree); // tree ‘0’
            tw.setRecursive(false);
            tw.setFilter(PathFilter.create(path));

            if (!tw.next()) {
                return;
            }

            File repoRoot = repo.getWorkTree();
            Paths.get(repoRoot.getPath(), tw.getPathString());
            File file = new File(tw.getPathString());
            LockFile lock = new LockFile(file);
            lock.lock();

            tw.close();

        } catch (IOException e) {
            logger.error("Error while locking file for site: " + site + " path: " + path, e);
        }
    }
}
 
Example #29
Source File: Utils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the current file/folder specified by the given TreeWalk lies under any of the given filters
 * @param treeWalk
 * @param filters
 * @return
 */
public static boolean isUnderOrEqual (TreeWalk treeWalk, Collection<PathFilter> filters) {
    boolean retval = filters.isEmpty();
    for (PathFilter filter : filters) {
        if (filter.include(treeWalk) && treeWalk.getPathString().length() >= filter.getPath().length()) {
            retval = true;
            break;
        }
    }
    return retval;
}
 
Example #30
Source File: GitClient.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
public String readFile(Repository repo, String commitId, String filePath) throws IOException {
	ObjectId oid = repo.resolve(commitId);
	RevCommit commit = repo.parseCommit(oid);
   	try (TreeWalk walk = TreeWalk.forPath(repo, filePath, commit.getTree())) {
           if (walk != null) {
               byte[] bytes = repo.open(walk.getObjectId(0)).getBytes();
               return new String(bytes, StandardCharsets.UTF_8);
           } else {
               throw new IllegalArgumentException(String.format("No file found for commitId=%s and filePath=%s", commitId, filePath));
           }
       }
}