Java Code Examples for org.eclipse.jgit.treewalk.TreeWalk

The following examples show how to use org.eclipse.jgit.treewalk.TreeWalk. 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
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 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: onedev   Source File: ResolveMerger.java    License: 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 4
Source Project: onedev   Source File: Project.java    License: 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 5
Source Project: onedev   Source File: PullRequestUpdate.java    License: 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 6
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 7
Source Project: onedev   Source File: GitUtilsTest.java    License: 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 8
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 9
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 10
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 11
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 12
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 13
Source Project: cf-butler   Source File: GitClient.java    License: 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));
           }
       }
}
 
Example 14
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 15
Source Project: writelatex-git-bridge   Source File: RepositoryObjectTreeWalker.java    License: MIT License 5 votes vote down vote up
private TreeWalk initTreeWalk(
        Repository repository,
        ObjectId objectId
) throws IOException {
    if (objectId == null) {
        return null;
    }
    RevWalk walk = new RevWalk(repository);
    TreeWalk treeWalk = new TreeWalk(repository);
    treeWalk.addTree(walk.parseCommit(objectId).getTree());
    treeWalk.setRecursive(true);
    return treeWalk;
}
 
Example 16
Source Project: onedev   Source File: TreeRevFilter.java    License: MIT License 5 votes vote down vote up
private void updateFollowFilter(ObjectId[] trees, DiffConfig cfg)
		throws MissingObjectException, IncorrectObjectTypeException,
		CorruptObjectException, IOException {
	TreeWalk tw = pathFilter;
	FollowFilter oldFilter = (FollowFilter) tw.getFilter();
	tw.setFilter(TreeFilter.ANY_DIFF);
	tw.reset(trees);

	List<DiffEntry> files = DiffEntry.scan(tw);
	RenameDetector rd = new RenameDetector(tw.getObjectReader(), cfg);
	rd.addAll(files);
	files = rd.compute();

	TreeFilter newFilter = oldFilter;
	for (DiffEntry ent : files) {
		if (isRename(ent) && ent.getNewPath().equals(oldFilter.getPath())) {
			newFilter = FollowFilter.create(ent.getOldPath(), cfg);
			RenameCallback callback = oldFilter.getRenameCallback();
			if (callback != null) {
				callback.renamed(ent);
				// forward the callback to the new follow filter
				((FollowFilter) newFilter).setRenameCallback(callback);
			}
			break;
		}
	}
	tw.setFilter(newFilter);
}
 
Example 17
Source Project: onedev   Source File: FollowFilter.java    License: MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public boolean include(TreeWalk walker)
		throws MissingObjectException, IncorrectObjectTypeException,
		IOException {
	return path.include(walker) && ANY_DIFF.include(walker);
}
 
Example 18
Source Project: onedev   Source File: CommitOptionPanel.java    License: 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 19
Source Project: onedev   Source File: PathQuery.java    License: 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 20
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 21
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 22
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 23
Source Project: git-merge-repos   Source File: SubtreeMerger.java    License: 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 24
Source Project: onedev   Source File: GitUtilsTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testRebaseWithoutConflicts() throws Exception {
	addFileAndCommit("initial", "", "initial");
	git.checkout().setCreateBranch(true).setName("dev").call();
	addFileAndCommit("dev1", "", "dev1");
	addFileAndCommit("dev2", "", "dev2");
	git.checkout().setName("master").call();
	addFileAndCommit("master1", "", "master1");
	addFileAndCommit("master2", "", "master2");
	ObjectId masterId = git.getRepository().resolve("master");
	ObjectId newCommitId = GitUtils.rebase(git.getRepository(), git.getRepository().resolve("dev"), masterId, user);
	try (	RevWalk revWalk = new RevWalk(git.getRepository());
			TreeWalk treeWalk = new TreeWalk(git.getRepository())) {
		RevCommit newCommit = revWalk.parseCommit(newCommitId);
		treeWalk.addTree(newCommit.getTree());
		Set<String> files = new HashSet<>();
		while (treeWalk.next()) {
			files.add(treeWalk.getPathString());
		}
		assertEquals(Sets.newHashSet("initial", "dev1", "dev2", "master1", "master2"), files);
		assertEquals("dev2", newCommit.getFullMessage());
		assertEquals(1, newCommit.getParentCount());
		
		treeWalk.reset();
		newCommit = revWalk.parseCommit(newCommit.getParent(0));
		treeWalk.addTree(newCommit.getTree());
		files = new HashSet<>();
		while (treeWalk.next()) {
			files.add(treeWalk.getPathString());
		}
		assertEquals(Sets.newHashSet("initial", "dev1", "master1", "master2"), files);
		assertEquals("dev1", newCommit.getFullMessage());
		assertEquals(1, newCommit.getParentCount());
		
		assertEquals(masterId, newCommit.getParent(0));
	}
}
 
