Java Code Examples for org.eclipse.jgit.treewalk.TreeWalk#getObjectId()

The following examples show how to use org.eclipse.jgit.treewalk.TreeWalk#getObjectId() . 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: GitUtils.java    From onedev with MIT License 6 votes vote down vote up
@Nullable
public static List<String> readLines(Repository repository, RevCommit commit, String path, 
		WhitespaceOption whitespaceOption) {
	try {
		TreeWalk treeWalk = TreeWalk.forPath(repository, path, commit.getTree());
		if (treeWalk != null) {
			ObjectId blobId = treeWalk.getObjectId(0);
			ObjectReader objectReader = treeWalk.getObjectReader();
			BlobIdent blobIdent = new BlobIdent(commit.name(), path, FileMode.REGULAR_FILE.getBits()); 
			Blob blob = new Blob(blobIdent, blobId, objectReader);
			List<String> normalizedLines = new ArrayList<>();
			for (String line: Preconditions.checkNotNull(blob.getText()).getLines()) {
				normalizedLines.add(whitespaceOption.process(line));
			}
			return normalizedLines;
		} else {
			return null;
		}
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example 2
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 3
Source File: GitUtilsTest.java    From onedev with MIT License 6 votes vote down vote up
@Test
public void testMergeWithDeletionAndModificationConflict() throws Exception {
	addFileAndCommit("file", "", "initial commit");
	git.checkout().setCreateBranch(true).setName("dev").call();
	removeFileAndCommit("file", "remove file");
	git.checkout().setName("master").call();
	addFileAndCommit("file", "1", "master");

	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(), "file", mergeCommit.getTree());
		BlobIdent blobIdent = new BlobIdent(mergeCommit.name(), "file", FileMode.REGULAR_FILE.getBits());
		Blob blob = new Blob(blobIdent, treeWalk.getObjectId(0), treeWalk.getObjectReader());
		assertEquals("1", blob.getText().getContent());
	}
}
 
Example 4
Source File: PGA.java    From coming with 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 5
Source File: GitUtilsTest.java    From onedev with MIT License 5 votes vote down vote up
@Test
public void testMergeWithLinkAndLinkConflict() throws Exception {
	File tempDir;
	
	tempDir = FileUtils.createTempDir();
	try (InputStream is = Resources.getResource(GitUtilsTest.class, "git-conflict-link-link.zip").openStream()) {
		ZipUtils.unzip(is, tempDir);
		try (Git git = Git.open(tempDir)) {
			ObjectId mergeCommitId;

			mergeCommitId = GitUtils.merge(git.getRepository(), git.getRepository().resolve("master"), 
					git.getRepository().resolve("dev"), false, user, user, "merge commit", false);
			
			assertNull(mergeCommitId);

			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(), "lib", mergeCommit.getTree());
				assertTrue(treeWalk != null && treeWalk.getFileMode(0) == FileMode.GITLINK);
				treeWalk = TreeWalk.forPath(git.getRepository(), ".gitmodules", mergeCommit.getTree());
				BlobIdent blobIdent = new BlobIdent(mergeCommit.name(), ".gitmodules", FileMode.GITLINK.getBits());
				Blob blob = new Blob(blobIdent, treeWalk.getObjectId(0), treeWalk.getObjectReader());
				assertTrue(blob.getText().getContent().trim().endsWith("/home/robin/temp/lib"));
			}
		}
	} finally {
		deleteDir(tempDir, 3);
	}
}
 
Example 6
Source File: Commit.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Return body of the commit
 *
 * @return body of the commit as an Object Stream
 * @throws IOException
 *             when reading the object failed
 */
public ObjectStream toObjectStream() throws IOException {
	final TreeWalk w = TreeWalk.forPath(db, pattern, revCommit.getTree());
	if (w == null) {
		return null;
	}
	ObjectId blobId = w.getObjectId(0);
	return db.open(blobId, Constants.OBJ_BLOB).openStream();
}
 
Example 7
Source File: GitCommit.java    From Getaviz with Apache License 2.0 4 votes vote down vote up
private VersionedFile readToByteArray(TreeWalk treeWalk) throws IOException {
	ObjectId objectId = treeWalk.getObjectId(0);
	ObjectLoader loader = repository.open(objectId);
	return new ByteArrayVersionedFile(IOUtils.toByteArray(loader.openStream()));
}
 
