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

The following examples show how to use org.eclipse.jgit.treewalk.TreeWalk#getPathString() . 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: GitCommit.java    From Getaviz with 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 2
Source File: GitConnector.java    From compiler with Apache License 2.0 6 votes vote down vote up
public List<String> getSnapshot(String commit) {
	ArrayList<String> snapshot = new ArrayList<String>();
	TreeWalk tw = new TreeWalk(repository);
	tw.reset();
	try {
		RevCommit rc = revwalk.parseCommit(repository.resolve(commit));
		tw.addTree(rc.getTree());
		tw.setRecursive(true);
		while (tw.next()) {
			if (!tw.isSubtree()) {
				String path = tw.getPathString();
				snapshot.add(path);
			}
		}
	} catch (IOException e) {
		System.err.println(e.getMessage());
	}
	tw.close();
	return snapshot;
}
 
Example 3
Source File: CommitOptionPanel.java    From onedev with MIT License 5 votes vote down vote up
private BlobChange getChange(TreeWalk treeWalk, RevCommit oldCommit, RevCommit newCommit) {
	DiffEntry.ChangeType changeType = DiffEntry.ChangeType.MODIFY;
	BlobIdent oldBlobIdent;
	if (!treeWalk.getObjectId(0).equals(ObjectId.zeroId())) {
		oldBlobIdent = new BlobIdent(oldCommit.name(), treeWalk.getPathString(), treeWalk.getRawMode(0));
	} else {
		oldBlobIdent = new BlobIdent(oldCommit.name(), null, FileMode.TREE.getBits());
		changeType = DiffEntry.ChangeType.ADD;
	}
	
	BlobIdent newBlobIdent;
	if (!treeWalk.getObjectId(1).equals(ObjectId.zeroId())) {
		newBlobIdent = new BlobIdent(newCommit.name(), treeWalk.getPathString(), treeWalk.getRawMode(1));
	} else {
		newBlobIdent = new BlobIdent(newCommit.name(), null, FileMode.TREE.getBits());
		changeType = DiffEntry.ChangeType.DELETE;
	}
	
	return new BlobChange(changeType, oldBlobIdent, newBlobIdent, WhitespaceOption.DEFAULT) {

		@Override
		public Blob getBlob(BlobIdent blobIdent) {
			return context.getProject().getBlob(blobIdent, true);
		}

	};
}
 
Example 4
Source File: PathQuery.java    From onedev with MIT License 5 votes vote down vote up
@Override
public void collect(IndexSearcher searcher, TreeWalk treeWalk, List<QueryHit> hits) {
	String blobPath = treeWalk.getPathString();
	LinearRange range = PathUtils.matchSegments(blobPath, match, true);
	if (range != null) {
		hits.add(new PathHit(blobPath, range));
	}
}
 
Example 5
Source File: GitConnector.java    From compiler with Apache License 2.0 5 votes vote down vote up
@Override
public List<ChangedFile> buildHeadSnapshot() {
	final List<ChangedFile> snapshot = new ArrayList<ChangedFile>();
	TreeWalk tw = new TreeWalk(repository);
	tw.reset();
	try {
		RevCommit rc = revwalk.parseCommit(repository.resolve(Constants.HEAD));
		tw.addTree(rc.getTree());
		tw.setRecursive(true);
		while (tw.next()) {
			if (!tw.isSubtree()) {
				String path = tw.getPathString();
				ChangedFile.Builder cfb = ChangedFile.newBuilder();
				cfb.setChange(ChangeKind.UNKNOWN);
				cfb.setName(path);
				cfb.setKind(FileKind.OTHER);
				cfb.setKey(0);
				cfb.setAst(false);
				GitCommit gc = new GitCommit(this, repository, revwalk, projectName);
				gc.filePathGitObjectIds.put(path, tw.getObjectId(0));
				gc.processChangeFile(cfb);
				snapshot.add(cfb.build());
			}
		}
	} catch (Exception e) {
		System.err.println(e.getMessage());
	}
	tw.close();
	
	return snapshot;
}
 