Example 25
Source Project: studio   Source File: GitContentRepository.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void unLockItemForPublishing(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.unlock();

            tw.close();

        } catch (IOException e) {
            logger.error("Error while unlocking file for site: " + site + " path: " + path, e);
        }
    }
}
 
Example 26
Source Project: onedev   Source File: GitUtilsTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testMergeWithoutConflicts() throws Exception {
	addFileAndCommit("initial", "", "initial");
	git.checkout().setCreateBranch(true).setName("dev").call();
	addFileAndCommit("dev1", "", "dev1");
	addFileAndCommit("dev2", "", "dev2");
	git.checkout().setName("master").call();
	addFileAndCommit("master1", "", "master1");
	addFileAndCommit("master2", "", "master2");
	ObjectId masterId = git.getRepository().resolve("master");
	ObjectId devId = git.getRepository().resolve("dev");
	ObjectId mergeCommitId = GitUtils.merge(git.getRepository(), masterId, devId, false, 
			user, user, "merge commit", false);
	try (	RevWalk revWalk = new RevWalk(git.getRepository());
			TreeWalk treeWalk = new TreeWalk(git.getRepository())) {
		RevCommit mergeCommit = revWalk.parseCommit(mergeCommitId);
		treeWalk.addTree(mergeCommit.getTree());
		Set<String> files = new HashSet<>();
		while (treeWalk.next()) {
			files.add(treeWalk.getPathString());
		}
		assertEquals(Sets.newHashSet("initial", "dev1", "dev2", "master1", "master2"), files);
		assertEquals(2, mergeCommit.getParentCount());
		assertEquals(masterId, mergeCommit.getParent(0));
		assertEquals(devId, mergeCommit.getParent(1));
	}
}
 
Example 27
Source Project: ParallelGit   Source File: TreeSnapshot.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
public static TreeSnapshot load(ObjectId id, ObjectReader reader) throws IOException {
  SortedMap<String, GitFileEntry> ret = new TreeMap<>();
  try(TreeWalk tw = TreeUtils.newTreeWalk(id, reader)) {
    while(tw.next()) ret.put(tw.getNameString(), newEntry(tw));
  }
  return new TreeSnapshot(ret, id);
}
 
Example 28
Source Project: onedev   Source File: GitUtilsTest.java    License: 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 29
Source Project: netbeans   Source File: GitRevisionInfo.java    License: Apache License 2.0 5 votes vote down vote up
private void listFiles() throws GitException {
    try (RevWalk revWalk = new RevWalk(repository);
        TreeWalk walk = new TreeWalk(repository)) {
        List<GitFileInfo> result;
        walk.reset();
        walk.setRecursive(true);
        RevCommit parentCommit = null;
        if (revCommit.getParentCount() > 0) {
            for (RevCommit commit : revCommit.getParents()) {
                revWalk.markStart(revWalk.lookupCommit(commit));
            }
            revWalk.setRevFilter(RevFilter.MERGE_BASE);
            Iterator<RevCommit> it = revWalk.iterator();
            if (it.hasNext()) {
                parentCommit = it.next();
            }
            if (parentCommit != null) {
                walk.addTree(parentCommit.getTree().getId());
            }
        }
        walk.addTree(revCommit.getTree().getId());
        walk.setFilter(AndTreeFilter.create(TreeFilter.ANY_DIFF, PathFilter.ANY_DIFF));
        if (parentCommit != null) {
            result = Utils.getDiffEntries(repository, walk, GitClassFactoryImpl.getInstance());
        } else {
            result = new ArrayList<>();
            while (walk.next()) {
                result.add(new GitFileInfo(new File(repository.getWorkTree(), walk.getPathString()), walk.getPathString(), GitFileInfo.Status.ADDED, null, null));
            }
        }
        this.modifiedFiles = result.toArray(new GitFileInfo[result.size()]);
    } catch (IOException ex) {
        throw new GitException(ex);
    }
}
 
Example 30
Source Project: netbeans   Source File: CherryPickCommand.java    License: 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;
        }
    };
}