Example 8
Source File: SymbolQuery.java    From onedev with MIT License 4 votes vote down vote up
@Override
public void collect(IndexSearcher searcher, TreeWalk treeWalk, List<QueryHit> hits) {
	String blobPath = treeWalk.getPathString();
	ObjectId blobId = treeWalk.getObjectId(0);
	
	List<Symbol> symbols = OneDev.getInstance(SearchManager.class).getSymbols(searcher, blobId, blobPath);
	if (symbols != null) {
		for (Symbol symbol: symbols) {
			if (hits.size() < getCount()) {
				if ((primary==null || primary.booleanValue() == symbol.isPrimary()) 
						&& symbol.getName() != null 
						&& symbol.isSearchable()
						&& (local == null || local.booleanValue() == symbol.isLocalInHierarchy())) {
					String normalizedTerm;
					if (!caseSensitive)
						normalizedTerm = term.toLowerCase();
					else
						normalizedTerm = term;
					
					String normalizedSymbolName;
					if (!caseSensitive)
						normalizedSymbolName = symbol.getName().toLowerCase();
					else
						normalizedSymbolName = symbol.getName();
					
					String normalizedExcludeTerm;
					if (excludeTerm != null) {
						if (!caseSensitive)
							normalizedExcludeTerm = excludeTerm.toLowerCase();
						else
							normalizedExcludeTerm = excludeTerm;
					} else {
						normalizedExcludeTerm = null;
					}
					if (WildcardUtils.matchString(normalizedTerm, normalizedSymbolName)
							&& (normalizedExcludeTerm == null || !normalizedSymbolName.equals(normalizedExcludeTerm))
							&& (excludeBlobPath == null || !excludeBlobPath.equals(blobPath))) {
						LinearRange match = WildcardUtils.rangeOfMatch(normalizedTerm, normalizedSymbolName);
						hits.add(new SymbolHit(blobPath, symbol, match));
					}
				}
			} else {
				break;
			}
		}
	}
}
 
Example 9
Source File: Project.java    From onedev with MIT License 4 votes vote down vote up
/**
 * Read blob content and cache result in repository in case the same blob 
 * content is requested again. 
 * 
 * We made this method thread-safe as we are using ForkJoinPool to calculate 
 * diffs of multiple blob changes concurrently, and this method will be 
 * accessed concurrently in that special case.
 * 
 * @param blobIdent
 * 			ident of the blob
 * @return
 * 			blob of specified blob ident
 * @throws
 * 			ObjectNotFoundException if blob of specified ident can not be found in repository 
 * 			
 */