Example 6
Source File: GitCommit.java    From compiler with Apache License 2.0 5 votes vote down vote up
void updateChangedFiles(RevCommit rc) {
	if (rc.getParentCount() == 0) {
		TreeWalk tw = new TreeWalk(repository);
		tw.reset();
		try {
			tw.addTree(rc.getTree());
			tw.setRecursive(true);
			while (tw.next()) {
				if (!tw.isSubtree()) {
					String path = tw.getPathString();
					getChangedFile(path, ChangeKind.ADDED);
					filePathGitObjectIds.put(path, tw.getObjectId(0));
				}
			}
		} catch (IOException e) {
			if (debug)
				System.err.println(e.getMessage());
		}
		tw.close();
	} else {
		parentIndices = new int[rc.getParentCount()];
		for (int i = 0; i < rc.getParentCount(); i++) {
			int parentIndex = connector.revisionMap.get(rc.getParent(i).getName());
			// merged commit in git only store diffs between the first parent and the child
			if (i == 0)
				updateChangedFiles(rc.getParent(i), parentIndex, rc);
			parentIndices[i] = parentIndex;
		}
	}
}
 
Example 7
Source File: SMAGit.java    From salesforce-migration-assistant with MIT License 5 votes vote down vote up
/**
 * Replicates ls-tree for the current commit.
 *
 * @return Map containing the full path and the data for all items in the repository.
 * @throws IOException
 */
public Map<String, byte[]> getAllMetadata() throws Exception
{
    Map<String, byte[]> contents = new HashMap<String, byte[]>();
    ObjectReader reader = repository.newObjectReader();
    ObjectId commitId = repository.resolve(curCommit);
    RevWalk revWalk = new RevWalk(reader);
    RevCommit commit = revWalk.parseCommit(commitId);
    RevTree tree = commit.getTree();
    TreeWalk treeWalk = new TreeWalk(reader);
    treeWalk.addTree(tree);
    treeWalk.setRecursive(false);

    while (treeWalk.next())
    {
        if (treeWalk.isSubtree())
        {
            treeWalk.enterSubtree();
        }
        else
        {
            String member = treeWalk.getPathString();
            if (member.contains(SOURCEDIR))
            {
                byte[] data = getBlob(member, curCommit);
                contents.put(member, data);
            }
        }
    }

    reader.release();

    return contents;
}
 
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: AddTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testAddMixedLineEndings () throws Exception {
    File f = new File(workDir, "f");
    String content = "";
    for (int i = 0; i < 10000; ++i) {
        content += i + "\r\n";
    }
    write(f, content);
    File[] files = new File[] { f };
    GitClient client = getClient(workDir);
    client.add(files, NULL_PROGRESS_MONITOR);
    client.commit(files, "commit", null, null, NULL_PROGRESS_MONITOR);
    
    Map<File, GitStatus> statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, workDir, f, true, Status.STATUS_NORMAL, Status.STATUS_NORMAL, Status.STATUS_NORMAL, false);
    
    // lets turn autocrlf on
    StoredConfig cfg = repository.getConfig();
    cfg.setString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, "true");
    cfg.save();
    
    // when this starts failing, remove the work around
    ObjectInserter inserter = repository.newObjectInserter();
    TreeWalk treeWalk = new TreeWalk(repository);
    treeWalk.setFilter(PathFilterGroup.createFromStrings("f"));
    treeWalk.setRecursive(true);
    treeWalk.reset();
    treeWalk.addTree(new FileTreeIterator(repository));
    while (treeWalk.next()) {
        String path = treeWalk.getPathString();
        assertEquals("f", path);
        WorkingTreeIterator fit = treeWalk.getTree(0, WorkingTreeIterator.class);
        try (InputStream in = fit.openEntryStream()) {
            inserter.insert(Constants.OBJ_BLOB, fit.getEntryLength(), in);
            fail("this should fail, remove the work around");
        } catch (EOFException ex) {
            assertEquals("Input did not match supplied length. 10.000 bytes are missing.", ex.getMessage());
        } finally {
            inserter.close();
        }
        break;
    }
    
    // no err should occur
    write(f, content + "hello");
    statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, workDir, f, true, Status.STATUS_NORMAL, Status.STATUS_MODIFIED, Status.STATUS_MODIFIED, false);
    client.add(files, NULL_PROGRESS_MONITOR);
    statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, workDir, f, true, Status.STATUS_MODIFIED, Status.STATUS_NORMAL, Status.STATUS_MODIFIED, false);
    client.commit(files, "message", null, null, NULL_PROGRESS_MONITOR);
    statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, workDir, f, true, Status.STATUS_NORMAL, Status.STATUS_NORMAL, Status.STATUS_NORMAL, false);
}
 
Example 10
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);
    }
}