@Nullable
public Blob getBlob(BlobIdent blobIdent, boolean mustExist) {
	Preconditions.checkArgument(blobIdent.revision!=null && blobIdent.path!=null && blobIdent.mode!=null, 
			"Revision, path and mode of ident param should be specified");
	
	Optional<Blob> blob = getBlobCache().get(blobIdent);
	if (blob == null) {
		try (RevWalk revWalk = new RevWalk(getRepository())) {
			ObjectId revId = getObjectId(blobIdent.revision, mustExist);		
			if (revId != null) {
				RevCommit commit = GitUtils.parseCommit(revWalk, revId);
				if (commit != null) {
					RevTree revTree = commit.getTree();
					TreeWalk treeWalk = TreeWalk.forPath(getRepository(), blobIdent.path, revTree);
					if (treeWalk != null) {
						ObjectId blobId = treeWalk.getObjectId(0);
						if (blobIdent.isGitLink()) {
							String url = getSubmodules(blobIdent.revision).get(blobIdent.path);
							if (url == null) {
								if (mustExist)
									throw new ObjectNotFoundException("Unable to find submodule '" + blobIdent.path + "' in .gitmodules");
								else
									blob = Optional.absent();
							} else {
								String hash = blobId.name();
								blob = Optional.of(new Blob(blobIdent, blobId, new Submodule(url, hash).toString().getBytes()));
							}
						} else if (blobIdent.isTree()) {
							throw new NotFileException("Path '" + blobIdent.path + "' is a tree");
						} else {
							blob = Optional.of(new Blob(blobIdent, blobId, treeWalk.getObjectReader()));
						}
					} 
				} 				
			} 
			if (blob == null) {
				if (mustExist)
					throw new ObjectNotFoundException("Unable to find blob ident: " + blobIdent);
				else 
					blob = Optional.absent();
			}
			getBlobCache().put(blobIdent, blob);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	return blob.orNull();
}
 
Example 10
Source File: TreeUtils.java    From ParallelGit with Apache License 2.0 4 votes vote down vote up
@Nullable
public static ObjectId getObjectId(TreeWalk tw) {
  return tw.getObjectId(0);
}
 
Example 11
Source File: TreeUtils.java    From ParallelGit with Apache License 2.0 4 votes vote down vote up
@Nullable
public static ObjectId getObjectId(TreeWalk tw) {
  return tw.getObjectId(0);
}
 
Example 12
Source File: GitProctorCore.java    From proctor with Apache License 2.0 4 votes vote down vote up
@Override
@Nullable
public <C> C getFileContents(
        final Class<C> c,
        final String[] path,
        @Nullable final C defaultValue,
        final String revision
) throws StoreException.ReadException, JsonProcessingException {
    try {
        if (!ObjectId.isId(revision)) {
            throw new StoreException.ReadException("Malformed id " + revision);
        }
        final ObjectId blobOrCommitId = ObjectId.fromString(revision);

        final ObjectLoader loader = git.getRepository().open(blobOrCommitId);

        if (loader.getType() == Constants.OBJ_COMMIT) {
            // look up the file at this revision
            final RevCommit commit = RevCommit.parse(loader.getCachedBytes());

            final TreeWalk treeWalk2 = new TreeWalk(git.getRepository());
            treeWalk2.addTree(commit.getTree());
            treeWalk2.setRecursive(true);
            final String joinedPath = String.join("/", path);
            treeWalk2.setFilter(PathFilter.create(joinedPath));

            if (!treeWalk2.next()) {
                // it did not find expected file `joinPath` so return default value
                return defaultValue;
            }
            final ObjectId blobId = treeWalk2.getObjectId(0);
            return getFileContents(c, blobId);
        } else if (loader.getType() == Constants.OBJ_BLOB) {
            return getFileContents(c, blobOrCommitId);
        } else {
            throw new StoreException.ReadException("Invalid Object Type " + loader.getType() + " for id " + revision);
        }
    } catch (final IOException e) {
        throw new StoreException.ReadException(e);
    }
}
 
Example 13
Source File: GitProctorCore.java    From proctor with Apache License 2.0 4 votes vote down vote up
@Override
public TestVersionResult determineVersions(final String fetchRevision) throws StoreException.ReadException {
    try {
        final RevWalk walk = new RevWalk(git.getRepository());
        final ObjectId commitId = ObjectId.fromString(fetchRevision);
        final RevCommit headTree = walk.parseCommit(commitId);
        final RevTree tree = headTree.getTree();

        // now use a TreeWalk to iterate over all files in the Tree recursively
        // you can set Filters to narrow down the results if needed
        final TreeWalk treeWalk = new TreeWalk(git.getRepository());
        treeWalk.addTree(tree);
        treeWalk.setFilter(AndTreeFilter
            .create(PathFilter.create(testDefinitionsDirectory), PathSuffixFilter.create("definition.json")));
        treeWalk.setRecursive(true);

        final List<TestVersionResult.Test> tests = Lists.newArrayList();
        while (treeWalk.next()) {
            final ObjectId id = treeWalk.getObjectId(0);
            // final RevTree revTree = walk.lookupTree(id);

            final String path = treeWalk.getPathString();
            final String[] pieces = path.split("/");
            final String testname = pieces[pieces.length - 2]; // tree / parent directory name

            // testname, blobid pair
            // note this is the blobid hash - not a commit hash
            // RevTree.id and RevBlob.id
            tests.add(new TestVersionResult.Test(testname, id.name()));
        }

        walk.dispose();
        return new TestVersionResult(
                tests,
                new Date(Long.valueOf(headTree.getCommitTime()) * 1000 /* convert seconds to milliseconds */),
                determineAuthorId(headTree),
                headTree.toObjectId().getName(),
                headTree.getFullMessage()
        );
    } catch (final IOException e) {
        throw new StoreException.ReadException(e);
    }
}